@promptctl/cc-candybar 1.127.1 → 1.128.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -39,23 +39,23 @@ import{createRequire as e}from"node:module";import t from"node:process";import{j
39
39
  `).join(`${n}${t}`)}function Hl(e,t,n){let[r,...i]=e,a=i.length===0?t:`{\n ${Vl(Hl(i,t,n),` `,`
40
40
  `)}${n.trailingComma}\n}`;return`${n.key(r)}: ${a}`}function Ul(e,t,n,r){return e.slice(0,t)+r+e.slice(n)}function Wl(e,t){return e.lastIndexOf(`
41
41
  `,t-1)+1}function Gl(e){return/^[ \t]*$/.test(e)}function Kl(e,t){let n=Wl(e,t);return/^[ \t]*/.exec(e.slice(n))[0]}function ql(e,t){return Gl(e.slice(Wl(e,t),t))}const Jl=/(?:\/\/[^\n]*?)?(\r\n|\n|$)/y;function Yl(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n++;let r=e[n]===`,`?n+1:-1;for(r!==-1&&(n=r);n<e.length&&(e[n]===` `||e[n]===` `);)n++;Jl.lastIndex=n;let i=Jl.exec(e);if(i===null)return{commaEnd:r,line:null};let a=n+i[0].length;return{commaEnd:r,line:{at:a-i[1].length,next:a}}}function Xl(e,t){let{commaEnd:n,line:r}=Yl(e,t.end);if(ql(e,t.start)&&r!==null)return Ul(e,Wl(e,t.start),r.next,``);if(n!==-1){let r=n;for(;r<e.length&&e[r]===` `;)r++;return Ul(e,t.start,r,``)}let i=t.start;for(;i>0&&(e[i-1]===` `||e[i-1]===` `);)i--;return e[i-1]===`,`?Ul(e,i-1,t.end,``):Ul(e,t.start,t.end,``)}function Zl(e,t,n,r,i){let a=n.commaEnd!==-1,o=a?e:Ul(e,t.end,t.end,`,`),s=n.line.at+ +!a,c=Bl(e);return Ul(o,s,s,`${c}${i}${Vl(r,i,c)}${a?`,`:``}`)}function Ql(e,t,n,r){let i=t.kind===`object`?t.entries:t.elements,a=i[i.length-1],o=Kl(e,t.span.start);if(a===void 0){let i=o+` `,a=Bl(e);return Ul(e,t.span.start+1,t.span.end-1,`${a}${i}${Vl(n,i,a)}${r.trailingComma}${a}${o}`)}let{commaEnd:s,line:c}=Yl(e,a.span.end);if(ql(e,a.span.start)&&c!==null){let t=e.slice(Wl(e,a.span.start),a.span.start);return Zl(e,a.span,{commaEnd:s,line:c},n,t)}let l=s===-1?a.span.end:s;return Ul(e,l,l,`${s===-1?`, `:` `}${n}${s===-1?``:`,`}`)}function $l(e,t,n,r){if(t.length===0)throw new Cl(`setValue needs a non-empty path`,0);if(/^\s*$/.test(e)){let i=Bl(e);return`{${i} ${Vl(Hl(t,n,r),` `,i)}${r.trailingComma}${i}}${i}`}return eu(e,kl(e),t,n,r)}function eu(e,t,n,r,i){let a=t;for(let t=0;t<n.length;t++){if(a.kind!==`object`)throw new Cl(`cannot set ${n.join(`.`)}: ${n.slice(0,t).join(`.`)||`the document`} is not an object`,a.span.start);let o=Al(a,n[t]);if(o===void 0)return Ql(e,a,Hl(n.slice(t),r,i),i);if(t===n.length-1){let t=Kl(e,o.keySpan.start);return Ul(e,o.value.span.start,o.value.span.end,Vl(r,t,Bl(e)))}a=o.value}throw new Cl(`unreachable: path exhausted`,0)}function tu(e,t,n=0){if(t.length===0)throw new Cl(`deleteValue needs a non-empty path`,0);if(/^\s*$/.test(e))return e;let r=t.slice(0,-1),i=jl(kl(e),r),a=i===void 0?void 0:Al(i,t[t.length-1]);if(a===void 0||i?.kind!==`object`)return e;let o=Xl(e,a.span);return r.length>n&&i.entries.length===1?tu(o,r,n):o}const nu=[`h`,`v`,`children`];function ru(e){if(e.kind===`string`)return e.value;if(e.kind!==`object`)return;let t=Al(e,`seg`)?.value,n=Al(e,`kind`)?.value,r=Al(e,`name`)?.value,i=t?.kind===`string`?t.value:n?.kind===`string`&&n.value===`segment`&&r?.kind===`string`?r.value:void 0;if(i===void 0)return;let a=Al(e,`id`)?.value;return a?.kind===`string`?a.value:i}function iu(e){return e.kind===`object`?nu.map(t=>Al(e,t)?.value).filter(e=>e?.kind===`array`):[]}function au(e){let t=Al(e,`rows`)?.value;return t?.kind===`object`?t.entries:null}function ou(e){if(e.kind!==`object`)return!0;let t=au(e);return t===null||t.length>0||e.entries.some(e=>e.key!==`rows`)}function*su(e,t){yield{node:e,bareAt:t};for(let t of iu(e))for(let e of t.elements)yield*su(e,null);for(let n of au(e)??[])yield*su(n.value,t===null?null:[...t,`rows`,n.key])}function cu(e,t){for(let{node:n}of su(e,null))if(ru(n)===t)return!0;return!1}function lu(e,t,n){let r=jl(kl(e),t);if(r===void 0)return null;for(let{node:i,bareAt:a}of su(r,t))if(ru(i)===n)return a===null?{text:e,ref:i}:lu($l(e,a,`{ h: [${Ml(e,i)}] }`,Ll),t,n);return null}function uu(e,t,n){let r=lu(e,t,n);return r===null?null:Xl(r.text,r.ref.span)}function du(e,t,n,r,i){let a=lu(e,t,r);if(a===null)return null;let{text:o,ref:s}=a,c=n.id===void 0?JSON.stringify(n.seg):`{ seg: ${JSON.stringify(n.seg)}, id: ${JSON.stringify(n.id)} }`,{commaEnd:l,line:u}=Yl(o,s.span.end);if(ql(o,s.span.start)&&u!==null){let e=o.slice(Wl(o,s.span.start),s.span.start);return i===`after`?Zl(o,s.span,{commaEnd:l,line:u},c,e):Ul(o,s.span.start,s.span.start,`${c},${Bl(o)}${e}`)}let d=Ml(o,s),f=i===`before`?`${c}, ${d}`:`${d}, ${c}`;return Ul(o,s.span.start,s.span.end,f)}function fu(e,t,n,r,i){let a=lu(e,t,n);if(a===null)return null;let{text:o,ref:s}=a,c=`{ ${Il(r)}: ${i} }`;return s.kind===`string`?Ul(o,s.span.start,s.span.end,`{ seg: ${JSON.stringify(s.value)}, settings: ${c} }`):Al(s,`settings`)===void 0?eu(o,s,[`settings`],c,Ll):eu(o,s,[`settings`,r],i,Ll)}var pu=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(_u(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function G(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=mu(e,n,i);if(t===-1)return r===void 0?void 0:hu(e,r);n=t,r=t}return r===void 0?void 0:hu(e,r)}function mu(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 hu(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function gu(e,t){try{return kl(t),null}catch(n){if(!(n instanceof Cl))throw n;return`${e}:${hu(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function _u(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(`
42
- `)}const vu=[`vertical`,`horizontal`],yu={vertical:`row`,horizontal:`cell`};function bu(e){return e.id??e.name}function xu(e){return[...wu(e)].flatMap(e=>e.kind===`segment`?[bu(e)]:[])}function Su(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Cu(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*wu(e){yield e;for(let t of Ou(e))yield*wu(t)}const Tu=(e,t)=>`${e}.children[${t}]`,Eu=e=>`${e}.opens.body`;function*Du(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*Du(r,Tu(t,n));else e.opens!==void 0&&(yield*Du(e.opens.body,Eu(t)))}function Ou(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}const ku=[`shade`,`variation`,`style`];function Au(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const ju=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Mu(e){return e.kind===`file`||e.kind===`shell`||e.kind===`template`}const Nu=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Pu=`theme`,Fu=`effect`,Iu=[Pu,Fu];function Lu(e){return{...e.settings,[Pu]:{label:Pu,domain:`theme`,default:e.palette??`bar`},[Fu]:{label:Fu,domain:Kc,default:`bar`}}}function Ru(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function zu(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Ru(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 Bu(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&Pc(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Vu(e){return String(e)}function Hu(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return _l(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Bu(e,r)?r:void 0}function Uu(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:Hu(n,o))??i}function Wu(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 Gu=[`left`,`center`,`right`],Ku=[`right`,`left`,`middle`];function qu(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),r])}),null)}function Ju(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),`default`])});return}return i}}function Yu(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),r])});return}return i}}function Xu(e,t,n){let r=Yu(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Oc(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[...t.split(`.`),`palette`])});return}return r}}function Zu(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 ${K(a)}`,line:G(e.source,[...t.split(`.`),r])});return}return a}}function Qu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $u(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function K(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function ed(e,t,n,r){return Qu(r)?(id(e,n,r,t.noun,new Set(Object.keys(t.fields)),td(e,t.removed??{},n,r)),nd(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${$u(r)}`,line:G(e.source,n.split(`.`))}),null)}function td(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)ad(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function nd(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 rd=new Set;function id(e,t,n,r,i,a=rd){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:G(e.source,[...t.split(`.`),o])})}function ad(e,t,n){return e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))}),null}function od(e,t,n,r){if(!Qu(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${$u(r)}`,line:G(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:G(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:G(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:G(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function sd(e,t,n,r){if(!Qu(r))return e.issues.push({path:n,message:`${n} must be an object, got ${$u(r)}`,line:G(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 ${$u(i)}`,line:G(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:G(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 id(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function cd(e,t,n){return{json:Sd(bd(n),e,t),keys:new Set([e,...Object.keys(n)])}}function ld(e){return(...t)=>e()(...t)}function ud(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:G(n.source,o.split(`.`))}),null}return a}}function dd(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Yu(e,t,r,n)}}function fd(){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 ${$u(i)}`,line:G(e.source,[n])});return}return i}}}}function pd(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 ${K(o)}`,line:G(e.source,[i])});return}return o}}}}function md(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 ${K(a)}`,line:G(e.source,[r])});return}return a}}}}function hd(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Xu(e,t,r)}}function gd(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>qu(e,t,r,n)??void 0}}function _d(e,t){return f(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function vd(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=qu(e,t,r,n);if(i===null)return;let a=_d(`${t}.${n}`,i);return a===null?i:ad(e,`${t}.${n}`,a)??void 0}}}function yd(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Zu(t,n,i,r,e)}}function bd(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 xd(e){return bd(e.fields)}function Sd(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Cd(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function wd(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const Td=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ed(e){return`#${e+1}`}const Dd={rows:{}};function Od(e){return`rows`in e}function kd(e){return Object.fromEntries(e.map((e,t)=>[Ed(t),e]))}function Ad(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:kd(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:kd([n])}}function jd(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Md(e){return Od(e)?jd(e):e}function*Nd(e,t){if(!Od(e)){yield*Du(e,t);return}yield[jd(e),t];for(let[n,r]of Object.entries(e.rows))yield*Du(r,`${t}.rows.${n}`)}function Pd(e,t){return Od(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Ad(e)}function Fd(e){if(!Od(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}function Id(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:zd(t.segments,Ld(t.segments,e.segments??{})),root:Pd(e.root??Dd,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:zd(t.presets,Rd(t.presets,e.presets??{})),themeDefaults:zd(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Ld(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function Rd(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 zd(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Bd=`closed`,Vd=`🍫`;function Hd(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 Ud(e,t,n,r){let i=Hd(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function Wd(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Gd(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function Kd(e,...t){return`{{ and ${[e,...t].map(qd).join(` `)} }}`}function qd(e){return`(eq .${e.variable} "${Wd(e.member)}")`}function Jd(e,t,n){return`{{ ${Yd(e,Xd(t),Xd(n))} }}`}function Yd(e,t,n){return`action "${e}" ${t} ${n}`}function Xd(e){return`"${Wd(e)}"`}function Zd(e,t){return{kind:`state`,key:e,default:t}}function Qd(e,t){return{set:e,cycle:[Bd,t]}}const $d={required:!1,json:{enum:[...il]},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: ${il.join(`, `)}`,line:G(e.source,[...t.split(`.`),n])});return}return Zu(e,t,r,n,il)}},ef={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Yu(e,t,r,n);return Lc(i)?i:Xu(e,t,r)}},tf={required:!1,json:{anyOf:[{enum:[...Gc]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Lc(i)?i:Zu(e,t,r,n,Gc)}},nf=/^[^\r\n]*\S[^\r\n]*$/u,rf=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),af={required:!1,json:{type:`string`,pattern:nf.source,not:{pattern:rf.source}},parse:(e,t,n,r)=>{let i=Yu(e,t,r,n);if(i===void 0||nf.test(i)&&!rf.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:G(e.source,[...t.split(`.`),n])})}};function of(e){return{spec:yd(e),domain:{from:e}}}function sf(){return{spec:fd(),domain:`bool`}}function cf(e){return{spec:e,domain:`text`}}const lf={default_empty_value:cf(dd()),default_separator:cf(dd()),palette:{spec:ef,domain:{from:`themes`}},style:{spec:dd(),domain:{from:`styles`}},effect:{spec:tf,domain:{from:Gc}},preset:{spec:dd(),domain:{from:`presets`}},endcaps:of(Xc),variation:of(ol),shade:of(ll),autoWrap:sf(),padding:{spec:pd(hl),domain:{...hl,step:1}},charset:of(tl),updateNotice:sf(),transitions:sf(),colorCompatibility:{spec:$d,domain:{from:il}},menuGlyph:cf(af)},uf=Object.fromEntries(Object.entries(lf).map(([e,t])=>[e,t.spec]));function df(e){return lf[e].domain}function ff(e){let t=df(e);if(t===`text`)throw Error(`globals.${e} is free text, which no control can change — list it in UNCONTROLLED_GLOBALS instead of SETTINGS`);return t}function pf(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:G(e.source,[...n.split(`.`),r])})}}}function mf(e){return pf(`${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 hf(e){return pf(`${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 gf(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Lc(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:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const _f={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)`},vf={noun:`globals key`,fields:uf,removed:_f},yf={preset:mf(`a preset`),menuGlyph:hf(`a preset`)},bf={noun:`preset globals key`,fields:{...uf,...yf},removed:_f};function xf(e){return jf(e)&&!(e in yf)}const Sf=`is decided later than any rule could be settled`,Cf={noun:`editGlobals key`,removed:_f,fields:{...uf,preset:mf(`the editGlobals fragment`),menuGlyph:hf(`the editGlobals fragment`),palette:gf(uf.palette,`the editGlobals fragment`,Sf),style:gf(uf.style,`the editGlobals fragment`,Sf),effect:gf(uf.effect,`the editGlobals fragment`,Sf)}},wf={noun:`theme default key`,fields:{...Object.fromEntries(ku.map(e=>[e,uf[e]])),style:gf(uf.style,`a theme's default`,`is the look that theme wears by name`)}};function Tf(e,t){if(!Qu(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${$u(t)}`,line:G(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${Oc(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=ed(e,wf,t,i);a!==null&&(n[r]=a)}return n}function Ef(e,t,n){return n===void 0?{}:ed(e,vf,t,n)??{}}function Df(e,t,n){return ed(e,bf,t,n)??{}}function Of(){return xd(bf)}function kf(e,t,n){return ed(e,Cf,t,n)??{}}const Af=new Set(Object.keys(uf));function jf(e){return Af.has(e)}function Mf(){return[...Af]}const Nf={padding:1};function Pf(e){let t=new Map;for(let[n,r]of Object.entries(Nf)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}function Ff(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: ${ju.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):Bf(e,`${t}.cache`,n.cache)}function If(e,t,n){if(n.cache!==void 0)return Bf(e,`${t}.cache`,n.cache)??void 0}function Lf(e){return{required:!0,json:Vf(),parse:(t,n,r,i)=>Ff(t,n,i,e)??void 0}}function Rf(){return{required:!1,json:Vf(),parse:(e,t,n,r)=>If(e,t,r)}}const zf={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Uf(n)?{ttl:n}:ad(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return ad(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=_d(`cache.watch_file`,n);return r===null?{watch_file:n}:ad(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}:ad(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:ad(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:ad(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function Bf(e,t,n){return od(e,zf,t,n)}function Vf(){return wd(zf)}const Hf=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Uf(e){return Hf.test(e)}function Wf(e,t,n){if(n===void 0)return{};if(!Qu(n))return e.issues.push({path:t,message:`${t} must be an object, got ${$u(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=sd(e,mp,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Gf(){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 ${$u(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function Kf(){return{required:!0,json:{enum:[...Nu]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Nu.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Nu.join(`, `)}, got ${JSON.stringify(i)}`,line:G(e.source,[...t.split(`.`),`field`])});return}return i}}}function qf(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Ju(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Jf={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:ad(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Yf(e,t,n):ad(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:ad(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function Yf(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return ad(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:ad(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function Xf(){return{required:!1,json:wd(Jf),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:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:od(e,Jf,`${t}.parse`,r.parse)??void 0)}}function Zf(){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)=>Qu(r.parse)&&`json`in r.parse?Qf(e,t,r.default):Yu(e,t,r,`default`)}}function Qf(e,t,n){if(n!==void 0)return $f(n)?n:ad(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function $f(e){return e!==null&&ep(e)}function ep(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(ep);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(ep)}default:return!1}}const tp={value:Gf(),default:dd()},np={path:gd(),type:yd([`string`,`number`,`boolean`]),default:qf()},rp={name:gd(),default:dd()},ip={path:vd(),readMode:yd([`whole`,`first-line`]),parse:Xf(),cache:Lf(`file`),default:Zf()},ap={command:gd(),parse:Xf(),cache:Lf(`shell`),default:Zf()},op={template:gd(),cache:Rf(),default:dd()},sp={layout:gd(),default:dd()},cp={cache:`a time variable reads the instant its render is drawn at, so it takes no cache policy — delete the key`},lp={field:Kf(),default:dd()},up={cache:`a git variable is refreshed by the daemon's own watch on the repository, so it takes no cache policy — delete the key`},dp={key:gd(),default:dd()},fp=`kind`;function pp(e,t,n={}){return{...cd(fp,e,t),parse:(r,i,a)=>{td(r,n,i,a);let o=nd(r,t,i,a);return o===null?null:{kind:e,...o}}}}const mp={tag:fp,noun:`source kind`,memberNoun:`variable`,arms:{literal:pp(`literal`,tp),input:pp(`input`,np),env:pp(`env`,rp),file:pp(`file`,ip),shell:pp(`shell`,ap),template:pp(`template`,op),time:pp(`time`,sp,cp),git:pp(`git`,lp,up),state:pp(`state`,dp)}};function hp(){return Cd(mp)}function gp(){return{type:`object`,additionalProperties:hp()}}const _p=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],vp=[..._p,`other`],yp={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`};function bp(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const xp=`groups.`,Sp=`menus.`,Cp=`edit.`,wp=`candybar.`,Tp=[xp,Sp,Cp,wp];function Ep(e){return Tp.some(t=>e.startsWith(t))}function Dp(e){let t=bp(e);return Tp.find(e=>t.startsWith(bp(e)))}function Op(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:G(e.source,[`root`])})}const kp=new Map([[`gitTaculous`,`gitaculous`],[`git`,`gitaculous`],[`settings.menu`,`candybar.menu`]]);function Ap(e){let t=kp.get(e);return t===void 0?``:` (the built-in segment "${e}" was renamed to "${t}" — update this reference)`}const jp=/^[A-Za-z_][A-Za-z0-9_]*$/,Mp={pattern:jp.source},Np={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},Pp={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`,...Mp}}}]},default:Np}},Fp=[`label`,`domain`,`default`],Ip=[`min`,`max`,`step`,`atLeast`];function Lp(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function Rp(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 Lp(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 Lp(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?Lp(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(Qu(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!Ip.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}}:Lp(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 Lp(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function zp(e,t,n){if(!Qu(n))return Lp(e,t,`${t} must be { label, domain, default }, got ${$u(n)}`);for(let r of Object.keys(n))Fp.includes(r)||Lp(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${Fp.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||Lp(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=Rp(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!Bp(n.default)||!Bu(o,n.default)?Lp(e,`${t}.default`,`default must be ${Wu(o)}, got ${K(n.default)}`):o}function Bp(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const Vp={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Pu}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function Hp(e){return Iu.includes(e)}function Up(){return{required:!1,json:{type:`object`,propertyNames:{...Mp,not:{enum:[...Iu]}},additionalProperties:Pp},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qu(i))return Lp(e,a,`${a} must be an object of name → { label, domain, default }, got ${$u(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!jp.test(t)){Lp(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(Hp(t)){Lp(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${Vp[t]}`);continue}let r=zp(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}function Wp(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)?i:Lp(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", got ${K(i)}`)}}}function Gp(){return{required:!1,json:{type:`object`,propertyNames:Mp,additionalProperties:Np},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qu(i))return Lp(e,a,`a placement's "settings" must be an object of setting name → value, got ${$u(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))Bp(n)?o[t]=n:Lp(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${$u(n)}`);return o}}}function Kp(e){return new Set(Object.keys(e.segments).filter(e=>!Ep(e)))}function qp(e,t,n){if(t===void 0)return{};if(!Qu(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${$u(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=ed(e,n.has(i)?$p:Qp,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function Jp(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?ad(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${Ap(t.slice(9))}`)??void 0:qu(e,t,r,n)??void 0}}function Yp(){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 ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function Xp(){return{required:!1,json:gp(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Wf(e,`${t}.${n}`,i)}}}const Zp={template:Jp(),description:dd(),group:yd(_p),width:Yp(),justify:yd(Gu),truncate:yd(Ku),bg:dd(),fg:dd(),when:dd(),palette:hd(),vars:Xp(),settings:Up()},Qp={noun:`segment key`,fields:Zp},$p={noun:`segment key`,fields:{...Zp,template:dd()}},em=`#/definitions/LayoutNode`,tm={kind:`container`,direction:`vertical`,children:[]};function nm(e){return{required:!0,json:{const:e},parse:()=>e}}function rm(){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 ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function im(){return{required:!0,json:{enum:[...vu]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&vu.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${vu.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function am(e){return{required:!0,json:{type:`array`,items:{$ref:em}},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 ${$u(a)}`,line:G(t.source,[`root`])}),[])}}}const om={noun:`layout-node key`,fields:{kind:nm(`segment`),name:rm(),when:dd(),id:Wp(),settings:Gp()}},sm=()=>yd(js),cm={noun:`layout-node key`,fields:{kind:nm(`container`),direction:im(),children:am(ld(()=>pm)),when:dd(),distribution:sm()}};function lm(){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 ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const um={noun:`layout-node key`,fields:{seg:lm(),when:dd(),id:Wp(),settings:Gp()}},dm={noun:`layout-node key`,fields:{h:am(ld(()=>pm)),when:dd(),distribution:sm()}},fm={noun:`layout-node key`,fields:{v:am(ld(()=>pm)),when:dd(),distribution:sm()}},pm=(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:G(e.source,[`root`])}),tm):{kind:`segment`,name:n};if(!Qu(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 ${$u(n)}`,line:G(e.source,[`root`])}),tm;if(n.kind===`container`)return ed(e,cm,t,n)??tm;if(n.kind===`segment`)return ed(e,om,t,n)??tm;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
42
+ `)}const vu=[`vertical`,`horizontal`],yu={vertical:`row`,horizontal:`cell`};function bu(e){return e.id??e.name}function xu(e){return[...wu(e)].flatMap(e=>e.kind===`segment`?[bu(e)]:[])}function Su(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Cu(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*wu(e){yield e;for(let t of Ou(e))yield*wu(t)}const Tu=(e,t)=>`${e}.children[${t}]`,Eu=e=>`${e}.opens.body`;function*Du(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*Du(r,Tu(t,n));else e.opens!==void 0&&(yield*Du(e.opens.body,Eu(t)))}function Ou(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}const ku=[`shade`,`variation`,`style`];function Au(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const ju=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Mu(e){return e.kind===`file`||e.kind===`shell`||e.kind===`template`}const Nu=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Pu=`theme`,Fu=`effect`,Iu=[Pu,Fu];function Lu(e){return{...e.settings,[Pu]:{label:Pu,domain:`theme`,default:e.palette??`bar`},[Fu]:{label:Fu,domain:Kc,default:`bar`}}}function Ru(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function zu(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Ru(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 Bu(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&Pc(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Vu(e){return String(e)}function Hu(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return _l(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Bu(e,r)?r:void 0}function Uu(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:Hu(n,o))??i}function Wu(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 Gu=[`left`,`center`,`right`],Ku=[`right`,`left`,`middle`];function qu(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),r])}),null)}function Ju(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),`default`])});return}return i}}function Yu(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 ${$u(i)}`,line:G(e.source,[...t.split(`.`),r])});return}return i}}function Xu(e,t,n){let r=Yu(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Oc(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[...t.split(`.`),`palette`])});return}return r}}function Zu(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 ${K(a)}`,line:G(e.source,[...t.split(`.`),r])});return}return a}}function Qu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $u(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function K(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function ed(e,t,n,r){return Qu(r)?(id(e,n,r,t.noun,new Set(Object.keys(t.fields)),td(e,t.removed??{},n,r)),nd(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${$u(r)}`,line:G(e.source,n.split(`.`))}),null)}function td(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)ad(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function nd(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 rd=new Set;function id(e,t,n,r,i,a=rd){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:G(e.source,[...t.split(`.`),o])})}function ad(e,t,n){return e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))}),null}function od(e,t,n,r){if(!Qu(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${$u(r)}`,line:G(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:G(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:G(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:G(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function sd(e,t,n,r){if(!Qu(r))return e.issues.push({path:n,message:`${n} must be an object, got ${$u(r)}`,line:G(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 ${$u(i)}`,line:G(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:G(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 id(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function cd(e,t,n){return{json:Sd(bd(n),e,t),keys:new Set([e,...Object.keys(n)])}}function ld(e){return(...t)=>e()(...t)}function ud(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:G(n.source,o.split(`.`))}),null}return a}}function dd(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Yu(e,t,r,n)}}function fd(){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 ${$u(i)}`,line:G(e.source,[n])});return}return i}}}}function pd(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 ${K(o)}`,line:G(e.source,[i])});return}return o}}}}function md(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 ${K(a)}`,line:G(e.source,[r])});return}return a}}}}function hd(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Xu(e,t,r)}}function gd(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>qu(e,t,r,n)??void 0}}function _d(e,t){return f(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function vd(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=qu(e,t,r,n);if(i===null)return;let a=_d(`${t}.${n}`,i);return a===null?i:ad(e,`${t}.${n}`,a)??void 0}}}function yd(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Zu(t,n,i,r,e)}}function bd(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 xd(e){return bd(e.fields)}function Sd(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Cd(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function wd(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const Td=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ed(e){return`#${e+1}`}const Dd={rows:{}};function Od(e){return`rows`in e}function kd(e){return Object.fromEntries(e.map((e,t)=>[Ed(t),e]))}function Ad(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:kd(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:kd([n])}}function jd(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Md(e){return Od(e)?jd(e):e}function*Nd(e,t){if(!Od(e)){yield*Du(e,t);return}yield[jd(e),t];for(let[n,r]of Object.entries(e.rows))yield*Du(r,`${t}.rows.${n}`)}function Pd(e,t){return Od(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Ad(e)}function Fd(e){if(!Od(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}function Id(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:zd(t.segments,Ld(t.segments,e.segments??{})),root:Pd(e.root??Dd,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:zd(t.presets,Rd(t.presets,e.presets??{})),themeDefaults:zd(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Ld(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function Rd(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 zd(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Bd=`closed`,Vd=`🍫`;function Hd(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 Ud(e,t,n,r){let i=Hd(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function Wd(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Gd(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function Kd(e,...t){return`{{ and ${[e,...t].map(qd).join(` `)} }}`}function qd(e){return`(eq .${e.variable} "${Wd(e.member)}")`}function Jd(e,t,n){return`{{ ${Yd(e,Xd(t),Xd(n))} }}`}function Yd(e,t,n){return`action "${e}" ${t} ${n}`}function Xd(e){return`"${Wd(e)}"`}function Zd(e,t){return{kind:`state`,key:e,default:t}}function Qd(e,t){return{set:e,cycle:[Bd,t]}}const $d={required:!1,json:{enum:[...il]},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: ${il.join(`, `)}`,line:G(e.source,[...t.split(`.`),n])});return}return Zu(e,t,r,n,il)}},ef={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Yu(e,t,r,n);return Lc(i)?i:Xu(e,t,r)}},tf={required:!1,json:{anyOf:[{enum:[...Gc]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Lc(i)?i:Zu(e,t,r,n,Gc)}},nf=/^[^\r\n]*\S[^\r\n]*$/u,rf=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),af={required:!1,json:{type:`string`,pattern:nf.source,not:{pattern:rf.source}},parse:(e,t,n,r)=>{let i=Yu(e,t,r,n);if(i===void 0||nf.test(i)&&!rf.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:G(e.source,[...t.split(`.`),n])})}};function of(e){return{spec:yd(e),domain:{from:e}}}function sf(){return{spec:fd(),domain:`bool`}}function cf(e){return{spec:e,domain:`text`}}const lf={default_empty_value:cf(dd()),default_separator:cf(dd()),palette:{spec:ef,domain:{from:`themes`}},style:{spec:dd(),domain:{from:`styles`}},effect:{spec:tf,domain:{from:Gc}},preset:{spec:dd(),domain:{from:`presets`}},endcaps:of(Xc),variation:of(ol),shade:of(ll),autoWrap:sf(),padding:{spec:pd(hl),domain:{...hl,step:1}},charset:of(tl),updateNotice:sf(),transitions:sf(),colorCompatibility:{spec:$d,domain:{from:il}},menuGlyph:cf(af)},uf=Object.fromEntries(Object.entries(lf).map(([e,t])=>[e,t.spec]));function df(e){return lf[e].domain}function ff(e){let t=df(e);if(t===`text`)throw Error(`globals.${e} is free text, which no control can change — list it in UNCONTROLLED_GLOBALS instead of SETTINGS`);return t}function pf(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:G(e.source,[...n.split(`.`),r])})}}}function mf(e){return pf(`${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 hf(e){return pf(`${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 gf(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Lc(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:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const _f={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)`},vf={noun:`globals key`,fields:uf,removed:_f},yf={preset:mf(`a preset`),menuGlyph:hf(`a preset`)},bf={noun:`preset globals key`,fields:{...uf,...yf},removed:_f};function xf(e){return jf(e)&&!(e in yf)}const Sf=`is decided later than any rule could be settled`,Cf={noun:`editGlobals key`,removed:_f,fields:{...uf,preset:mf(`the editGlobals fragment`),menuGlyph:hf(`the editGlobals fragment`),palette:gf(uf.palette,`the editGlobals fragment`,Sf),style:gf(uf.style,`the editGlobals fragment`,Sf),effect:gf(uf.effect,`the editGlobals fragment`,Sf)}},wf={noun:`theme default key`,fields:{...Object.fromEntries(ku.map(e=>[e,uf[e]])),style:gf(uf.style,`a theme's default`,`is the look that theme wears by name`)}};function Tf(e,t){if(!Qu(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${$u(t)}`,line:G(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${Oc(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=ed(e,wf,t,i);a!==null&&(n[r]=a)}return n}function Ef(e,t,n){return n===void 0?{}:ed(e,vf,t,n)??{}}function Df(e,t,n){return ed(e,bf,t,n)??{}}function Of(){return xd(bf)}function kf(e,t,n){return ed(e,Cf,t,n)??{}}const Af=new Set(Object.keys(uf));function jf(e){return Af.has(e)}function Mf(){return[...Af]}const Nf={padding:1};function Pf(e){let t=new Map;for(let[n,r]of Object.entries(Nf)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}function Ff(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: ${ju.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):Bf(e,`${t}.cache`,n.cache)}function If(e,t,n){if(n.cache!==void 0)return Bf(e,`${t}.cache`,n.cache)??void 0}function Lf(e){return{required:!0,json:Vf(),parse:(t,n,r,i)=>Ff(t,n,i,e)??void 0}}function Rf(){return{required:!1,json:Vf(),parse:(e,t,n,r)=>If(e,t,r)}}const zf={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Uf(n)?{ttl:n}:ad(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return ad(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=_d(`cache.watch_file`,n);return r===null?{watch_file:n}:ad(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}:ad(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:ad(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:ad(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function Bf(e,t,n){return od(e,zf,t,n)}function Vf(){return wd(zf)}const Hf=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Uf(e){return Hf.test(e)}function Wf(e,t,n){if(n===void 0)return{};if(!Qu(n))return e.issues.push({path:t,message:`${t} must be an object, got ${$u(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=sd(e,mp,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Gf(){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 ${$u(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function Kf(){return{required:!0,json:{enum:[...Nu]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Nu.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Nu.join(`, `)}, got ${JSON.stringify(i)}`,line:G(e.source,[...t.split(`.`),`field`])});return}return i}}}function qf(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Ju(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Jf={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:ad(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Yf(e,t,n):ad(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:ad(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function Yf(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return ad(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:ad(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function Xf(){return{required:!1,json:wd(Jf),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:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:od(e,Jf,`${t}.parse`,r.parse)??void 0)}}function Zf(){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)=>Qu(r.parse)&&`json`in r.parse?Qf(e,t,r.default):Yu(e,t,r,`default`)}}function Qf(e,t,n){if(n!==void 0)return $f(n)?n:ad(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function $f(e){return e!==null&&ep(e)}function ep(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(ep);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(ep)}default:return!1}}const tp={value:Gf(),default:dd()},np={path:gd(),type:yd([`string`,`number`,`boolean`]),default:qf()},rp={name:gd(),default:dd()},ip={path:vd(),readMode:yd([`whole`,`first-line`]),parse:Xf(),cache:Lf(`file`),default:Zf()},ap={command:gd(),parse:Xf(),cache:Lf(`shell`),default:Zf()},op={template:gd(),cache:Rf(),default:dd()},sp={layout:gd(),default:dd()},cp={cache:`a time variable reads the instant its render is drawn at, so it takes no cache policy — delete the key`},lp={field:Kf(),default:dd()},up={cache:`a git variable is refreshed by the daemon's own watch on the repository, so it takes no cache policy — delete the key`},dp={key:gd(),default:dd()},fp=`kind`;function pp(e,t,n={}){return{...cd(fp,e,t),parse:(r,i,a)=>{td(r,n,i,a);let o=nd(r,t,i,a);return o===null?null:{kind:e,...o}}}}const mp={tag:fp,noun:`source kind`,memberNoun:`variable`,arms:{literal:pp(`literal`,tp),input:pp(`input`,np),env:pp(`env`,rp),file:pp(`file`,ip),shell:pp(`shell`,ap),template:pp(`template`,op),time:pp(`time`,sp,cp),git:pp(`git`,lp,up),state:pp(`state`,dp)}};function hp(){return Cd(mp)}function gp(){return{type:`object`,additionalProperties:hp()}}const _p=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],vp=[..._p,`other`],yp={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`};function bp(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const xp=`groups.`,Sp=`menus.`,Cp=`edit.`,wp=`candybar.`,Tp=[xp,Sp,Cp,wp];function Ep(e){return Tp.some(t=>e.startsWith(t))}function Dp(e){let t=bp(e);return Tp.find(e=>t.startsWith(bp(e)))}function Op(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:G(e.source,[`root`])})}const kp=new Map([[`gitTaculous`,`gitaculous`],[`git`,`gitaculous`],[`settings.menu`,`candybar.menu`]]);function Ap(e){let t=kp.get(e);return t===void 0?``:` (the built-in segment "${e}" was renamed to "${t}" — update this reference)`}const jp=/^[A-Za-z_][A-Za-z0-9_]*$/,Mp={pattern:jp.source},Np={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},Pp={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`,...Mp}}}]},default:Np}},Fp=[`label`,`domain`,`default`],Ip=[`min`,`max`,`step`,`atLeast`];function Lp(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function Rp(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 Lp(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 Lp(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?Lp(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(Qu(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!Ip.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}}:Lp(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 Lp(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function zp(e,t,n){if(!Qu(n))return Lp(e,t,`${t} must be { label, domain, default }, got ${$u(n)}`);for(let r of Object.keys(n))Fp.includes(r)||Lp(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${Fp.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||Lp(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=Rp(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!Bp(n.default)||!Bu(o,n.default)?Lp(e,`${t}.default`,`default must be ${Wu(o)}, got ${K(n.default)}`):o}function Bp(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const Vp={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Pu}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function Hp(e){return Iu.includes(e)}function Up(){return{required:!1,json:{type:`object`,propertyNames:{...Mp,not:{enum:[...Iu]}},additionalProperties:Pp},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qu(i))return Lp(e,a,`${a} must be an object of name → { label, domain, default }, got ${$u(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!jp.test(t)){Lp(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(Hp(t)){Lp(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${Vp[t]}`);continue}let r=zp(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const Wp=Tp.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function Gp(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${Wp})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!Ep(i)?i:Lp(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Tp.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function Kp(){return{required:!1,json:{type:`object`,propertyNames:Mp,additionalProperties:Np},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qu(i))return Lp(e,a,`a placement's "settings" must be an object of setting name → value, got ${$u(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))Bp(n)?o[t]=n:Lp(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${$u(n)}`);return o}}}function qp(e){return new Set(Object.keys(e.segments).filter(e=>!Ep(e)))}function Jp(e,t,n){if(t===void 0)return{};if(!Qu(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${$u(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=ed(e,n.has(i)?em:$p,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function Yp(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?ad(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${Ap(t.slice(9))}`)??void 0:qu(e,t,r,n)??void 0}}function Xp(){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 ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function Zp(){return{required:!1,json:gp(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Wf(e,`${t}.${n}`,i)}}}const Qp={template:Yp(),description:dd(),group:yd(_p),width:Xp(),justify:yd(Gu),truncate:yd(Ku),bg:dd(),fg:dd(),when:dd(),palette:hd(),vars:Zp(),settings:Up()},$p={noun:`segment key`,fields:Qp},em={noun:`segment key`,fields:{...Qp,template:dd()}},tm=`#/definitions/LayoutNode`,nm={kind:`container`,direction:`vertical`,children:[]};function rm(e){return{required:!0,json:{const:e},parse:()=>e}}function im(){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 ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function am(){return{required:!0,json:{enum:[...vu]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&vu.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${vu.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function om(e){return{required:!0,json:{type:`array`,items:{$ref:tm}},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 ${$u(a)}`,line:G(t.source,[`root`])}),[])}}}const sm={noun:`layout-node key`,fields:{kind:rm(`segment`),name:im(),when:dd(),id:Gp(),settings:Kp()}},cm=()=>yd(js),lm={noun:`layout-node key`,fields:{kind:rm(`container`),direction:am(),children:om(ld(()=>mm)),when:dd(),distribution:cm()}};function um(){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 ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const dm={noun:`layout-node key`,fields:{seg:um(),when:dd(),id:Gp(),settings:Kp()}},fm={noun:`layout-node key`,fields:{h:om(ld(()=>mm)),when:dd(),distribution:cm()}},pm={noun:`layout-node key`,fields:{v:om(ld(()=>mm)),when:dd(),distribution:cm()}},mm=(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:G(e.source,[`root`])}),nm):{kind:`segment`,name:n};if(!Qu(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 ${$u(n)}`,line:G(e.source,[`root`])}),nm;if(n.kind===`container`)return ed(e,lm,t,n)??nm;if(n.kind===`segment`)return ed(e,sm,t,n)??nm;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
43
43
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
44
- New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),tm;if(n.kind===`group`){let r=ed(e,bm,t,n);return r===null?tm:(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}),Sm(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:G(e.source,[`root`])}),tm}if(a){let r=ed(e,um,t,n);return r===null?tm:{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=ed(e,dm,t,n);return r===null?tm:{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=ed(e,fm,t,n);return r===null?tm:{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:G(e.source,[`root`])}),tm};function mm(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Td.source},additionalProperties:{$ref:em}},parse:(e,t,n,r)=>{let i=r[n];if(!Qu(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${$u(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Td.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:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=pm(e,`${t}.${n}.${r}`,o)}return a}}}const hm={noun:`root key`,fields:{rows:mm(),when:dd(),distribution:sm()}};function gm(e,t,n){return Qu(n)&&`rows`in n?ed(e,hm,t,n)??{rows:{}}:pm(e,t,n)}function _m(){return{required:!0,json:{type:`string`,pattern:Td.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Td.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 "${Bd}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function vm(){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 ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function ym(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=qu(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:G(e.source,[...t.split(`.`),n])});return}return i}}}}const bm={noun:`layout-node key`,fields:{kind:nm(`group`),name:_m(),label:ym(),open:fd(),direction:yd(vu),key:vm(),bg:dd(),fg:dd(),when:dd(),distribution:sm(),children:am(ld(()=>pm))}};function xm(e){return e.key??`groups.`+e.name}function Sm(e){let t=xp+e.name;return Gd(t,{variable:t,key:xm(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function Cm(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function wm(e,t){Op(e,t,xp,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&Cm(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}.`)&&xm(t)===xm(r)&&Cm(e,t.path,`group "${t.name}" shares key "${xm(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=xm(t);if(i.has(n)||i.set(n,Bd),t.open===!0){let r=i.get(n);r!==`closed`&&Cm(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=xp+e.name,r=xm(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Zd(r,i.get(r)),o[t]=Qd(r,e.name),s[t]={template:Jd(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}}var Tm=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?Pm(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}},Em=class extends Tm{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Dm=class extends Tm{name=`EvalError`;kind=`EvalError`},Om=class extends Dm{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Fm(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}},km=class extends Dm{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}},Am=class extends Dm{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}},jm=class extends Am{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)}`}},Mm=class extends Dm{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Nm=class extends Dm{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Pm(e,t){let n=e.split(`
44
+ New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),nm;if(n.kind===`group`){let r=ed(e,xm,t,n);return r===null?nm:(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}),Cm(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:G(e.source,[`root`])}),nm}if(a){let r=ed(e,dm,t,n);return r===null?nm:{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=ed(e,fm,t,n);return r===null?nm:{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=ed(e,pm,t,n);return r===null?nm:{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:G(e.source,[`root`])}),nm};function hm(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Td.source},additionalProperties:{$ref:tm}},parse:(e,t,n,r)=>{let i=r[n];if(!Qu(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${$u(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Td.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:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=mm(e,`${t}.${n}.${r}`,o)}return a}}}const gm={noun:`root key`,fields:{rows:hm(),when:dd(),distribution:cm()}};function _m(e,t,n){return Qu(n)&&`rows`in n?ed(e,gm,t,n)??{rows:{}}:mm(e,t,n)}function vm(){return{required:!0,json:{type:`string`,pattern:Td.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Td.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 "${Bd}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function ym(){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 ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function bm(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=qu(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:G(e.source,[...t.split(`.`),n])});return}return i}}}}const xm={noun:`layout-node key`,fields:{kind:rm(`group`),name:vm(),label:bm(),open:fd(),direction:yd(vu),key:ym(),bg:dd(),fg:dd(),when:dd(),distribution:cm(),children:om(ld(()=>mm))}};function Sm(e){return e.key??`groups.`+e.name}function Cm(e){let t=xp+e.name;return Gd(t,{variable:t,key:Sm(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function wm(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Tm(e,t){Op(e,t,xp,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&wm(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}.`)&&Sm(t)===Sm(r)&&wm(e,t.path,`group "${t.name}" shares key "${Sm(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=Sm(t);if(i.has(n)||i.set(n,Bd),t.open===!0){let r=i.get(n);r!==`closed`&&wm(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=xp+e.name,r=Sm(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Zd(r,i.get(r)),o[t]=Qd(r,e.name),s[t]={template:Jd(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}}var Em=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?Fm(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}},Dm=class extends Em{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Om=class extends Em{name=`EvalError`;kind=`EvalError`},km=class extends Om{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Im(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}},Am=class extends Om{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}},jm=class extends Om{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}},Mm=class extends jm{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)}`}},Nm=class extends Om{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Pm=class extends Om{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Fm(e,t){let n=e.split(`
45
45
  `),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(`
46
- `)}function Fm(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Im(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 Im(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 Lm(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Rm=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`]]),zm={left:`{{`,right:`}}`};var Bm=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=zm){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 Em(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&&Vm(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);Vm(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);Vm(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(;Vm(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`;Vm(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&&(Um(e)||Hm(e)&&Um(this.src[this.offset+1]??``)||e===`.`&&Um(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Jm(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===`
46
+ `)}function Im(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Lm(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 Lm(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 Rm(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const zm=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`]]),Bm={left:`{{`,right:`}}`};var Vm=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Bm){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 Dm(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&&Hm(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);Hm(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);Hm(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(;Hm(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`;Hm(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&&(Wm(e)||Um(e)&&Wm(this.src[this.offset+1]??``)||e===`.`&&Wm(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Ym(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===`
47
47
  `)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===`
48
- `)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(Hm(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);Wm(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);Gm(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);Km(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Um(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Um(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),Hm(this.src[this.offset]??``)&&this.advanceBy(1);Um(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Wm(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);Ym(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Jm(this.src[this.offset+1]??``);)for(this.advanceBy(1);Ym(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),!Jm(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;Ym(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Jm(this.src[this.offset+1]??``);)for(this.advanceBy(1);Ym(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(;Ym(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Rm.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===`
48
+ `)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(Um(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);Gm(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);Km(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);qm(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Wm(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Wm(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),Um(this.src[this.offset]??``)&&this.advanceBy(1);Wm(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Gm(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);Xm(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Ym(this.src[this.offset+1]??``);)for(this.advanceBy(1);Xm(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),!Ym(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;Xm(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Ym(this.src[this.offset+1]??``);)for(this.advanceBy(1);Xm(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(;Xm(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=zm.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===`
49
49
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
50
- `?(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 Vm(e){return e===` `||e===` `||e===`\r`||e===`
51
- `}function Hm(e){return e===`+`||e===`-`}function Um(e){return e>=`0`&&e<=`9`}function Wm(e){return Um(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Gm(e){return e>=`0`&&e<=`7`}function Km(e){return e===`0`||e===`1`}function qm(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Jm(e){return qm(e)||e===`_`}function Ym(e){return Jm(e)||Um(e)}let Xm,Zm;function Qm(e,t){return Zm(e,t)}var $m=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{Xm=(t,n)=>new e(t,n),Zm=(e,t)=>e.#e.get(t)??(e.#t&&Zm(e.#t,t))}has(e){return Zm(this,e)!==void 0}};function eh(e,t,n=$m.EMPTY){return new th(e,t,n).parseTemplate()}var th=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new Bm(e,t):new Bm(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:ih(n)});return n}errAt(e,t,n={}){return new Em(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 ${ih(e)}`,{found:ih(e)})}return{root:e,defines:Xm(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=rh(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 nh(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${ih(n)} at top level`,{found:ih(n)})}return nh(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 Em(`{{${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 Em(`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:ih(e)});return fh(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(!ah(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:ih(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=[oh(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(oh(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;ah(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 oh(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:fh(e.value,e.pos,this.source)};case`Number`:return ch(e);case`Char`:return lh(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 ${ih(e)}`,{expected:`command argument`,found:ih(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 nh(e,t){return{type:`List`,pos:e,nodes:t}}function rh(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function ih(e){return e.type===`EOF`?`end of input`:e.value||e.type}function ah(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 oh(e){return{type:`Variable`,pos:e.pos,idents:sh(e.value)}}function sh(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function ch(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=uh(i);return{...s,intValue:e}}if(a){let e=dh(i);return{...s,floatValue:e}}let c=dh(i);return{...s,complexValue:[0,c]}}function lh(e,t){let n=ph(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 uh(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 dh(e){return Number(e)}function fh(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+=`
52
- `;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 Em(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function ph(e,t,n){let r=fh(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Em(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function mh(e,t){if(t(e)!==!1)for(let n of hh(e))mh(n,t)}function hh(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 Lm(e)}}const gh=Symbol(`go-template-js.MISSING`);function _h(e,t){if(e==null)return gh;if(e instanceof Map)return e.has(t)?e.get(t):gh;if(Array.isArray(e))return gh;if(typeof e==`object`){let n=e;return t in n?n[t]:gh}return gh}function vh(e,t){let n=e;for(let e of t){if(n===gh)return gh;n=_h(n,e)}return n}function yh(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)=>yh(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)||!yh(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=>yh(e[n],t[n])):!1}return!1}const bh=new WeakSet;function xh(e){return bh.add(e),e}function Sh(e){return bh.has(e)}function Ch(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 wh(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Dh(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Dh(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Oh(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Oh(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Oh(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Oh(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>kh(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Ah(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Mh(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Fh(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Fh(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>Wh(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>qh(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>qh(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>Rh(Fh(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Vh(Fh(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>Uh(Fh(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Ch(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Th(){return{and:xh({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Ch(t))return t;return t}}),or:xh({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Ch(t))return t;return t}})}}function Eh(e,t){return{...wh(e,t),...Th()}}function Dh(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):yh(e,t)}function Oh(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 kh(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Ah(e,t){if(Array.isArray(e)||typeof e==`string`){let n=jh(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 ${Nh(t)}`);return e[t]}throw Error(`index: cannot index ${Nh(e)}`)}function jh(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 ${Ph(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Mh(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]=jh(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 Nh(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Ph(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 Fh(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+=Ih(a,t),r=o}return n}function Ih(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Lh={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Rh(e){return e.replace(/[\0"'&<>]/g,e=>Lh[e]??e)}const zh={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Bh=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Vh(e){let t=``;for(let n of e){let e=zh[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Bh.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Hh=new TextEncoder;function Uh(e){let t=``,n=Hh.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 Wh(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+=Gh(l??``,u,d,n,r),o=c+1}return i}function Gh(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?Kh(t,n):Kh(t,Ih(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Ph(n)}=${Ih(n,r)})`:Kh(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return Kh(t,qh(n,r,i));case`q`:return Kh(t,JSON.stringify(Ih(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Ph(n)}=${Ih(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return Kh(t,Number(n).toFixed(i))}case`t`:return Kh(t,Ch(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 Kh(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Ph(n)}=${Ih(n,r)})`:typeof n==`bigint`?Kh(t,n.toString(16)):Kh(t,Math.trunc(n).toString(16));default:return`%!${e}(${Ph(n)}=${Ih(n,r)})`}}function Kh(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 qh(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>qh(e,t,n)).join(` `)}]`:e instanceof Map?Jh([...e.entries()],t,n):Yh(e)?Jh(Object.entries(e),t,n):String(e)}function Jh(e,t,n){let r=e=>qh(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 Yh(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 Xh(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function Zh(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function Qh(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 $h(e,t,n){e.vars.set(t,n)}const eg=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],tg=new Set([`default`,`zero`,`error`]);function ng(e){if(e===void 0)return`default`;if(tg.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${rg(e)}`)}function rg(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 ig(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${rg(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${rg(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${rg(e.right)}`);return{left:e.left,right:e.right}}}function ag(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function og(e){let t=new Set(eg);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 ${eg.join(`, `)}`)}),ag(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 sg=Object.freeze({kind:`break`}),cg=Object.freeze({kind:`continue`}),lg={kind:`none`};let ug;(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{ug=(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 dg(e){let t=new Set,n=e=>{mh(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 fg={kind:`dynamic`};function pg(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=Pg(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:fg}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return fg;let t=e.cmds[0];if(t===void 0)return fg;let n=t.args[0];return n===void 0||n.type!==`Identifier`?fg:{kind:`call`,name:n.ident,args:t.args.slice(1).map(pg)}}default:return fg}}function mg(e){let t=[],n=e=>{mh(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(pg);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 hg=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??Cg,this.isT=e.isT??gg,this.missingKey=ng(e.missingKey),this.delims=ig(e.delims),this.funcs=og({...Eh(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=eh(e,this.delims,t);return ug(n.source,e=>this.evalParsed(n,e),n.defines,dg(n),mg(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=Xh(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 sg;case`Continue`:throw cg;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 Dm(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Lm(e)}}evalIf(e,t,n){Ch(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(Ch(r)){let i=Zh(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=jg(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=Zh(t,o);if(i.length===1)$h(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;$h(a,e,r),$h(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===cg)continue;throw e}}}catch(e){if(e===sg)return;throw e}}evalTemplateInvoke(e,t,n){let r=Qm(n.defines,e.name);if(!r)throw new Dm(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=Zh(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=Zh(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=Qm(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 Dm(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,lg);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)$h(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 Dm(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Dm(`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 Om(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Sh(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){vg(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof Am?new Am(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Nm?new Nm(t.message,r,{source:i.source}):t instanceof Tm?t:new Dm(`error calling ${e}: ${kg(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 Pg(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 Om(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 Dm(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=vh(e,t);if(i!==gh)return i;if(this.missingKey===`error`)throw new Mm(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=Qh(t,i);if(!a.found)throw new Dm(`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(qh(e,this.toString,this.isT)))}};const gg=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function _g(e){return new hg(e)}function vg(e,t,n,r,i,a=Cg,o=Sg,s=gg){let{argTypes:c,arity:l}=t,u=yg(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new km(e,u,n.length,r,{source:i});let d=bg(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!xg(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new jm(e,t+1,l,r,{source:i}):new Am(e,t+1,Og(c),Ag(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(!Tg(n[f],l))throw new Am(e,t+1,`${Og(`ordered`)} of the same kind as ${Ag(n[f])}`,Ag(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!Eg(n[p],l))throw new Am(e,t+1,`${Og(`comparable`)} of the same kind as ${Ag(n[p])}`,Ag(l),r,{source:i})}}}function yg(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 bg(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 xg(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 Yh(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||Yh(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||Yh(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||Yh(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 wg(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function Sg(e){return e}function Cg(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 Am(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Ag(e),{line:0,column:0,offset:0})}function wg(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Tg(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Eg(e,t){let n=Dg(e),r=Dg(t);return n===`nil`||r===`nil`?!0:n===r}function Dg(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 Og(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 kg(e){return e instanceof Error?e.message:String(e)}function Ag(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function jg(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?Mg([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Mg(Object.entries(e)):[]}function Mg(e){return[...e].sort((e,t)=>Ng(e[0],t[0]))}function Ng(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 Pg(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 Fg(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Ig(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 Lg(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 Rg(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=Lg(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 zg(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Lg(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 Bg(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 Vg(e){return JSON.stringify(e)??`null`}function Hg(){return{atoi:{fn:e=>Fg(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>Rg(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>zg(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>Ig(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>Bg(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>Vg(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const Ug={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Wg(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*Ug[a],n=n.slice(e[0].length)}return t?-r:r}function Gg(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Ug.us?`${Math.floor(n)}ns`:n<Ug.ms?Kg(n,Ug.us,3,`µs`):n<Ug.s?Kg(n,Ug.ms,6,`ms`):qg(n),t?`-${r}`:r}function Kg(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 qg(e){let t=Math.floor(e/Ug.h);e-=t*Ug.h;let n=Math.floor(e/Ug.m);e-=n*Ug.m;let r=Math.floor(e/Ug.s),i=e-r*Ug.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 Jg(e){return e*Ug.s}function Yg(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 Xg(e,t){let n=t().getTime()-Yg(e).getTime();return Gg(Math.round(n/1e3)*1e9)}const Zg=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Qg=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],$g=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],e_=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function t_(e){return e<10?`0${e}`:String(e)}function n_(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function r_(e){return e<10?` ${e}`:String(e)}function i_(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${t_(Math.floor(n/60))}${t_(n%60)}`}function a_(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${t_(Math.floor(n/60))}:${t_(n%60)}`}function o_(e){return`${e>=0?`+`:`-`}${t_(Math.floor(Math.abs(e)/60))}`}function s_(e){return e===0?`Z`:i_(e)}function c_(e){return e===0?`Z`:a_(e)}function l_(e){return e===0?`Z`:o_(e)}function u_(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const d_=[[`.000000000`,e=>`.${u_(e.ms,9,!1)}`],[`.999999999`,e=>{let t=u_(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${u_(e.ms,6,!1)}`],[`.999999`,e=>{let t=u_(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${n_(e.ms)}`],[`.999`,e=>{let t=n_(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Zg[e.month-1]??`January`],[`Monday`,e=>$g[e.weekday]??`Monday`],[`Z07:00`,e=>c_(e.offsetMinutes)],[`-07:00`,e=>a_(e.offsetMinutes)],[`Z0700`,e=>s_(e.offsetMinutes)],[`-0700`,e=>i_(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Qg[e.month-1]??`Jan`],[`Mon`,e=>e_[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>o_(e.offsetMinutes)],[`Z07`,e=>l_(e.offsetMinutes)],[`15`,e=>t_(e.hour)],[`01`,e=>t_(e.month)],[`02`,e=>t_(e.day)],[`_2`,e=>r_(e.day)],[`03`,e=>t_(e.hour12)],[`04`,e=>t_(e.minute)],[`05`,e=>t_(e.second)],[`06`,e=>t_(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 f_(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of d_)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const p_={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function m_(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const h_=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function g_(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=m_(new Intl.DateTimeFormat(`en-US`,{...p_,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=m_(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=__(m_(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=h_.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 __(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 v_(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function y_(e,t){return f_(e,g_(Yg(t),v_()))}function b_(e,t,n){return f_(e,g_(Yg(t),n))}function x_(e,t){let n=Yg(t),r=Wg(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function S_(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Gg(Jg(t))}return typeof e==`bigint`?Gg(Jg(Number(e))):typeof e==`number`?Gg(Jg(e)):`0s`}const C_=36e11*24*365,w_=36e11*24*30,T_=36e11*24,E_=36e11,D_=6e10,O_=1e9;function k_(e){let t=Wg(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>C_?`${Math.floor(n/C_)}y`:n>w_?`${Math.floor(n/w_)}mo`:n>T_?`${Math.floor(n/T_)}d`:n>E_?`${Math.floor(n/E_)}h`:n>D_?`${Math.floor(n/D_)}m`:n>O_?`${Math.floor(n/O_)}s`:`0s`}function A_(e){let t=g_(Yg(e),v_());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function j_(e,t){let n=g_(Yg(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function M_(e){return e()}const N_=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],P_=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function F_(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function I_(e,t,n){return[e.slice(t,t+n),t+n]}function L_(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 R_(e,t){for(let[n,r]of N_.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function z_(e,t){for(let[n,r]of P_.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function B_(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 V_(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 H_(e,t){if(e[t]===` `){let[n,r]=L_(e,t+1,1,1);return[n,r]}return L_(e,t,1,2)}function U_(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]=L_(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=L_(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=L_(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function W_(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]=L_(e,t+1,2,2);return[n*r*60,i]}return U_(e,t,n)}function G_(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 K_(e,t,n){let[r,i]=I_(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function q_(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=R_(t,n);return i.month=e,[r,i]}case`Monday`:return[B_(t,n),i];case`Jan`:{let[e,r]=z_(t,n);return i.month=e,[r,i]}case`Mon`:return[V_(t,n),i];case`2006`:{let[e,r]=L_(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=L_(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=L_(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=L_(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=H_(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=L_(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=L_(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=L_(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=L_(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=L_(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=L_(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=L_(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=L_(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=L_(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[G_(t,n),i];case`-0700`:{let[e,r]=U_(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=U_(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]=L_(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=W_(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=W_(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=W_(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]=K_(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]=K_(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]=K_(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 J_=`.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 Y_(e,t){let n=0,r=0,i=F_();for(;n<e.length;){let a=!1;for(let o of J_)if(e.startsWith(o,n)){let[e,s]=q_(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 X_(e,t){return Y_(e,t)}function Z_(e){return String(Math.floor(Yg(e).getTime()/1e3))}function Q_(e=()=>new Date){return{now:{fn:()=>M_(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>y_(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>b_(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>x_(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>A_(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>j_(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>S_(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>k_(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>X_(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>Xg(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>Z_(e),argTypes:[`value`],arity:{kind:`exact`}}}}function $_(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 ev(...e){for(let t of e)if(!$_(t))return t}function tv(e,t){return $_(t)?e:t}function nv(e){return JSON.parse(e)}function rv(e,t,n){return Ch(n)?e:t}function iv(e){return JSON.stringify(e)??`null`}function av(e){return JSON.stringify(e,null,2)??`null`}function ov(){return{default:{fn:(e,t)=>tv(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>$_(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>ev(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>rv(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>nv(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>iv(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>av(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function sv(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function cv(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 sv(...t)}function lv(e,t){return e[t]}function uv(e,t){return t in e}function dv(e){return Object.keys(e)}function fv(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 pv(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function mv(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 hv(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function gv(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function _v(e,t,n){return e[t]=n,e}function vv(e,t){return delete e[t],e}function yv(e){return Object.values(e)}function bv(){return{dict:{fn:(...e)=>sv(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>lv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>_v(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>vv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>dv(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>yv(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>gv(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>hv(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>mv(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>uv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>fv(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>pv(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function xv(e){throw new Nm(e)}function Sv(){return{fail:{fn:e=>xv(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 Cv(...e){for(let t of e)if($_(t))return!1;return!0}function wv(...e){for(let t of e)if(!$_(t))return!0;return!1}function Tv(e,t){return[...e,t]}function Ev(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 Dv(e){return e.filter(e=>!$_(e))}function Ov(...e){let t=[];for(let n of e)t.push(...n);return t}const kv={line:0,column:0,offset:0};function Av(e,t,n,r){return new Am(e,t,n,r,kv)}function jv(...e){if(e.length<3)throw Av(`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(!Nv(t))throw Av(`dig`,e.length-1,`dict`,Pv(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Av(`dig`,e,`string`,Pv(r[e]));return Mv(t,n,r,e.length)}function Mv(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(!Nv(a))throw Av(`dig`,r-1,`dict at intermediate key`,Pv(a));return Mv(a,t,n.slice(1),r)}function Nv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Pv(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Fv(e){return e[0]}function Iv(e,t){return t.some(t=>yh(t,e))}function Lv(e){return e.slice(0,-1)}function Rv(e){return e[e.length-1]}function zv(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Bv(...e){return e}function Vv(e,t){return[t,...e]}function Hv(e){return e.slice(1)}function Uv(e){return[...e].reverse()}function Wv(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Gv(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Kv(e){let t=[];for(let n of e)t.some(e=>yh(e,n))||t.push(n);return t}function qv(e,...t){return e.filter(e=>!t.some(t=>yh(t,e)))}function Jv(){return{list:{fn:(...e)=>Bv(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>Fv(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>Rv(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>Hv(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>Lv(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>zv(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>Uv(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>Kv(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>qv(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>Iv(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>Dv(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>Wv(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>Ov(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Ev(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>Vv(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>Tv(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>Gv(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>Tv(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>Bv(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>jv(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>Cv(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>wv(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function Yv(...e){return e.reduce((e,t)=>e+t,0)}function Xv(e){return e+1}function Zv(e){return e+1}function Qv(...e){return e.reduce((e,t)=>e+t,0)}function $v(e){return Math.ceil(e)}function ey(e,t){return Math.trunc(e/t)}function ty(e,...t){return t.reduce((e,t)=>e/t,e)}function ny(e){return Math.floor(e)}function ry(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function iy(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function ay(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function oy(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function sy(e,t){return e%t}function cy(...e){return e.reduce((e,t)=>e*t,1)}function ly(...e){return e.reduce((e,t)=>e*t,1)}function uy(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function dy(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 fy(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),dy(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return dy(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:dy(n,i+t,r).join(` `)}default:return``}}function py(e,t){return e-t}function my(e,...t){return t.reduce((e,t)=>e-t,e)}function hy(e){return dy(0,e,e<0?-1:1)}function gy(){return{add:{fn:(...e)=>Yv(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>py(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>cy(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>ey(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>sy(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>ay(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>ry(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>ny(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>$v(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>uy(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>Qv(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>my(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>ly(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>ty(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>Xv(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>Zv(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>iy(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>oy(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>ry(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>fy(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>hy(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>dy(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function _y(e){return Array.from(e)}function vy(e,t){return e===``?_y(t):t.split(e)}function yy(e,t){let n=_y(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function by(e,t,n){let r=_y(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},xy=/^[-_\s]$/,Sy=/^\p{P}$/u,Cy=/^\p{L}$/u,wy=/^\p{Lu}$/u,Ty=/^\p{N}$/u;function Ey(e){return e!==void 0&&xy.test(e)}function Dy(e){return e!==void 0&&Cy.test(e)}function Oy(e){return e!==void 0&&wy.test(e)}function ky(e){return e!==void 0&&Ty.test(e)}function Ay(e){return e!==void 0&&Sy.test(e)}function jy(e,t){if(t>=e.length)return{word:{wt:q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(Ey(n)){for(;r<e.length&&Ey(e[r]);)r++;return{word:{wt:q.Connector,text:e.slice(t,r).join(``)},next:r}}if(Ay(n)){for(;r<e.length&&Ay(e[r]);)r++;return{word:{wt:q.Punct,text:e.slice(t,r).join(``)},next:r}}if(Oy(n)){if(r>=e.length)return{word:{wt:q.UpperCase,text:n},next:r};if(Oy(e[r])){let n=r;for(;n<e.length&&Oy(e[n]);)n++;return n<e.length&&Dy(e[n])?{word:{wt:q.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(Dy(e[r])){let n=r+1;for(;n<e.length&&Dy(e[n])&&!Oy(e[n]);)n++;return{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:q.UpperCase,text:n},next:r}}if(Dy(n)){for(;r<e.length&&Dy(e[r])&&!Oy(e[r]);)r++;return{word:{wt:q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(ky(n)){for(;r<e.length&&ky(e[r]);)r++;return{word:{wt:q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!Ey(e[r])&&!Dy(e[r])&&!ky(e[r])&&!Ay(e[r]);)r++;return{word:{wt:q.Other,text:e.slice(t,r).join(``)},next:r}}function My(e,t,n){if(t.wt!==q.UpperCase&&t.wt!==q.Connector){e.push(t.text);return}for(let r of t.text)Ey(r)?e.push(n):Oy(r)?e.push(r.toLowerCase()):e.push(r)}function Ny(e,t){if(e.length===0)return``;let n=_y(e),r=[],{word:i,next:a}=jy(n,0);for(;a<n.length;){i.wt!==q.Connector&&My(r,i,t);let e=i,o=i;if({word:i,next:a}=jy(n,a),e.wt===q.Number){for(;i.wt===q.Alphabet||i.wt===q.Number;)My(r,i,t),{word:i,next:a}=jy(n,a);i.wt!==q.Invalid&&i.wt!==q.Punct&&i.wt!==q.Connector&&r.push(t);continue}if(e.wt===q.Connector){My(r,o,t);continue}if(e.wt===q.Punct)continue;if(i.wt!==q.Number){i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=jy(n,a),i.wt!==q.Alphabet){My(r,s,t),i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}for(r.push(t),My(r,s,t);i.wt===q.Alphabet||i.wt===q.Number;)My(r,i,t),{word:i,next:a}=jy(n,a);i.wt!==q.Invalid&&i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t)}return My(r,i,t),r.join(``).toLowerCase()}function Py(e){if(e.length===0)return``;let t=_y(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!Ey(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++,Ey(i)&&Ey(e)){n.push(e);continue}Ey(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Fy(e){return Py(e)}function Iy(...e){return e.join(` `)}function Ly(e,t){return t.includes(e)}function Ry(e,t){return t.startsWith(e)}function zy(e,t){return t.endsWith(e)}function By(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
50
+ `?(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 Hm(e){return e===` `||e===` `||e===`\r`||e===`
51
+ `}function Um(e){return e===`+`||e===`-`}function Wm(e){return e>=`0`&&e<=`9`}function Gm(e){return Wm(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Km(e){return e>=`0`&&e<=`7`}function qm(e){return e===`0`||e===`1`}function Jm(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Ym(e){return Jm(e)||e===`_`}function Xm(e){return Ym(e)||Wm(e)}let Zm,Qm;function $m(e,t){return Qm(e,t)}var eh=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{Zm=(t,n)=>new e(t,n),Qm=(e,t)=>e.#e.get(t)??(e.#t&&Qm(e.#t,t))}has(e){return Qm(this,e)!==void 0}};function th(e,t,n=eh.EMPTY){return new nh(e,t,n).parseTemplate()}var nh=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new Vm(e,t):new Vm(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:ah(n)});return n}errAt(e,t,n={}){return new Dm(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 ${ah(e)}`,{found:ah(e)})}return{root:e,defines:Zm(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=ih(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 rh(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${ah(n)} at top level`,{found:ah(n)})}return rh(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 Dm(`{{${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 Dm(`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:ah(e)});return ph(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(!oh(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:ah(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=[sh(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(sh(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;oh(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 sh(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:ph(e.value,e.pos,this.source)};case`Number`:return lh(e);case`Char`:return uh(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 ${ah(e)}`,{expected:`command argument`,found:ah(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 rh(e,t){return{type:`List`,pos:e,nodes:t}}function ih(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function ah(e){return e.type===`EOF`?`end of input`:e.value||e.type}function oh(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 sh(e){return{type:`Variable`,pos:e.pos,idents:ch(e.value)}}function ch(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function lh(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=dh(i);return{...s,intValue:e}}if(a){let e=fh(i);return{...s,floatValue:e}}let c=fh(i);return{...s,complexValue:[0,c]}}function uh(e,t){let n=mh(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 dh(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 fh(e){return Number(e)}function ph(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+=`
52
+ `;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 Dm(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function mh(e,t,n){let r=ph(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Dm(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function hh(e,t){if(t(e)!==!1)for(let n of gh(e))hh(n,t)}function gh(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 Rm(e)}}const _h=Symbol(`go-template-js.MISSING`);function vh(e,t){if(e==null)return _h;if(e instanceof Map)return e.has(t)?e.get(t):_h;if(Array.isArray(e))return _h;if(typeof e==`object`){let n=e;return t in n?n[t]:_h}return _h}function yh(e,t){let n=e;for(let e of t){if(n===_h)return _h;n=vh(n,e)}return n}function bh(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)=>bh(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)||!bh(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=>bh(e[n],t[n])):!1}return!1}const xh=new WeakSet;function Sh(e){return xh.add(e),e}function Ch(e){return xh.has(e)}function wh(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 Th(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Oh(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Oh(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>kh(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>kh(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>kh(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>kh(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Ah(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=jh(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Nh(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Ih(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Ih(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>Gh(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>Jh(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>Jh(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>zh(Ih(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Hh(Ih(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>Wh(Ih(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!wh(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Eh(){return{and:Sh({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!wh(t))return t;return t}}),or:Sh({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),wh(t))return t;return t}})}}function Dh(e,t){return{...Th(e,t),...Eh()}}function Oh(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):bh(e,t)}function kh(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 Ah(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function jh(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Mh(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 ${Ph(t)}`);return e[t]}throw Error(`index: cannot index ${Ph(e)}`)}function Mh(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 ${Fh(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Nh(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]=Mh(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 Ph(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Fh(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 Ih(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+=Lh(a,t),r=o}return n}function Lh(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Rh={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function zh(e){return e.replace(/[\0"'&<>]/g,e=>Rh[e]??e)}const Bh={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Vh=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Hh(e){let t=``;for(let n of e){let e=Bh[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Vh.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Uh=new TextEncoder;function Wh(e){let t=``,n=Uh.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 Gh(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+=Kh(l??``,u,d,n,r),o=c+1}return i}function Kh(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?qh(t,n):qh(t,Lh(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Fh(n)}=${Lh(n,r)})`:qh(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return qh(t,Jh(n,r,i));case`q`:return qh(t,JSON.stringify(Lh(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Fh(n)}=${Lh(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return qh(t,Number(n).toFixed(i))}case`t`:return qh(t,wh(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 qh(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Fh(n)}=${Lh(n,r)})`:typeof n==`bigint`?qh(t,n.toString(16)):qh(t,Math.trunc(n).toString(16));default:return`%!${e}(${Fh(n)}=${Lh(n,r)})`}}function qh(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 Jh(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>Jh(e,t,n)).join(` `)}]`:e instanceof Map?Yh([...e.entries()],t,n):Xh(e)?Yh(Object.entries(e),t,n):String(e)}function Yh(e,t,n){let r=e=>Jh(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 Xh(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 Zh(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function Qh(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function $h(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 eg(e,t,n){e.vars.set(t,n)}const tg=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],ng=new Set([`default`,`zero`,`error`]);function rg(e){if(e===void 0)return`default`;if(ng.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${ig(e)}`)}function ig(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 ag(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${ig(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${ig(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${ig(e.right)}`);return{left:e.left,right:e.right}}}function og(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function sg(e){let t=new Set(tg);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 ${tg.join(`, `)}`)}),og(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 cg=Object.freeze({kind:`break`}),lg=Object.freeze({kind:`continue`}),ug={kind:`none`};let dg;(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{dg=(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 fg(e){let t=new Set,n=e=>{hh(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 pg={kind:`dynamic`};function mg(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=Fg(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:pg}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return pg;let t=e.cmds[0];if(t===void 0)return pg;let n=t.args[0];return n===void 0||n.type!==`Identifier`?pg:{kind:`call`,name:n.ident,args:t.args.slice(1).map(mg)}}default:return pg}}function hg(e){let t=[],n=e=>{hh(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(mg);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 gg=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??wg,this.isT=e.isT??_g,this.missingKey=rg(e.missingKey),this.delims=ag(e.delims),this.funcs=sg({...Dh(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=th(e,this.delims,t);return dg(n.source,e=>this.evalParsed(n,e),n.defines,fg(n),hg(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=Zh(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 cg;case`Continue`:throw lg;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 Om(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Rm(e)}}evalIf(e,t,n){wh(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(wh(r)){let i=Qh(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=Mg(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=Qh(t,o);if(i.length===1)eg(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;eg(a,e,r),eg(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===lg)continue;throw e}}}catch(e){if(e===cg)return;throw e}}evalTemplateInvoke(e,t,n){let r=$m(n.defines,e.name);if(!r)throw new Om(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=Qh(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=Qh(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=$m(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 Om(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,ug);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)eg(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 Om(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Om(`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 km(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Ch(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){yg(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof jm?new jm(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Pm?new Pm(t.message,r,{source:i.source}):t instanceof Em?t:new Om(`error calling ${e}: ${Ag(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 Fg(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 km(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 Om(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=yh(e,t);if(i!==_h)return i;if(this.missingKey===`error`)throw new Nm(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=$h(t,i);if(!a.found)throw new Om(`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(Jh(e,this.toString,this.isT)))}};const _g=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function vg(e){return new gg(e)}function yg(e,t,n,r,i,a=wg,o=Cg,s=_g){let{argTypes:c,arity:l}=t,u=bg(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new Am(e,u,n.length,r,{source:i});let d=xg(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!Sg(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new Mm(e,t+1,l,r,{source:i}):new jm(e,t+1,kg(c),jg(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(!Eg(n[f],l))throw new jm(e,t+1,`${kg(`ordered`)} of the same kind as ${jg(n[f])}`,jg(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!Dg(n[p],l))throw new jm(e,t+1,`${kg(`comparable`)} of the same kind as ${jg(n[p])}`,jg(l),r,{source:i})}}}function bg(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 xg(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 Sg(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 Xh(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||Xh(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||Xh(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||Xh(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 Tg(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function Cg(e){return e}function wg(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 jm(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,jg(e),{line:0,column:0,offset:0})}function Tg(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Eg(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Dg(e,t){let n=Og(e),r=Og(t);return n===`nil`||r===`nil`?!0:n===r}function Og(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 kg(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 Ag(e){return e instanceof Error?e.message:String(e)}function jg(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Mg(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?Ng([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Ng(Object.entries(e)):[]}function Ng(e){return[...e].sort((e,t)=>Pg(e[0],t[0]))}function Pg(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 Fg(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 Ig(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Lg(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 Rg(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 zg(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=Rg(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 Bg(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Rg(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 Vg(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 Hg(e){return JSON.stringify(e)??`null`}function Ug(){return{atoi:{fn:e=>Ig(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>zg(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>Bg(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>Lg(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>Vg(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>Hg(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const Wg={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Gg(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*Wg[a],n=n.slice(e[0].length)}return t?-r:r}function Kg(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Wg.us?`${Math.floor(n)}ns`:n<Wg.ms?qg(n,Wg.us,3,`µs`):n<Wg.s?qg(n,Wg.ms,6,`ms`):Jg(n),t?`-${r}`:r}function qg(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 Jg(e){let t=Math.floor(e/Wg.h);e-=t*Wg.h;let n=Math.floor(e/Wg.m);e-=n*Wg.m;let r=Math.floor(e/Wg.s),i=e-r*Wg.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 Yg(e){return e*Wg.s}function Xg(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 Zg(e,t){let n=t().getTime()-Xg(e).getTime();return Kg(Math.round(n/1e3)*1e9)}const Qg=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],$g=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],e_=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],t_=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function n_(e){return e<10?`0${e}`:String(e)}function r_(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function i_(e){return e<10?` ${e}`:String(e)}function a_(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${n_(Math.floor(n/60))}${n_(n%60)}`}function o_(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${n_(Math.floor(n/60))}:${n_(n%60)}`}function s_(e){return`${e>=0?`+`:`-`}${n_(Math.floor(Math.abs(e)/60))}`}function c_(e){return e===0?`Z`:a_(e)}function l_(e){return e===0?`Z`:o_(e)}function u_(e){return e===0?`Z`:s_(e)}function d_(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const f_=[[`.000000000`,e=>`.${d_(e.ms,9,!1)}`],[`.999999999`,e=>{let t=d_(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${d_(e.ms,6,!1)}`],[`.999999`,e=>{let t=d_(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${r_(e.ms)}`],[`.999`,e=>{let t=r_(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Qg[e.month-1]??`January`],[`Monday`,e=>e_[e.weekday]??`Monday`],[`Z07:00`,e=>l_(e.offsetMinutes)],[`-07:00`,e=>o_(e.offsetMinutes)],[`Z0700`,e=>c_(e.offsetMinutes)],[`-0700`,e=>a_(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>$g[e.month-1]??`Jan`],[`Mon`,e=>t_[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>s_(e.offsetMinutes)],[`Z07`,e=>u_(e.offsetMinutes)],[`15`,e=>n_(e.hour)],[`01`,e=>n_(e.month)],[`02`,e=>n_(e.day)],[`_2`,e=>i_(e.day)],[`03`,e=>n_(e.hour12)],[`04`,e=>n_(e.minute)],[`05`,e=>n_(e.second)],[`06`,e=>n_(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 p_(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of f_)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const m_={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function h_(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const g_=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function __(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=h_(new Intl.DateTimeFormat(`en-US`,{...m_,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=h_(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=v_(h_(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=g_.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 v_(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 y_(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function b_(e,t){return p_(e,__(Xg(t),y_()))}function x_(e,t,n){return p_(e,__(Xg(t),n))}function S_(e,t){let n=Xg(t),r=Gg(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function C_(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Kg(Yg(t))}return typeof e==`bigint`?Kg(Yg(Number(e))):typeof e==`number`?Kg(Yg(e)):`0s`}const w_=36e11*24*365,T_=36e11*24*30,E_=36e11*24,D_=36e11,O_=6e10,k_=1e9;function A_(e){let t=Gg(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>w_?`${Math.floor(n/w_)}y`:n>T_?`${Math.floor(n/T_)}mo`:n>E_?`${Math.floor(n/E_)}d`:n>D_?`${Math.floor(n/D_)}h`:n>O_?`${Math.floor(n/O_)}m`:n>k_?`${Math.floor(n/k_)}s`:`0s`}function j_(e){let t=__(Xg(e),y_());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function M_(e,t){let n=__(Xg(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function N_(e){return e()}const P_=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],F_=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function I_(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function L_(e,t,n){return[e.slice(t,t+n),t+n]}function R_(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 z_(e,t){for(let[n,r]of P_.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function B_(e,t){for(let[n,r]of F_.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function V_(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 H_(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 U_(e,t){if(e[t]===` `){let[n,r]=R_(e,t+1,1,1);return[n,r]}return R_(e,t,1,2)}function W_(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]=R_(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=R_(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=R_(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function G_(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]=R_(e,t+1,2,2);return[n*r*60,i]}return W_(e,t,n)}function K_(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 q_(e,t,n){let[r,i]=L_(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function J_(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=z_(t,n);return i.month=e,[r,i]}case`Monday`:return[V_(t,n),i];case`Jan`:{let[e,r]=B_(t,n);return i.month=e,[r,i]}case`Mon`:return[H_(t,n),i];case`2006`:{let[e,r]=R_(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=R_(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=R_(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=R_(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=U_(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=R_(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=R_(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=R_(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=R_(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=R_(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=R_(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=R_(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=R_(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=R_(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[K_(t,n),i];case`-0700`:{let[e,r]=W_(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=W_(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]=R_(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=G_(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=G_(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=G_(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]=q_(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]=q_(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]=q_(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 Y_=`.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 X_(e,t){let n=0,r=0,i=I_();for(;n<e.length;){let a=!1;for(let o of Y_)if(e.startsWith(o,n)){let[e,s]=J_(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 Z_(e,t){return X_(e,t)}function Q_(e){return String(Math.floor(Xg(e).getTime()/1e3))}function $_(e=()=>new Date){return{now:{fn:()=>N_(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>b_(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>x_(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>S_(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>j_(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>M_(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>C_(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>A_(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>Z_(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>Zg(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>Q_(e),argTypes:[`value`],arity:{kind:`exact`}}}}function ev(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 tv(...e){for(let t of e)if(!ev(t))return t}function nv(e,t){return ev(t)?e:t}function rv(e){return JSON.parse(e)}function iv(e,t,n){return wh(n)?e:t}function av(e){return JSON.stringify(e)??`null`}function ov(e){return JSON.stringify(e,null,2)??`null`}function sv(){return{default:{fn:(e,t)=>nv(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>ev(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>tv(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>iv(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>rv(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>av(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>ov(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function cv(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function lv(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 cv(...t)}function uv(e,t){return e[t]}function dv(e,t){return t in e}function fv(e){return Object.keys(e)}function pv(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 mv(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function hv(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 gv(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function _v(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function vv(e,t,n){return e[t]=n,e}function yv(e,t){return delete e[t],e}function bv(e){return Object.values(e)}function xv(){return{dict:{fn:(...e)=>cv(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>uv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>vv(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>yv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>fv(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>bv(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>_v(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>gv(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>hv(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>dv(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>pv(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>mv(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function Sv(e){throw new Pm(e)}function Cv(){return{fail:{fn:e=>Sv(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 wv(...e){for(let t of e)if(ev(t))return!1;return!0}function Tv(...e){for(let t of e)if(!ev(t))return!0;return!1}function Ev(e,t){return[...e,t]}function Dv(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 Ov(e){return e.filter(e=>!ev(e))}function kv(...e){let t=[];for(let n of e)t.push(...n);return t}const Av={line:0,column:0,offset:0};function jv(e,t,n,r){return new jm(e,t,n,r,Av)}function Mv(...e){if(e.length<3)throw jv(`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(!Pv(t))throw jv(`dig`,e.length-1,`dict`,Fv(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw jv(`dig`,e,`string`,Fv(r[e]));return Nv(t,n,r,e.length)}function Nv(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(!Pv(a))throw jv(`dig`,r-1,`dict at intermediate key`,Fv(a));return Nv(a,t,n.slice(1),r)}function Pv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Fv(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Iv(e){return e[0]}function Lv(e,t){return t.some(t=>bh(t,e))}function Rv(e){return e.slice(0,-1)}function zv(e){return e[e.length-1]}function Bv(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Vv(...e){return e}function Hv(e,t){return[t,...e]}function Uv(e){return e.slice(1)}function Wv(e){return[...e].reverse()}function Gv(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Kv(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function qv(e){let t=[];for(let n of e)t.some(e=>bh(e,n))||t.push(n);return t}function Jv(e,...t){return e.filter(e=>!t.some(t=>bh(t,e)))}function Yv(){return{list:{fn:(...e)=>Vv(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>Iv(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>zv(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>Uv(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>Rv(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>Bv(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>Wv(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>qv(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>Jv(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>Lv(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>Ov(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>Gv(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>kv(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Dv(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>Hv(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>Ev(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>Kv(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>Ev(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>Vv(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>Mv(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>wv(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>Tv(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function Xv(...e){return e.reduce((e,t)=>e+t,0)}function Zv(e){return e+1}function Qv(e){return e+1}function $v(...e){return e.reduce((e,t)=>e+t,0)}function ey(e){return Math.ceil(e)}function ty(e,t){return Math.trunc(e/t)}function ny(e,...t){return t.reduce((e,t)=>e/t,e)}function ry(e){return Math.floor(e)}function iy(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function ay(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function oy(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function sy(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function cy(e,t){return e%t}function ly(...e){return e.reduce((e,t)=>e*t,1)}function uy(...e){return e.reduce((e,t)=>e*t,1)}function dy(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function fy(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 py(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),fy(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return fy(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:fy(n,i+t,r).join(` `)}default:return``}}function my(e,t){return e-t}function hy(e,...t){return t.reduce((e,t)=>e-t,e)}function gy(e){return fy(0,e,e<0?-1:1)}function _y(){return{add:{fn:(...e)=>Xv(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>my(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>ly(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>ty(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>cy(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>oy(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>iy(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>ry(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>ey(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>dy(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>$v(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>hy(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>uy(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>ny(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>Zv(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>Qv(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>ay(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>sy(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>iy(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>py(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>gy(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>fy(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function vy(e){return Array.from(e)}function yy(e,t){return e===``?vy(t):t.split(e)}function by(e,t){let n=vy(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function xy(e,t,n){let r=vy(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},Sy=/^[-_\s]$/,Cy=/^\p{P}$/u,wy=/^\p{L}$/u,Ty=/^\p{Lu}$/u,Ey=/^\p{N}$/u;function Dy(e){return e!==void 0&&Sy.test(e)}function Oy(e){return e!==void 0&&wy.test(e)}function ky(e){return e!==void 0&&Ty.test(e)}function Ay(e){return e!==void 0&&Ey.test(e)}function jy(e){return e!==void 0&&Cy.test(e)}function My(e,t){if(t>=e.length)return{word:{wt:q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(Dy(n)){for(;r<e.length&&Dy(e[r]);)r++;return{word:{wt:q.Connector,text:e.slice(t,r).join(``)},next:r}}if(jy(n)){for(;r<e.length&&jy(e[r]);)r++;return{word:{wt:q.Punct,text:e.slice(t,r).join(``)},next:r}}if(ky(n)){if(r>=e.length)return{word:{wt:q.UpperCase,text:n},next:r};if(ky(e[r])){let n=r;for(;n<e.length&&ky(e[n]);)n++;return n<e.length&&Oy(e[n])?{word:{wt:q.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(Oy(e[r])){let n=r+1;for(;n<e.length&&Oy(e[n])&&!ky(e[n]);)n++;return{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:q.UpperCase,text:n},next:r}}if(Oy(n)){for(;r<e.length&&Oy(e[r])&&!ky(e[r]);)r++;return{word:{wt:q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(Ay(n)){for(;r<e.length&&Ay(e[r]);)r++;return{word:{wt:q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!Dy(e[r])&&!Oy(e[r])&&!Ay(e[r])&&!jy(e[r]);)r++;return{word:{wt:q.Other,text:e.slice(t,r).join(``)},next:r}}function Ny(e,t,n){if(t.wt!==q.UpperCase&&t.wt!==q.Connector){e.push(t.text);return}for(let r of t.text)Dy(r)?e.push(n):ky(r)?e.push(r.toLowerCase()):e.push(r)}function Py(e,t){if(e.length===0)return``;let n=vy(e),r=[],{word:i,next:a}=My(n,0);for(;a<n.length;){i.wt!==q.Connector&&Ny(r,i,t);let e=i,o=i;if({word:i,next:a}=My(n,a),e.wt===q.Number){for(;i.wt===q.Alphabet||i.wt===q.Number;)Ny(r,i,t),{word:i,next:a}=My(n,a);i.wt!==q.Invalid&&i.wt!==q.Punct&&i.wt!==q.Connector&&r.push(t);continue}if(e.wt===q.Connector){Ny(r,o,t);continue}if(e.wt===q.Punct)continue;if(i.wt!==q.Number){i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=My(n,a),i.wt!==q.Alphabet){Ny(r,s,t),i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}for(r.push(t),Ny(r,s,t);i.wt===q.Alphabet||i.wt===q.Number;)Ny(r,i,t),{word:i,next:a}=My(n,a);i.wt!==q.Invalid&&i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t)}return Ny(r,i,t),r.join(``).toLowerCase()}function Fy(e){if(e.length===0)return``;let t=vy(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!Dy(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++,Dy(i)&&Dy(e)){n.push(e);continue}Dy(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Iy(e){return Fy(e)}function Ly(...e){return e.join(` `)}function Ry(e,t){return t.includes(e)}function zy(e,t){return t.startsWith(e)}function By(e,t){return t.endsWith(e)}function Vy(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
53
53
  `).map(e=>n+e).join(`
54
- `)}function Vy(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 Hy(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Av(`join`,2,`list of strings/primitives`,`list element of type ${Uy(e)}`);n.push(String(e))}return n.join(e)}function Uy(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Wy(e){return Ny(e,`-`)}function Gy(e){return e.toLowerCase()}function Ky(e,t){return`\n${By(e,t)}`}function qy(e){return e.replace(/\s+/g,``)}function Jy(e,t,n){return n===1?e:t}function Yy(...e){return e.map(e=>`"${e}"`).join(` `)}function Xy(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Zy(e,t){return t.repeat(Math.max(0,e))}function Qy(e,t,n){return vy(e,n).join(t)}function $y(e){return Ny(e,`_`)}function eb(e,t){let n=vy(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function tb(e,t){return vy(e,t)}function nb(e,t,n){let r=rb(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function rb(e,t,n){if(n===0)return[];let r=vy(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 ib(...e){return e.map(e=>`'${e}'`).join(` `)}function ab(e,t,n){let r=_y(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 ob(e){let t=``;for(let n of e)sb(n)?t+=n.toLowerCase():cb(n)?t+=n.toUpperCase():t+=n;return t}function sb(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function cb(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function lb(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function ub(e){return e.trim()}function db(e,t){if(e.length===0)return t;let n=new Set(_y(e)),r=_y(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 fb(e,t){return t.startsWith(e)?t.slice(e.length):t}function pb(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function mb(e,t){let n=_y(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 hb(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function gb(e){return e.toUpperCase()}function _b(e,t){return vb(e,`
55
- `,t)}function vb(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
56
- `)){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 yb(e,t,n){return vb(e,t,n)}function bb(){return{abbrev:{fn:(e,t)=>yy(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>by(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>Fy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>Iy(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>Ly(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>Ry(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>zy(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>By(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>Vy(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>Hy(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>Wy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>Gy(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>Ky(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>qy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>Jy(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Yy(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>Xy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Zy(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Qy(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>$y(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>eb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>tb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>nb(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>ib(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>ab(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>ob(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>lb(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>ub(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>db(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>fb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>pb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>mb(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>hb(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>gb(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>_b(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>yb(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function xb(e){return e}function Sb(e,t,n){return n===void 0?Sp+bp(e)+`.`+bp(t):Cb(n)}function Cb(e){return Sp+bp(e)}function wb(e,t){return e+`.`+t}function Tb(e){return e+`.page`}const Eb=[`closeOnPick`,`paged`,`key`,`distribution`],Db=e=>Eb.includes(e),Ob=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${js.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function kb(e){for(let t of Object.keys(e))if(!Db(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${Ob}`);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&&!Ms(r))throw Error(`{{ menu }} option "distribution" must be one of: ${js.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Ps(r)}}const Ab=`default`,jb={};function Mb(e){return[...new Set([Ab,...Object.keys(e)])]}function Nb(e,t,n){return Fc(void 0,e,t,Ab,n)}function Pb(e,t){let n={[Ab]:jb,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Ab}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Fb(e,t){let n=Pb(e.presets,t).root??Dd;return{node:jd(Pd(n,e.root)),path:Fd(n)?`presets.${t}.root`:`root`}}function Ib(e,t){return{...e.globals,...Pb(e.presets,t).globals}}const Lb=`menu`,Rb=`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`,zb=e=>e.kind===`call`&&e.name===`dict`,Bb=e=>e.kind===`literal`&&typeof e.value!=`object`,Vb=e=>Hd(``,e,2)===void 0;function Hb(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&&zb(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(zb))return t(`whose options (dict …) is not its last argument — ${Rb}`);if(i!==void 0&&a===void 0&&!Bb(i)&&Vb(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=Hd(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${Rb}`);let c=a===void 0?{}:cv(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=kb(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Dp(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 "${Cb(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 Ub(e){let t=_g({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Lb).map(Hb)}catch{return`parse-failed`}}function Wb(e){let t=_g({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Lb)}catch{return!1}}function Gb(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Kb(e,t){Op(e,t,Sp,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))Wb(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:G(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`&&Wb(i)&&Gb(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of wu(Md(t.root)))typeof n.when==`string`&&Wb(n.when)&&Gb(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||!Wb(r))continue;let n=Ub(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:qb(r.apply);n!==void 0&&Gb(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function qb(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(xb(e)===`closed`)return`whose apply action is named "${Bd}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function Jb(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 Mb(e.presets)){let a=new Map,s=new Map;for(let c of wu(Fb(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,Ub(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=bu(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||qb(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=xb(i),f=Sb(u,i,l.key),p=Tb(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=wb(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]=Qd(f,d),n[f]=Zd(f,Bd),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const Yb=_g({fromString:e=>e}),Xb=`edit.mode`,Zb=`edit.configure`,Qb=`edit.toggle`,$b=`edit.unconfigure`,ex=[Qb,$b],tx=`arrange`,nx=`${Cp}draft.`;function rx(e,t){return`${e}:${t}`}const ix={variable:Xb,key:Xb,member:tx},ax=Kd(ix);function ox(e){try{return Yb.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function sx(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&ox(e))return!0;return!1}function cx(e,t){if(Op(e,t,Cp,`edit mode`),!sx(t))return;let{variables:n,actions:r}=lx();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function lx(){return{variables:{[Xb]:Zd(Xb,Bd),[Zb]:Zd(Zb,Bd)},actions:{[Qb]:Qd(Xb,tx),[$b]:{set:Zb,to:Bd}}}}const ux=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*dx(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const fx=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,px=RegExp(`^(?:(\\$)(?:\\.(${fx}))?|\\.(${fx})?)(?=[\\s)]|$)`);function mx(e,t,n){let r=px.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 hx=/^(\w+)\b\s*([\s\S]*)$/;function*gx(e,t){let n=[t];for(let r of dx(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=hx.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:mx(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(mx(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const _x=/(?<![.$])\btemplate\s+$/;function*vx(e,t,n){let r=0;for(let i of[...e.matchAll(ux)]){let a=i.index+i[0].length;_x.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:mx(e.slice(a),t,n)}),r=a}}function*yx(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...gx(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...vx(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const bx=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${fx})`,`g`);function*xx({code:e,dot:t,root:n}){let r=e.replace(ux,``);for(let e of[...r.matchAll(bx)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function Sx(e,t){let n=new Map;for(let r of yx(e,t))for(let e of xx(r))n.has(e)||n.set(e,r.via);return n}const Cx=/(?<![.$])\b(action|picker|menu|carousel)\s+$/,wx={action:1,picker:2,menu:1,carousel:2};function*Tx(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(ux)]){let o=e.slice(t,a.index),s=Cx.exec(o);if(s!==null)n=wx[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function Ex(e,t){let n=new Map;for(let{code:r,via:i}of yx(e,t))for(let{name:e,site:t}of Tx(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function Dx(e,t){return new Set([...Ox(e,t)].filter(e=>Object.hasOwn(t,e)))}function Ox(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of yx(e,t))for(let{name:e}of vx(r,i,a))n.add(e);return n}function kx(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function Ax(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),jx(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function jx(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&Au(e.parse)===`json`}function Mx(e){let t=l.basename(e),n=l.dirname(e);for(;;){let r=Nx(n);if(r!==null)return{dir:r,name:t,leaf:n===l.dirname(e)};t=l.basename(n),n=l.dirname(n)}}function Nx(e){try{return r.statSync(e).isDirectory()?r.realpathSync(e):null}catch{return null}}var Px=ve((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:an}function r(){dn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===fn}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){sn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){sn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return cn.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(ne())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&re(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ie(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function C(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
54
+ `)}function Hy(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 Uy(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw jv(`join`,2,`list of strings/primitives`,`list element of type ${Wy(e)}`);n.push(String(e))}return n.join(e)}function Wy(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Gy(e){return Py(e,`-`)}function Ky(e){return e.toLowerCase()}function qy(e,t){return`\n${Vy(e,t)}`}function Jy(e){return e.replace(/\s+/g,``)}function Yy(e,t,n){return n===1?e:t}function Xy(...e){return e.map(e=>`"${e}"`).join(` `)}function Zy(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Qy(e,t){return t.repeat(Math.max(0,e))}function $y(e,t,n){return yy(e,n).join(t)}function eb(e){return Py(e,`_`)}function tb(e,t){let n=yy(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function nb(e,t){return yy(e,t)}function rb(e,t,n){let r=ib(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function ib(e,t,n){if(n===0)return[];let r=yy(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 ab(...e){return e.map(e=>`'${e}'`).join(` `)}function ob(e,t,n){let r=vy(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 sb(e){let t=``;for(let n of e)cb(n)?t+=n.toLowerCase():lb(n)?t+=n.toUpperCase():t+=n;return t}function cb(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function lb(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function ub(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function db(e){return e.trim()}function fb(e,t){if(e.length===0)return t;let n=new Set(vy(e)),r=vy(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 pb(e,t){return t.startsWith(e)?t.slice(e.length):t}function mb(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function hb(e,t){let n=vy(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 gb(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function _b(e){return e.toUpperCase()}function vb(e,t){return yb(e,`
55
+ `,t)}function yb(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
56
+ `)){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 bb(e,t,n){return yb(e,t,n)}function xb(){return{abbrev:{fn:(e,t)=>by(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>xy(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>Iy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>Ly(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>Ry(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>zy(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>By(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>Vy(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>Hy(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>Uy(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>Gy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>Ky(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>qy(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>Jy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>Yy(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Xy(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>Zy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Qy(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>$y(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>eb(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>tb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>nb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>rb(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>ab(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>ob(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>sb(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>ub(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>db(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>fb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>pb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>mb(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>hb(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>gb(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>_b(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>vb(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>bb(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Sb(e){return e}function Cb(e,t,n){return n===void 0?Sp+bp(e)+`.`+bp(t):wb(n)}function wb(e){return Sp+bp(e)}function Tb(e,t){return e+`.`+t}function Eb(e){return e+`.page`}const Db=[`closeOnPick`,`paged`,`key`,`distribution`],Ob=e=>Db.includes(e),kb=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${js.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function Ab(e){for(let t of Object.keys(e))if(!Ob(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${kb}`);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&&!Ms(r))throw Error(`{{ menu }} option "distribution" must be one of: ${js.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Ps(r)}}const jb=`default`,Mb={};function Nb(e){return[...new Set([jb,...Object.keys(e)])]}function Pb(e,t,n){return Fc(void 0,e,t,jb,n)}function Fb(e,t){let n={[jb]:Mb,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${jb}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Ib(e,t){let n=Fb(e.presets,t).root??Dd;return{node:jd(Pd(n,e.root)),path:Fd(n)?`presets.${t}.root`:`root`}}function Lb(e,t){return{...e.globals,...Fb(e.presets,t).globals}}const Rb=`menu`,zb=`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`,Bb=e=>e.kind===`call`&&e.name===`dict`,Vb=e=>e.kind===`literal`&&typeof e.value!=`object`,Hb=e=>Hd(``,e,2)===void 0;function Ub(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&&Bb(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(Bb))return t(`whose options (dict …) is not its last argument — ${zb}`);if(i!==void 0&&a===void 0&&!Vb(i)&&Hb(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=Hd(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${zb}`);let c=a===void 0?{}:lv(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=Ab(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Dp(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 "${wb(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 Wb(e){let t=vg({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Rb).map(Ub)}catch{return`parse-failed`}}function Gb(e){let t=vg({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Rb)}catch{return!1}}function Kb(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function qb(e,t){Op(e,t,Sp,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))Gb(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:G(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`&&Gb(i)&&Kb(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of wu(Md(t.root)))typeof n.when==`string`&&Gb(n.when)&&Kb(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||!Gb(r))continue;let n=Wb(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:Jb(r.apply);n!==void 0&&Kb(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function Jb(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(Sb(e)===`closed`)return`whose apply action is named "${Bd}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function Yb(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 Nb(e.presets)){let a=new Map,s=new Map;for(let c of wu(Ib(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,Wb(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=bu(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||Jb(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=Sb(i),f=Cb(u,i,l.key),p=Eb(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=Tb(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]=Qd(f,d),n[f]=Zd(f,Bd),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const Xb=vg({fromString:e=>e}),Zb=`edit.mode`,Qb=`edit.configure`,$b=`edit.toggle`,ex=`edit.unconfigure`,tx=[$b,ex],nx=`arrange`,rx=`${Cp}draft.`;function ix(e,t){return`${e}:${t}`}const ax={variable:Zb,key:Zb,member:nx},ox=Kd(ax);function sx(e){try{return Xb.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function cx(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&sx(e))return!0;return!1}function lx(e,t){if(Op(e,t,Cp,`edit mode`),!cx(t))return;let{variables:n,actions:r}=ux();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function ux(){return{variables:{[Zb]:Zd(Zb,Bd),[Qb]:Zd(Qb,Bd)},actions:{[$b]:Qd(Zb,nx),[ex]:{set:Qb,to:Bd}}}}const dx=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*fx(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const px=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,mx=RegExp(`^(?:(\\$)(?:\\.(${px}))?|\\.(${px})?)(?=[\\s)]|$)`);function hx(e,t,n){let r=mx.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 gx=/^(\w+)\b\s*([\s\S]*)$/;function*_x(e,t){let n=[t];for(let r of fx(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=gx.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:hx(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(hx(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const vx=/(?<![.$])\btemplate\s+$/;function*yx(e,t,n){let r=0;for(let i of[...e.matchAll(dx)]){let a=i.index+i[0].length;vx.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:hx(e.slice(a),t,n)}),r=a}}function*bx(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[..._x(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...yx(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const xx=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${px})`,`g`);function*Sx({code:e,dot:t,root:n}){let r=e.replace(dx,``);for(let e of[...r.matchAll(xx)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function Cx(e,t){let n=new Map;for(let r of bx(e,t))for(let e of Sx(r))n.has(e)||n.set(e,r.via);return n}const wx=/(?<![.$])\b(action|picker|menu|carousel)\s+$/,Tx={action:1,picker:2,menu:1,carousel:2};function*Ex(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(dx)]){let o=e.slice(t,a.index),s=wx.exec(o);if(s!==null)n=Tx[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function Dx(e,t){let n=new Map;for(let{code:r,via:i}of bx(e,t))for(let{name:e,site:t}of Ex(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function Ox(e,t){return new Set([...kx(e,t)].filter(e=>Object.hasOwn(t,e)))}function kx(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of bx(e,t))for(let{name:e}of yx(r,i,a))n.add(e);return n}function Ax(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function jx(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),Mx(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function Mx(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&Au(e.parse)===`json`}function Nx(e){let t=l.basename(e),n=l.dirname(e);for(;;){let r=Px(n);if(r!==null)return{dir:r,name:t,leaf:n===l.dirname(e)};t=l.basename(n),n=l.dirname(n)}}function Px(e){try{return r.statSync(e).isDirectory()?r.realpathSync(e):null}catch{return null}}var Fx=ve((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:an}function r(){dn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===fn}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){sn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){sn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return cn.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(ne())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&re(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ie(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function C(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
57
57
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ee(){return(ee=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(null,arguments)}function w(e){return(w=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function te(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,re(e,t)}function ne(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(ne=function(){return!!e})()}function re(e,t){return(re=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function ie(e){var t=function(e){if(typeof e!=`object`||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var n=t.call(e,`string`);if(typeof n!=`object`)return n;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e);return typeof t==`symbol`?t:t+``}function T(e){var t=typeof Map==`function`?new Map:void 0;return(T=function(e){function n(){return b(e,arguments,w(this).constructor)}if(e===null||!function(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),re(n,e)})(e)}function E(e){return Object.assign((function(t,n){if(oe(n))return e.t(t,n);ae(t,n,e)}),e)}function ae(e,t,n){g(e,gn)||u(e,gn,ee({},e[gn])),function(e){return e.i===`override`}(n)||(e[gn][t]=n)}function oe(e){return typeof e==`object`&&typeof e.kind==`string`}function se(e,t,n){t===void 0&&(t=pn),n===void 0&&(n=pn);var r=new P(e);return t!==pn&&dt(r,t),n!==pn&&ft(r,n),r}function ce(e,t,n){return xt(e)?e:Array.isArray(e)?En.array(e,{name:n}):c(e)?En.object(e,void 0,{name:n}):p(e)?En.map(e,{name:n}):m(e)?En.set(e,{name:n}):typeof e!=`function`||ct(e)||vt(e)?e:l(e)?nr(e):Xn(n,e)}function le(e){return e}function ue(e,t){return{i:e,u:t,o:de,s:fe,t:pe}}function de(e,t,n,r){var i;return(i=this.u)!=null&&i.bound?this.s(e,t,n,!1)===null?0:1:r===e.h?this.s(e,t,n,!1)===null?0:2:ct(n.value)?1:(sn(r,t,me(e,this,t,n,!1)),2)}function fe(e,t,n,r){var i=me(e,this,t,n);return e.l(t,i,r)}function pe(e,n){var r,i=n.kind,a=n.name,o=n.addInitializer,s=this,c=function(e){var t;return Ne(s.u?.name??a.toString(),e,(t=s.u?.autoAction)!=null&&t)};return i==`field`?function(e){var t,n=e;return ct(n)||(n=c(n)),(t=s.u)!=null&&t.bound&&((n=n.bind(this)).isMobxAction=!0),n}:i==`method`?(ct(e)||(e=c(e)),(r=this.u)!=null&&r.bound&&o((function(){var e=this[a].bind(this);e.isMobxAction=!0,this[a]=e})),e):void t(`Cannot apply '`+s.i+`' to '`+String(a)+`' (kind: `+i+`):
58
- '`+s.i+`' can only be used on properties with a function value.`)}function me(e,t,n,r,i){var a,o,s;i===void 0&&(i=z.safeDescriptors);var c=r.value;return(a=t.u)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:Ne(t.u?.name??n.toString(),c,(o=t.u?.autoAction)!=null&&o,(s=t.u)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function he(e,t){return{i:e,u:t,o:ge,s:_e,t:ve}}function ge(e,t,n,r){var i;return r===e.h?this.s(e,t,n,!1)===null?0:2:(i=this.u)!=null&&i.bound&&(!g(e.h,t)||!vt(e.h[t]))&&this.s(e,t,n,!1)===null?0:vt(n.value)?1:(sn(r,t,ye(e,0,0,n,!1,!1)),2)}function _e(e,t,n,r){var i=ye(e,0,0,n,this.u?.bound);return e.l(t,i,r)}function ve(e,t){var n,r=t.name,i=t.addInitializer;return vt(e)||(e=nr(e)),(n=this.u)!=null&&n.bound&&i((function(){var e=this[r].bind(this);e.isMobXFlow=!0,this[r]=e})),e}function ye(e,t,n,r,i,a){a===void 0&&(a=z.safeDescriptors);var o=r.value;return vt(o)||(o=nr(o)),i&&((o=o.bind(e.v??e.h)).isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function be(e,t){return{i:e,u:t,o:D,s:xe,t:Se}}function D(e,t,n){return this.s(e,t,n,!1)===null?0:1}function xe(e,t,n,r){return e.m(t,ee({},this.u,{get:n.get,set:n.set}),r)}function Se(e,t){var n=this,r=t.name;return(0,t.addInitializer)((function(){var t=Ut(this)[N],i=ee({},n.u,{get:e,context:this});i.name||=`ObservableObject.`+r.toString(),t.j.set(r,new Fn(i))})),function(){return this[N].O(r)}}function Ce(e,t){return{i:e,u:t,o:we,s:Te,t:Ee}}function we(e,t,n){return this.s(e,t,n,!1)===null?0:1}function Te(e,t,n,r){return e.g(t,n.value,this.u?.enhancer??ce,r)}function Ee(e,t){function n(e,t){var n=Ut(e)[N],i=new Nn(t,r.u?.enhancer??ce,`ObservableObject.`+a.toString(),!1);n.j.set(a,i),o.add(e)}var r=this,i=t.kind,a=t.name,o=new WeakSet;if(i==`accessor`)return{get:function(){return o.has(this)||n(this,e.get.call(this)),this[N].O(a)},set:function(e){return o.has(this)||n(this,e),this[N].S(a,e)},init:function(e){return o.has(this)||n(this,e),e}}}function De(e){return{i:`true`,u:e,o:Oe,s:ke,t:Ae}}function Oe(e,t,n,r){var i,a,o;if(n.get)return kn.o(e,t,n,r);if(n.set){var s=ct(n.set)?n.set:Ne(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!z.safeDescriptors||e.p,set:s})===null?0:2:(sn(r,t,{configurable:!0,set:s}),2)}if(r!==e.h&&typeof n.value==`function`)return l(n.value)?((o=this.u)!=null&&o.autoBind?nr.bound:nr).o(e,t,n,r):((a=this.u)!=null&&a.autoBind?Xn.bound:Xn).o(e,t,n,r);var c=!1===this.u?.deep?En.ref:En;return typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function ke(e,t,n,r){var i;return n.get?kn.s(e,t,n,r):n.set?e.l(t,{configurable:!z.safeDescriptors||e.p,set:Ne(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.u?.deep?En.ref:En).s(e,t,n,r))}function Ae(){t(`'`+this.i+`' cannot be used as a decorator`)}function je(e){return e||bn}function O(e){return!0===e.deep?ce:!1===e.deep?le:(t=e.defaultDecorator)&&(n=(r=t.u)?.enhancer)!=null?n:ce;var t,n,r}function Me(e,t,n){return oe(t)?xn.t(e,t):o(t)?void ae(e,t,xn):xt(e)?e:c(e)?En.object(e,t,n):Array.isArray(e)?En.array(e,t):p(e)?En.map(e,t):m(e)?En.set(e,t):typeof e==`object`&&e?e:En.box(e,t)}function Ne(e,t,n,r){function i(){return Pe(0,n,t,r||this,arguments)}return n===void 0&&(n=!1),i.isMobxAction=!0,i.toString=function(){return t.toString()},jn&&(Mn.value=e,sn(i,`name`,Mn)),i}function Pe(e,t,n,r,i){var a=Fe(0,t);try{return n.apply(r,i)}catch(e){throw a._=e,e}finally{Ie(a)}}function Fe(e,t){var n=z.trackingDerivation,r=!t||!n;$e();var i=z.allowStateChanges;r&&(Ge(),i=Re(!0));var a={A:r,k:n,M:i,V:qe(!0),R:!1,N:0,T:L++,C:An};return An=a.T,a}function Ie(e){An!==e.T&&t(30),An=e.C,e._!==void 0&&(z.suppressReactionErrors=!0),ze(e.M),Je(e.V),et(),e.A&&Ke(e.k),z.suppressReactionErrors=!1}function Le(e,t){var n=Re(e);try{return t()}finally{ze(n)}}function Re(e){var t=z.allowStateChanges;return z.allowStateChanges=e,t}function ze(e){z.allowStateChanges=e}function Be(e){return e instanceof Rn}function Ve(e){switch(e.I){case R.L:return!1;case R.P:case R.K:return!0;case R.B:for(var t=qe(!0),n=Ge(),r=e.D,i=r.length,a=0;a<i;a++){var o=r[a];if(Ln(o)){if(z.disableErrorBoundaries)o.get();else try{o.get()}catch{return Ke(n),Je(t),!0}if(e.I===R.K)return Ke(n),Je(t),!0}}return Ye(e),Ke(n),Je(t),!1}}function He(e,t,n){var r=qe(!0);Ye(e),e.W=Array(e.q===0?100:e.D.length),e.G=0,e.q=++z.runId;var i,a=z.trackingDerivation;if(z.trackingDerivation=e,z.inBatch++,!0===z.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Rn(e)}return z.inBatch--,z.trackingDerivation=a,function(e){for(var t=e.D,n=e.D=e.W,r=R.L,i=0,a=e.G,o=0;o<a;o++){var s=n[o];s.diffValue===0&&(s.diffValue=1,i!==o&&(n[i]=s),i++),s.I>r&&(r=s.I)}for(n.length=i,e.W=null,a=t.length;a--;){var c=t[a];c.diffValue===0&&Ze(c,e),c.diffValue=0}for(;i--;){var l=n[i];l.diffValue===1&&(l.diffValue=0,Xe(l,e))}r!==R.L&&(e.I=r,e.H())}(e),Je(r),i}function Ue(e){var t=e.D;e.D=[];for(var n=t.length;n--;)Ze(t[n],e);e.I=R.P}function We(e){var t=Ge();try{return e()}finally{Ke(t)}}function Ge(){var e=z.trackingDerivation;return z.trackingDerivation=null,e}function Ke(e){z.trackingDerivation=e}function qe(e){var t=z.allowStateReads;return z.allowStateReads=e,t}function Je(e){z.allowStateReads=e}function Ye(e){if(e.I!==R.L){e.I=R.L;for(var t=e.D,n=t.length;n--;)t[n].U=R.L}}function Xe(e,t){e.F.add(t),e.U>t.I&&(e.U=t.I)}function Ze(e,t){e.F.delete(t),e.F.size===0&&Qe(e)}function Qe(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,z.pendingUnobservations.push(e))}function $e(){z.inBatch++}function et(){if(--z.inBatch==0){rt();for(var e=z.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,n.F.size===0&&(n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof Fn&&n.X())}z.pendingUnobservations=[]}}function tt(e){var t=z.trackingDerivation;return t===null?(e.F.size===0&&z.inBatch>0&&Qe(e),!1):(t.q!==e.$&&(e.$=t.q,t.W[t.G++]=e,!e.isBeingObserved&&z.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function nt(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(e){e.I===R.L&&e.H(),e.I=R.K})))}function rt(){z.inBatch>0||z.isRunningReactions||B(it)}function it(){z.isRunningReactions=!0;for(var e=z.pendingReactions,t=0;e.length>0;){++t==100&&(console.error(`[mobx] cycle in reaction: `+e[0]),e.splice(0));for(var n=e.splice(0),r=0,i=n.length;r<i;r++)n[r].J()}z.isRunningReactions=!1}function at(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}}function ot(e){return function(t,n){return a(t)?Ne(t.name||`<unnamed action>`,t,e):a(n)?Ne(t,n,e):oe(n)?(e?qn:Gn).t(t,n):o(n)?ae(t,n,e?qn:Gn):o(t)?E(ue(e?`autoAction`:`action`,{name:t,autoAction:e})):void 0}}function st(e){return Pe(0,!1,e,this,void 0)}function ct(e){return a(e)&&!0===e.isMobxAction}function lt(e,t){function n(){e(i)}var r;t===void 0&&(t=un);var i,a=t?.name??`Autorun`;if(t.scheduler||t.delay){var o=ut(t),s=!1;i=new Un(a,(function(){s||(s=!0,o((function(){s=!1,i.isDisposed||i.track(n)})))}),t.onError,t.requiresObservable)}else i=new Un(a,(function(){this.track(n)}),t.onError,t.requiresObservable);return(r=t)!=null&&(r=r.signal)!=null&&r.aborted||i.Y(),i.Z(t?.signal)}function ut(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:Zn}function dt(e,t,n){return pt(`onBO`,e,t,n)}function ft(e,t,n){return pt(`onBUO`,e,t,n)}function pt(e,t,n,r){var i=typeof r==`function`?Xt(t,n):Xt(t),o=a(r)?r:n,s=e+`L`;return i[s]?i[s].add(o):i[s]=new Set([o]),function(){var e=i[s];e&&(e.delete(o),e.size===0&&delete i[s])}}function mt(e,t,n,r){var i=M(t);return $t((function(){var t=Ut(e,r)[N];hn(i).forEach((function(e){t.s(e,i[e],!n||!(e in n)||n[e])}))})),e}function ht(e){var t,n={name:e.tt};return e.D&&e.D.length>0&&(n.dependencies=(t=e.D,Array.from(new Set(t))).map(ht)),n}function gt(e){var t={name:e.tt};return function(e){return e.F&&e.F.size>0}(e)&&(t.observers=Array.from(function(e){return e.F}(e)).map(gt)),t}function _t(e){a(e.cancel)&&e.cancel()}function vt(e){return!0===e?.isMobXFlow}function yt(e,t){return t===void 0?Ln(e):!1===Gt(e)||!e[N].j.has(t)?!1:Ln(Xt(e,t))}function bt(e,t){return!!e&&(t===void 0?Gt(e)||!!e[N]||_n(e)||Wn(e)||Ln(e):!!Gt(e)&&e[N].j.has(t))}function xt(e){return bt(e)}function St(e){return Gt(e)?e[N].nt():hr(e)||V(e)?Array.from(e.keys()):Bt(e)?e.map((function(e,t){return t})):void t(5)}function Ct(e,n){return Gt(e)?e[N].it(n):hr(e)||V(e)?e.has(n):Bt(e)?n>=0&&n<e.length:void t(10)}function wt(e){if(Gt(e))return e[N].rt();t(38)}function Tt(e,t,n){return e.set(t,n),n}function Et(e,t){t===void 0&&(t=void 0),$e();try{return e.apply(t)}finally{et()}}function Dt(e,t,n){var r;if(typeof n.timeout==`number`){var i=Error(`WHEN_TIMEOUT`);r=setTimeout((function(){if(!o[N].isDisposed){if(o(),!n.onError)throw i;n.onError(i)}}),n.timeout)}n.name=`When`;var a=Ne(`When-effect`,t),o=lt((function(t){Le(!1,e)&&(t.dispose(),r&&clearTimeout(r),a())}),n);return o}function Ot(e,t){var n,r,i;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Object.assign(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:function(){return null}});var a=new Promise((function(n,a){var o,s=Dt(e,n,ee({},t,{onError:a}));r=function(){s(),a(Error(`WHEN_CANCELLED`))},i=function(){s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)})).finally((function(){var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)}));return a.cancel=r,a}function kt(e){return e[N]}function At(e){return e.et!==void 0&&e.et.length>0}function jt(e,t){var n=e.et||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Mt(e,n){var r=Ge();try{for(var i=[].concat(e.et||[]),a=0,o=i.length;a<o&&((n=i[a](n))&&!n.type&&t(14),n);a++);return n}finally{Ke(r)}}function Nt(e){return e.ut!==void 0&&e.ut.length>0}function Pt(e,t){var n=e.ut||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Ft(e,t){var n=Ge(),r=e.ut;if(r){for(var i=0,a=(r=r.slice()).length;i<a;i++)r[i](t);Ke(n)}}function It(e,t,n,i){return n===void 0&&(n=`ObservableArray`),i===void 0&&(i=!1),r(),$t((function(){var r=new sr(n,t,i,!1);d(r.j,N,r);var a=new Proxy(r.j,or);return r.v=a,e&&e.length&&r.ot(0,0,e),a}))}function Lt(e,t){typeof Array.prototype[e]==`function`&&(cr[e]=t(e))}function Rt(e){return function(){var t=this[N];t.st.reportObserved();var n=t.ft(t.j);return n[e].apply(n,arguments)}}function k(e){return function(t,n){var r=this,i=this[N];return i.st.reportObserved(),i.ft(i.j)[e]((function(e,i){return t.call(n,e,i,r)}))}}function zt(e){return function(){var t=this,n=this[N];n.st.reportObserved();var r=n.ft(n.j),i=arguments[0];return arguments[0]=function(e,n,r){return i(e,n,r,t)},r[e].apply(r,arguments)}}function Bt(e){return s(e)&&dr(e[N])}function Vt(e){return e[Symbol.toStringTag]=`MapIterator`,nn(e)}function Ht(e){return e[Symbol.toStringTag]=`SetIterator`,nn(e)}function Ut(e,t){if(g(e,N))return e;var n=t?.name??`ObservableObject`;return u(e,N,new yr(e,new Map,String(n),function(e){return e?e.defaultDecorator??De(e):void 0}(t))),e}function Wt(e){return vr[e]||(vr[e]={get:function(){return this[N].O(e)},set:function(t){return this[N].S(e,t)}})}function Gt(e){return!!s(e)&&br(e[N])}function A(e,t,n){var r;(r=e.h[gn])==null||delete r[n]}function Kt(e){return{enumerable:!1,configurable:!0,get:function(){return this[N].ct(e)},set:function(t){this[N].ht(e,t)}}}function qt(e){sn(Tr.prototype,``+e,Kt(e))}function Jt(e){if(e>Cr){for(var t=Cr;t<e+100;t++)qt(t);Cr=e}}function Yt(e,t,n){return new Tr(e,t,n)}function Xt(e,n){if(typeof e==`object`&&e){if(Bt(e))return n!==void 0&&t(23),e[N].st;if(V(e))return e.st;if(hr(e)){if(n===void 0)return e.lt;var r=e.vt.get(n)||e.dt.get(n);return r||t(25,n,Qt(e)),r}if(Gt(e)){if(!n)return t(26);var i=e[N].j.get(n);return i||t(27,n,Qt(e)),i}if(_n(e)||Ln(e)||Wn(e))return e}else if(a(e)&&Wn(e[N]))return e[N];t(28)}function Zt(e,n){return e||t(29),n===void 0?_n(e)||Ln(e)||Wn(e)||hr(e)||V(e)?e:e[N]?e[N]:void t(24,e):Zt(Xt(e,n))}function Qt(e,t){var n;if(t!==void 0)n=Xt(e,t);else{if(ct(e))return e.name;n=Gt(e)||hr(e)||V(e)?Zt(e):Xt(e)}return n.tt}function $t(e){var t=Ge(),n=Re(!0);$e();try{return e()}finally{et(),ze(n),Ke(t)}}function en(e,t,n){return n===void 0&&(n=-1),function e(t,n,r,i,o){if(t===n)return t!==0||1/t==1/n;if(t==null||n==null)return!1;if(t!=t)return n!=n;var s=typeof t;if(s!==`function`&&s!==`object`&&typeof n!=`object`)return!1;var c=Er.call(t);if(c!==Er.call(n))return!1;switch(c){case`[object RegExp]`:case`[object String]`:return``+t==``+n;case`[object Number]`:return+t==+t?+t==0?1/t==1/n:+t==+n:+n!=+n;case`[object Date]`:case`[object Boolean]`:return+t==+n;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(t)===Symbol.valueOf.call(n);case`[object Map]`:case`[object Set]`:r>=0&&r++}t=tn(t),n=tn(n);var l=c===`[object Array]`;if(!l){if(typeof t!=`object`||typeof n!=`object`)return!1;var u=t.constructor,d=n.constructor;if(u!==d&&!(a(u)&&u instanceof u&&a(d)&&d instanceof d)&&`constructor`in t&&`constructor`in n)return!1}if(r===0)return!1;r<0&&(r=-1),o||=[];for(var f=(i||=[]).length;f--;)if(i[f]===t)return o[f]===n;if(i.push(t),o.push(n),l){if((f=t.length)!==n.length)return!1;for(;f--;)if(!e(t[f],n[f],r-1,i,o))return!1}else{var p=Object.keys(t),m=p.length;if(Object.keys(n).length!==m)return!1;for(var h=0;h<m;h++){var _=p[h];if(!g(n,_)||!e(t[_],n[_],r-1,i,o))return!1}}return i.pop(),o.pop(),!0}(e,t,n)}function tn(e){return Bt(e)?e.slice():p(e)||hr(e)||m(e)||V(e)?Array.from(e.entries()):e}function nn(e){return e[Symbol.iterator]=rn,Object.assign(Object.create(Dr),e)}function rn(){return this}Object.defineProperty(e,`__esModule`,{value:!0});var an={},j=Object.assign,on=Object.getOwnPropertyDescriptor,sn=Object.defineProperty,cn=Object.prototype,ln=[];Object.freeze(ln);var un={};Object.freeze(un);var dn=typeof Proxy<`u`,fn=Object.toString(),pn=function(){},mn=Object.getOwnPropertySymbols!==void 0,hn=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:mn?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,M=Object.getOwnPropertyDescriptors||function(e){var t={};return hn(e).forEach((function(n){t[n]=on(e,n)})),t},gn=Symbol(`mobx-stored-annotations`),N=Symbol(`mobx administration`),P=function(){function e(e){e===void 0&&(e=`Atom`),this.tt=void 0,this.bt=0,this.F=new Set,this.$=0,this.U=R.P,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return tt(this)},t.reportChanged=function(){$e(),nt(this),et()},t.toString=function(){return this.tt},S(e,[{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();P.pt=1,P.yt=2,P.wt=4;var _n=f(`Atom`,P),vn={identity:function(e,t){return e===t},structural:function(e,t){return en(e,t)},default:function(e,t){return Object.is?Object.is(e,t):e===t?e!==0||1/e==1/t:e!=e&&t!=t},shallow:function(e,t){return en(e,t,1)}},yn=E({i:`override`,o:function(){return 0},s:function(){t(`'`+this.i+`' can only be used with 'makeObservable'`)},t:function(){console.warn(`'`+this.i+`' cannot be used with decorators - this is a no-op`)}}),F=De(),bn={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};Object.freeze(bn);var xn=Ce(`observable`),Sn=Ce(`observable.ref`,{enhancer:le}),I=Ce(`observable.shallow`,{enhancer:function(e,t,n){return e==null||Gt(e)||Bt(e)||hr(e)||V(e)?e:Array.isArray(e)?En.array(e,{name:n,deep:!1}):c(e)?En.object(e,void 0,{name:n,deep:!1}):p(e)?En.map(e,{name:n,deep:!1}):m(e)?En.set(e,{name:n,deep:!1}):void 0}}),Cn=Ce(`observable.struct`,{enhancer:function(e,t){return en(e,t)?t:e}}),wn=E(xn);j(Me,wn);var Tn,En=j(Me,{box:function(e,t){var n=je(t);return new Nn(e,O(n),n.name,!0,n.equals)},array:function(e,t){var n=je(t);return(!1===z.useProxies||!1===n.proxy?Yt:It)(e,O(n),n.name)},map:function(e,t){var n=je(t);return new mr(e,O(n),n.name)},set:function(e,t){var n=je(t);return new _r(e,O(n),n.name)},object:function(e,t,n){return $t((function(){return mt(!1===z.useProxies||!1===n?.proxy?Ut({},n):function(e,t){var n;return r(),(n=(e=Ut(e,t))[N]).v??(n.v=new Proxy(e,rr))}({},n),e,t)}))},ref:E(Sn),shallow:E(I),deep:wn,struct:E(Cn)}),Dn=be(`computed`),On=be(`computed.struct`,{equals:vn.structural}),kn=function(e,t){if(oe(t))return Dn.t(e,t);if(o(t))return ae(e,t,Dn);if(c(e))return E(be(`computed`,e));var n=c(t)?t:{};return n.get=e,n.name||=e.name||``,new Fn(n)};Object.assign(kn,Dn),kn.struct=E(On);var An=0,L=1,jn=(Tn=on((function(){}),`name`)?.configurable)!=null&&Tn,Mn={value:`action`,configurable:!0,writable:!1,enumerable:!1},Nn=function(e){function t(t,n,r,i,a){var o;return r===void 0&&(r=`ObservableValue`),a===void 0&&(a=vn.default),(o=e.call(this,r)||this).enhancer=void 0,o.tt=void 0,o.equals=void 0,o.jt=!1,o.et=void 0,o.ut=void 0,o.Ot=void 0,o.dehancer=void 0,o.enhancer=n,o.tt=r,o.equals=a,o.Ot=n(t,void 0,r),o}te(t,e);var n=t.prototype;return n.dehanceValue=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.set=function(e){(e=this.xt(e))!==z.UNCHANGED&&this.gt(e)},n.xt=function(e){if(At(this)){var t=Mt(this,{object:this,type:ar,newValue:e});if(!t)return z.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.Ot,this.tt),this.equals(this.Ot,e)?z.UNCHANGED:e},n.gt=function(e){var t=this.Ot;this.Ot=e,this.reportChanged(),Nt(this)&&Ft(this,{type:ar,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.Ot)},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t&&e({observableKind:`value`,debugObjectName:this.tt,object:this,type:ar,newValue:this.Ot,oldValue:void 0}),Pt(this,e)},n.raw=function(){return this.Ot},n.toJSON=function(){return this.get()},n.toString=function(){return this.tt+`[`+this.Ot+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},t}(P),Pn=f(`ObservableValue`,Nn),Fn=function(){function e(e){this.I=R.P,this.D=[],this.W=null,this.F=new Set,this.q=0,this.$=0,this.U=R.L,this.G=0,this.Ot=new Rn(null),this.tt=void 0,this.At=void 0,this.bt=0,this.derivation=void 0,this.kt=void 0,this.Mt=In.NONE,this.Et=void 0,this.Vt=void 0,this.Rt=void 0,this.Nt=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.kt=Ne(`ComputedValue-setter`,e.set)),this.Vt=e.equals||(e.compareStructural||e.struct?vn.structural:vn.default),this.Et=e.context,this.Rt=e.requiresReaction,this.Nt=!!e.keepAlive}var n=e.prototype;return n.H=function(){(function(e){e.U===R.L&&(e.U=R.B,e.F.forEach((function(e){e.I===R.L&&(e.I=R.B,e.H())})))})(this)},n.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},n.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},n.get=function(){if(this.isComputing&&t(32,this.tt,this.derivation),z.inBatch!==0||this.F.size!==0||this.Nt){if(tt(this),Ve(this)){var e=z.trackingContext;this.Nt&&!e&&(z.trackingContext=this),this.trackAndCompute()&&function(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(t){t.I===R.B?t.I=R.K:t.I===R.L&&(e.U=R.L)})))}(this),z.trackingContext=e}}else Ve(this)&&(this.Tt(),$e(),this.Ot=this.Ct(!1),et());var n=this.Ot;if(Be(n))throw n.cause;return n},n.set=function(e){if(this.kt){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.kt.call(this.Et,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)},n.trackAndCompute=function(){var e=this.Ot,t=this.I===R.P,n=this.Ct(!0),r=t||Be(e)||Be(n)||!this.Vt(e,n);return r&&(this.Ot=n),r},n.Ct=function(e){this.isComputing=!0;var t,n=Re(!1);if(e)t=He(this,this.derivation,this.Et);else if(!0===z.disableErrorBoundaries)t=this.derivation.call(this.Et);else try{t=this.derivation.call(this.Et)}catch(e){t=new Rn(e)}return ze(n),this.isComputing=!1,t},n.X=function(){this.Nt||(Ue(this),this.Ot=void 0)},n._t=function(e,t){var n=this,r=!0,i=void 0;return lt((function(){var a=n.get();if(!r||t){var o=Ge();e({observableKind:`computed`,debugObjectName:n.tt,type:ar,object:n,newValue:a,oldValue:i}),Ke(o)}r=!1,i=a}))},n.Tt=function(){},n.toString=function(){return this.tt+`[`+this.derivation.toString()+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},S(e,[{key:`isComputing`,get:function(){return _(this.bt,e.It)},set:function(t){this.bt=v(this.bt,e.It,t)}},{key:`isRunningSetter`,get:function(){return _(this.bt,e.Lt)},set:function(t){this.bt=v(this.bt,e.Lt,t)}},{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Fn.It=1,Fn.Lt=2,Fn.pt=4,Fn.yt=8,Fn.wt=16;var R,In,Ln=f(`ComputedValue`,Fn);(function(e){e[e.P=-1]=`NOT_TRACKING_`,e[e.L=0]=`UP_TO_DATE_`,e[e.B=1]=`POSSIBLY_STALE_`,e[e.K=2]=`STALE_`})(R||={}),function(e){e[e.NONE=0]=`NONE`,e[e.LOG=1]=`LOG`,e[e.BREAK=2]=`BREAK`}(In||={});var Rn=function(e){this.cause=void 0,this.cause=e},zn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`,`useProxies`],Bn=function(){this.version=6,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.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.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Vn=!0,Hn=!1,z=function(){var e=n();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Vn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==new Bn().version&&(Vn=!1),Vn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Bn):(setTimeout((function(){Hn||t(35)}),1),new Bn)}(),Un=function(){function e(e,t,n,r){e===void 0&&(e=`Reaction`),this.tt=void 0,this.Pt=void 0,this.Kt=void 0,this.Bt=void 0,this.D=[],this.W=[],this.I=R.P,this.q=0,this.G=0,this.bt=0,this.Mt=In.NONE,this.tt=e,this.Pt=t,this.Kt=n,this.Bt=r}var t=e.prototype;return t.H=function(){this.Y()},t.Y=function(){this.isScheduled||(this.isScheduled=!0,z.pendingReactions.push(this),rt())},t.J=function(){if(!this.isDisposed){$e(),this.isScheduled=!1;var e=z.trackingContext;if(z.trackingContext=this,Ve(this)){this.isTrackPending=!0;try{this.Pt()}catch(e){this.Dt(e)}}z.trackingContext=e,et()}},t.track=function(e){if(!this.isDisposed){$e(),this.isRunning=!0;var t=z.trackingContext;z.trackingContext=this;var n=He(this,e,void 0);z.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ue(this),Be(n)&&this.Dt(n.cause),et()}},t.Dt=function(e){var t=this;if(this.Kt)this.Kt(e,this);else{if(z.disableErrorBoundaries)throw e;z.suppressReactionErrors||console.error(`[mobx] uncaught error in '`+this+`'`,e),z.globalReactionErrorHandlers.forEach((function(n){return n(e,t)}))}},t.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.isRunning||($e(),Ue(this),et()))},t.Z=function(e){var t=this,n=function n(){t.dispose(),e==null||e.removeEventListener==null||e.removeEventListener(`abort`,n)};return e==null||e.addEventListener==null||e.addEventListener(`abort`,n),n[N]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(n[Symbol.dispose]=n),n},t.toString=function(){return`Reaction[`+this.tt+`]`},t.trace=function(){},S(e,[{key:`isDisposed`,get:function(){return _(this.bt,e.Wt)},set:function(t){this.bt=v(this.bt,e.Wt,t)}},{key:`isScheduled`,get:function(){return _(this.bt,e.qt)},set:function(t){this.bt=v(this.bt,e.qt,t)}},{key:`isTrackPending`,get:function(){return _(this.bt,e.Gt)},set:function(t){this.bt=v(this.bt,e.Gt,t)}},{key:`isRunning`,get:function(){return _(this.bt,e.Ht)},set:function(t){this.bt=v(this.bt,e.Ht,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Un.Wt=1,Un.qt=2,Un.Gt=4,Un.Ht=8,Un.wt=16;var B=function(e){return e()},Wn=f(`Reaction`,Un),Gn=ue(`action`),Kn=ue(`action.bound`,{bound:!0}),qn=ue(`autoAction`,{autoAction:!0}),Jn=ue(`autoAction.bound`,{autoAction:!0,bound:!0}),Yn=ot(!1);Object.assign(Yn,Gn);var Xn=ot(!0);Object.assign(Xn,qn),Yn.bound=E(Kn),Xn.bound=E(Jn);var Zn=function(e){return e()},Qn=0,$n=function(e){function t(){var n;return n=e.call(this,`FLOW_CANCELLED`)||this,Object.setPrototypeOf(n,(this instanceof t?this.constructor:void 0).prototype),n.name=`FlowCancellationError`,n}return te(t,e),t.prototype.toString=function(){return`Error: `+this.message},t}(T(Error)),er=he(`flow`),tr=he(`flow.bound`,{bound:!0}),nr=Object.assign((function(e,t){if(oe(t))return er.t(e,t);if(o(t))return ae(e,t,er);var n=e,r=n.name||`<unnamed flow>`,i=function(){var e,t=this,i=arguments,o=++Qn,s=Yn(r+` - runid: `+o+` - init`,n).apply(t,i),c=void 0,l=new Promise((function(t,n){function i(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.next).call(s,e)}catch(e){return n(e)}u(t)}function l(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.throw).call(s,e)}catch(e){return n(e)}u(t)}function u(e){if(!a(e?.then))return e.done?t(e.value):(c=Promise.resolve(e.value)).then(i,l);e.then(u,n)}var d=0;e=n,i(void 0)}));return l.cancel=Yn(r+` - runid: `+o+` - cancel`,(function(){try{c&&_t(c);var t=s.return(void 0),n=Promise.resolve(t.value);n.then(pn,pn),_t(n),e(new $n)}catch(t){e(t)}})),l};return i.isMobXFlow=!0,i}),er);nr.bound=E(tr);var rr={has:function(e,t){return kt(e).it(t)},get:function(e,t){return kt(e).ct(t)},set:function(e,t,n){var r;return!!o(t)&&((r=kt(e).ht(t,n,!0))==null||r)},deleteProperty:function(e,t){var n;return!!o(t)&&((n=kt(e).Ut(t,!0))==null||n)},defineProperty:function(e,t,n){var r;return(r=kt(e).l(t,n))==null||r},ownKeys:function(e){return kt(e).rt()},preventExtensions:function(){t(13)}},ir=Symbol(`mobx-keys`),ar=`update`,or={get:function(e,t){var n=e[N];return t===N?n:t===`length`?n.Ft():typeof t!=`string`||isNaN(t)?g(cr,t)?cr[t]:e[t]:n.ct(parseInt(t))},set:function(e,t,n){var r=e[N];return t===`length`&&r.Xt(n),typeof t==`symbol`||isNaN(t)?e[t]=n:r.ht(parseInt(t),n),!0},preventExtensions:function(){t(15)}},sr=function(){function e(e,t,n,r){e===void 0&&(e=`ObservableArray`),this.zt=void 0,this.$t=void 0,this.st=void 0,this.j=[],this.et=void 0,this.ut=void 0,this.Jt=void 0,this.dehancer=void 0,this.v=void 0,this.Yt=0,this.zt=n,this.$t=r,this.st=new P(e),this.Jt=function(e,n){return t(e,n,`ObservableArray[..]`)}}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.ft=function(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t===void 0&&(t=!1),t&&e({observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:0,added:this.j.slice(),addedCount:this.j.length,removed:[],removedCount:0}),Pt(this,e)},n.Ft=function(){return this.st.reportObserved(),this.j.length},n.Xt=function(e){(typeof e!=`number`||isNaN(e)||e<0)&&t(`Out of range: `+e);var n=this.j.length;if(e!==n)if(e>n){for(var r=Array(e-n),i=0;i<e-n;i++)r[i]=void 0;this.ot(n,0,r)}else this.ot(e,n-e)},n.Zt=function(e,n){e!==this.Yt&&t(16),this.Yt+=n,this.$t&&n>0&&Jt(e+n+1)},n.ot=function(e,t,n){var r=this,i=this.j.length;if(e===void 0?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=arguments.length===1?i-e:t==null?0:Math.max(0,Math.min(t,i-e)),n===void 0&&(n=ln),At(this)){var a=Mt(this,{object:this.v,type:`splice`,index:e,removedCount:t,added:n});if(!a)return ln;t=a.removedCount,n=a.added}if(n=n.length===0?n:n.map((function(e){return r.Jt(e,void 0)})),this.$t){var o=n.length-t;this.Zt(i,o)}var s=this.tn(e,t,n);return t===0&&n.length===0||this.nn(e,n,s),this.ft(s)},n.tn=function(e,t,n){var r;if(n.length<1e4)return(r=this.j).splice.apply(r,[e,t].concat(n));var i=this.j.slice(e,e+t),a=this.j.slice(e+t);this.j.length+=n.length-t;for(var o=0;o<n.length;o++)this.j[e+o]=n[o];for(var s=0;s<a.length;s++)this.j[e+n.length+s]=a[s];return i},n.in=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,type:ar,debugObjectName:this.st.tt,index:e,newValue:t,oldValue:n}:null;this.st.reportChanged(),i&&Ft(this,a)},n.nn=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.st.reportChanged(),i&&Ft(this,a)},n.ct=function(e){if(!(this.$t&&e>=this.j.length))return this.st.reportObserved(),this.Qt(this.j[e]);console.warn(`[mobx] Out of bounds read: `+e)},n.ht=function(e,n){var r=this.j;if(this.$t&&e>r.length&&t(17,e,r.length),e<r.length){var i=r[e];if(At(this)){var a=Mt(this,{type:ar,object:this.v,index:e,newValue:n});if(!a)return;n=a.newValue}(n=this.Jt(n,i))!==i&&(r[e]=n,this.in(e,n,i))}else{for(var o=Array(e+1-r.length),s=0;s<o.length-1;s++)o[s]=void 0;o[o.length-1]=n,this.ot(r.length,0,o)}},e}(),cr={clear:function(){return this.splice(0)},replace:function(e){var t=this[N];return t.ot(0,t.j.length,e)},toJSON:function(){return this.slice()},splice:function(e,t){var n=[...arguments].slice(2),r=this[N];switch(arguments.length){case 0:return[];case 1:return r.ot(e);case 2:return r.ot(e,t)}return r.ot(e,t,n)},spliceWithArray:function(e,t,n){return this[N].ot(e,t,n)},push:function(){for(var e=this[N],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(e.j.length,0,n),e.j.length},pop:function(){return this.splice(Math.max(this[N].j.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=this[N],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(0,0,n),e.j.length},reverse:function(){return z.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort:function(){z.trackingDerivation&&t(37,`sort`);var e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove:function(e){var t=this[N],n=t.ft(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};Lt(`at`,Rt),Lt(`concat`,Rt),Lt(`flat`,Rt),Lt(`includes`,Rt),Lt(`indexOf`,Rt),Lt(`join`,Rt),Lt(`lastIndexOf`,Rt),Lt(`slice`,Rt),Lt(`toString`,Rt),Lt(`toLocaleString`,Rt),Lt(`toSorted`,Rt),Lt(`toSpliced`,Rt),Lt(`with`,Rt),Lt(`every`,k),Lt(`filter`,k),Lt(`find`,k),Lt(`findIndex`,k),Lt(`findLast`,k),Lt(`findLastIndex`,k),Lt(`flatMap`,k),Lt(`forEach`,k),Lt(`map`,k),Lt(`some`,k),Lt(`toReversed`,k),Lt(`reduce`,zt),Lt(`reduceRight`,zt);var lr,ur,dr=f(`ObservableArrayAdministration`,sr),fr={},pr=`add`,mr=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableMap`),this.Jt=void 0,this.tt=void 0,this[N]=fr,this.vt=void 0,this.dt=void 0,this.lt=void 0,this.et=void 0,this.ut=void 0,this.dehancer=void 0,this.Jt=n,this.tt=r,a(Map)||t(18),$t((function(){i.lt=se(`ObservableMap.keys()`),i.vt=new Map,i.dt=new Map,e&&i.merge(e)}))}var n=e.prototype;return n.it=function(e){return this.vt.has(e)},n.has=function(e){var t=this;if(!z.trackingDerivation)return this.it(e);var n=this.dt.get(e);if(!n){var r=n=new Nn(this.it(e),le,`ObservableMap.key?`,!1);this.dt.set(e,r),ft(r,(function(){return t.dt.delete(e)}))}return n.get()},n.set=function(e,t){var n=this.it(e);if(At(this)){var r=Mt(this,{type:n?ar:pr,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.rn(e,t):this.en(e,t),this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,name:e}))return!1;if(this.it(e)){var n=Nt(this),r=n?{observableKind:`map`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:this.vt.get(e).Ot,name:e}:null;return Et((function(){var n;t.lt.reportChanged(),(n=t.dt.get(e))==null||n.gt(!1),t.vt.get(e).gt(void 0),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.rn=function(e,t){var n=this.vt.get(e);if((t=n.xt(t))!==z.UNCHANGED){var r=Nt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:ar,object:this,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),r&&Ft(this,i)}},n.en=function(e,t){var n=this;Et((function(){var r,i=new Nn(t,n.Jt,`ObservableMap.key`,!1);n.vt.set(e,i),t=i.Ot,(r=n.dt.get(e))==null||r.gt(!0),n.lt.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`map`,debugObjectName:this.tt,type:pr,object:this,name:e,newValue:t}:null)},n.get=function(e){return this.has(e)?this.Qt(this.vt.get(e).get()):this.Qt(void 0)},n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.keys=function(){return this.lt.reportObserved(),this.vt.keys()},n.values=function(){var e=this,t=this.keys();return Vt({next:function(){var n=t.next(),r=n.done;return{done:r,value:r?void 0:e.get(n.value)}}})},n.entries=function(){var e=this,t=this.keys();return Vt({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:[i,e.get(i)]}}})},n[Symbol.iterator]=function(){return this.entries()},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i[1],i[0],this)}},n.merge=function(e){var n=this;return hr(e)&&(e=new Map(e)),Et((function(){var r,i;c(e)?function(e){var t=Object.keys(e);if(!mn)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter((function(t){return cn.propertyIsEnumerable.call(e,t)}))):t}(e).forEach((function(t){return n.set(t,e[t])})):Array.isArray(e)?e.forEach((function(e){return n.set(e[0],e[1])})):p(e)?(r=Object.getPrototypeOf(e),i=Object.getPrototypeOf(r),Object.getPrototypeOf(i)!==null&&t(19,e),e.forEach((function(e,t){return n.set(t,e)}))):e!=null&&t(20,e)})),this},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.keys());!(t=n()).done;)e.delete(t.value)}))}))},n.replace=function(e){var n=this;return Et((function(){for(var r,i=function(e){if(p(e)||hr(e))return e;if(Array.isArray(e))return new Map(e);if(c(e)){var n=new Map;for(var r in e)n.set(r,e[r]);return n}return t(21,e)}(e),a=new Map,o=!1,s=C(n.vt.keys());!(r=s()).done;){var l=r.value;if(!i.has(l))if(n.delete(l))o=!0;else{var u=n.vt.get(l);a.set(l,u)}}for(var d,f=C(i.entries());!(d=f()).done;){var m=d.value,h=m[0],g=m[1],_=n.vt.has(h);if(n.set(h,g),n.vt.has(h)){var v=n.vt.get(h);a.set(h,v),_||(o=!0)}}if(!o)if(n.vt.size!==a.size)n.lt.reportChanged();else for(var y=n.vt.keys(),b=a.keys(),x=y.next(),S=b.next();!x.done;){if(x.value!==S.value){n.lt.reportChanged();break}x=y.next(),S=b.next()}n.vt=a})),this},n.toString=function(){return`[object ObservableMap]`},n.toJSON=function(){return Array.from(this)},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},S(e,[{key:`size`,get:function(){return this.lt.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Map`}}])}(),hr=f(`ObservableMap`,mr),gr={},_r=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableSet`),this.tt=void 0,this[N]=gr,this.vt=new Set,this.st=void 0,this.ut=void 0,this.et=void 0,this.dehancer=void 0,this.Jt=void 0,this.tt=r,a(Set)||t(22),this.Jt=function(e,t){return n(e,t,r)},$t((function(){i.st=se(i.tt),e&&i.replace(e)}))}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.vt.values());!(t=n()).done;)e.delete(t.value)}))}))},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i,i,this)}},n.add=function(e){var t=this;if(At(this)){var n=Mt(this,{type:pr,object:this,newValue:e});if(!n)return this;e=n.newValue}if(!this.has(e)){Et((function(){t.vt.add(t.Jt(e,void 0)),t.st.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`set`,debugObjectName:this.tt,type:pr,object:this,newValue:e}:null)}return this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,oldValue:e}))return!1;if(this.has(e)){var n=Nt(this),r=n?{observableKind:`set`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:e}:null;return Et((function(){t.st.reportChanged(),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.has=function(e){return this.st.reportObserved(),this.vt.has(this.Qt(e))},n.entries=function(){var e=this.values();return Ht({next:function(){var t=e.next(),n=t.value,r=t.done;return r?{value:void 0,done:r}:{value:[n,n],done:r}}})},n.keys=function(){return this.values()},n.values=function(){this.st.reportObserved();var e=this,t=this.vt.values();return Ht({next:function(){var n=t.next(),r=n.done;return r?{value:void 0,done:r}:{value:e.Qt(n.value),done:r}}})},n.intersection=function(e){return m(e)&&!V(e)?e.intersection(this):new Set(this).intersection(e)},n.union=function(e){return m(e)&&!V(e)?e.union(this):new Set(this).union(e)},n.difference=function(e){return new Set(this).difference(e)},n.symmetricDifference=function(e){return m(e)&&!V(e)?e.symmetricDifference(this):new Set(this).symmetricDifference(e)},n.isSubsetOf=function(e){return new Set(this).isSubsetOf(e)},n.isSupersetOf=function(e){return new Set(this).isSupersetOf(e)},n.isDisjointFrom=function(e){return m(e)&&!V(e)?e.isDisjointFrom(this):new Set(this).isDisjointFrom(e)},n.replace=function(e){var n=this;return V(e)&&(e=new Set(e)),Et((function(){Array.isArray(e)||m(e)?(n.clear(),e.forEach((function(e){return n.add(e)}))):e!=null&&t(`Cannot initialize set from `+e)})),this},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.toJSON=function(){return Array.from(this)},n.toString=function(){return`[object ObservableSet]`},n[Symbol.iterator]=function(){return this.values()},S(e,[{key:`size`,get:function(){return this.st.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Set`}}])}(),V=f(`ObservableSet`,_r),vr=Object.create(null),yr=function(){function e(e,t,n,r){t===void 0&&(t=new Map),r===void 0&&(r=F),this.h=void 0,this.j=void 0,this.tt=void 0,this.un=void 0,this.lt=void 0,this.ut=void 0,this.et=void 0,this.v=void 0,this.p=void 0,this.on=void 0,this.sn=void 0,this.h=e,this.j=t,this.tt=n,this.un=r,this.lt=new P(`ObservableObject.keys`),this.p=c(this.h)}var n=e.prototype;return n.O=function(e){return this.j.get(e).get()},n.S=function(e,t){var n=this.j.get(e);if(n instanceof Fn)return n.set(t),!0;if(At(this)){var r=Mt(this,{type:ar,object:this.v||this.h,name:e,newValue:t});if(!r)return null;t=r.newValue}if((t=n.xt(t))!==z.UNCHANGED){var i=Nt(this),a=i?{type:ar,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),i&&Ft(this,a)}return!0},n.ct=function(e){return z.trackingDerivation&&!g(this.h,e)&&this.it(e),this.h[e]},n.ht=function(e,t,n){return n===void 0&&(n=!1),g(this.h,e)?this.j.has(e)?this.S(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.s(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.un,n)},n.it=function(e){if(!z.trackingDerivation)return e in this.h;this.sn||=new Map;var t=this.sn.get(e);return t||(t=new Nn(e in this.h,le,`ObservableObject.key?`,!1),this.sn.set(e,t)),t.get()},n.o=function(e,n){if(!0===n&&(n=this.un),!1!==n){if(!(e in this.h)){var r;if((r=this.h[gn])!=null&&r[e])return;t(1,n.i,this.tt+`.`+e.toString())}for(var i=this.h;i&&i!==cn;){var a=on(i,e);if(a){var o=n.o(this,e,a,i);if(o===0)return;if(o===1)break}i=Object.getPrototypeOf(i)}A(this,0,e)}},n.s=function(e,t,n,r){if(r===void 0&&(r=!1),!0===n&&(n=this.un),!1===n)return this.l(e,t,r);var i=n.s(this,e,t,r);return i&&A(this,0,e),i},n.l=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)){var i=Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:t.value});if(!i)return null;var a=i.newValue;t.value!==a&&(t=ee({},t,{value:a}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else sn(this.h,e,t);this.fn(e,t.value)}finally{et()}return!0},n.g=function(e,t,n,r){r===void 0&&(r=!1);try{$e();var i=this.Ut(e);if(!i)return i;if(At(this)){var a=Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:t});if(!a)return null;t=a.newValue}var o=Wt(e),s={configurable:!z.safeDescriptors||this.p,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.h,e,s))return!1}else sn(this.h,e,s);var c=new Nn(t,n,`ObservableObject.key`,!1);this.j.set(e,c),this.fn(e,c.Ot)}finally{et()}return!0},n.m=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;var i=Wt(e),a={configurable:!z.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else sn(this.h,e,a);this.j.set(e,new Fn(t)),this.fn(e,void 0)}finally{et()}return!0},n.Ut=function(e,t){if(t===void 0&&(t=!1),!g(this.h,e))return!0;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:`remove`}))return null;try{var n;$e();var r=Nt(this),i=this.j.get(e),a=void 0;if(!i&&r&&(a=on(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 Nn&&(a=i.Ot),nt(i)),this.lt.reportChanged(),(n=this.sn)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&Ft(this,{type:`remove`,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{et()}return!0},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.fn=function(e,t){var n,r=Nt(this);r&&r&&Ft(this,r?{type:pr,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.sn)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()},n.rt=function(){return this.lt.reportObserved(),hn(this.h)},n.nt=function(){return this.lt.reportObserved(),Object.keys(this.h)},e}(),br=f(`ObservableObjectAdministration`,yr),xr=Kt(0),Sr=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,!1===e}(),Cr=0,wr=function(){};lr=wr,ur=Array.prototype,Object.setPrototypeOf?Object.setPrototypeOf(lr.prototype,ur):lr.prototype.__proto__===void 0?lr.prototype=ur:lr.prototype.__proto__=ur;var Tr=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray`),i===void 0&&(i=!1),a=e.call(this)||this,$t((function(){var e=new sr(r,n,i,!0);e.v=a,d(a,N,e),t&&t.length&&a.spliceWithArray(0,0,t),Sr&&Object.defineProperty(a,`0`,xr)})),a}te(t,e);var n=t.prototype;return n.concat=function(){this[N].st.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map((function(e){return Bt(e)?e.slice():e})))},n[Symbol.iterator]=function(){var e=this,t=0;return nn({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},S(t,[{key:`length`,get:function(){return this[N].Ft()},set:function(e){this[N].Xt(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(wr);Object.entries(cr).forEach((function(e){var t=e[0];t!==`concat`&&u(Tr.prototype,t,e[1])})),Jt(1e3);var Er=cn.toString,Dr=n().Iterator?.prototype||{};[`Symbol`,`Map`,`Set`].forEach((function(e){n()[e]===void 0&&t(`MobX requires global '`+e+`' to be available or polyfilled`)})),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:at,extras:{getDebugName:Qt},$mobx:N}),e.$mobx=N,e.FlowCancellationError=$n,e.ObservableMap=mr,e.ObservableSet=_r,e.Reaction=Un,e._allowStateChanges=Le,e._allowStateChangesInsideComputed=st,e._allowStateReadsEnd=Je,e._allowStateReadsStart=qe,e._autoAction=Xn,e._endAction=Ie,e._getAdministration=Zt,e._getGlobalState=function(){return z},e._interceptReads=function(e,t,n){var r;return hr(e)||Bt(e)||Pn(e)?r=Zt(e):Gt(e)&&(r=Zt(e,t)),r.dehancer=typeof t==`function`?t:n,function(){r.dehancer=void 0}},e._isComputingDerivation=function(){return z.trackingDerivation!==null},e._resetGlobalState=function(){var e=new Bn;for(var t in e)zn.indexOf(t)===-1&&(z[t]=e[t]);z.allowStateChanges=!z.enforceActions},e._startAction=Fe,e.action=Yn,e.autorun=lt,e.comparer=vn,e.computed=kn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((z.pendingReactions.length||z.inBatch||z.isRunningReactions)&&t(36),Hn=!0,Vn){var e=n();--e.__mobxInstanceCount==0&&(e.__mobxGlobals=void 0),z=new Bn}}();var r,i,a=e.useProxies,o=e.enforceActions;if(a!==void 0&&(z.useProxies=a===`always`||a!==`never`&&typeof Proxy<`u`),a===`ifavailable`&&(z.verifyProxies=!0),o!==void 0){var s=o===`always`?`always`:o===`observed`;z.enforceActions=s,z.allowStateChanges=!0!==s&&s!==`always`}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach((function(t){t in e&&(z[t]=!!e[t])})),z.allowStateReads=!z.observableRequiresReaction,e.reactionScheduler&&(r=e.reactionScheduler,i=B,B=function(e){return r((function(){return i(e)}))})},e.createAtom=se,e.defineProperty=function(e,n,r){if(Gt(e))return e[N].l(n,r);t(39)},e.entries=function(e){return Gt(e)?St(e).map((function(t){return[t,e[t]]})):hr(e)?St(e).map((function(t){return[t,e.get(t)]})):V(e)?Array.from(e.entries()):Bt(e)?e.map((function(e,t){return[t,e]})):void t(7)},e.extendObservable=mt,e.flow=nr,e.flowResult=function(e){return e},e.get=function(e,n){if(Ct(e,n))return Gt(e)?e[N].ct(n):hr(e)?e.get(n):Bt(e)?e[n]:void t(11)},e.getAtom=Xt,e.getDebugName=Qt,e.getDependencyTree=function(e,t){return ht(Xt(e,t))},e.getObserverTree=function(e,t){return gt(Xt(e,t))},e.has=Ct,e.intercept=function(e,t,n){return a(n)?function(e,t,n){return Zt(e,t).St(n)}(e,t,n):function(e,t){return Zt(e).St(t)}(e,t)},e.isAction=ct,e.isBoxedObservable=Pn,e.isComputed=function(e){return yt(e)},e.isComputedProp=function(e,t){return yt(e,t)},e.isFlow=vt,e.isFlowCancellationError=function(e){return e instanceof $n},e.isObservable=xt,e.isObservableArray=Bt,e.isObservableMap=hr,e.isObservableObject=Gt,e.isObservableProp=function(e,t){return bt(e,t)},e.isObservableSet=V,e.keys=St,e.makeAutoObservable=function(e,t,n){return c(e)?mt(e,e,t,n):($t((function(){var r=Ut(e,n)[N];if(!e[ir]){var i=Object.getPrototypeOf(e),a=new Set([].concat(hn(e),hn(i)));a.delete(`constructor`),a.delete(N),u(i,ir,a)}e[ir].forEach((function(e){return r.o(e,!t||!(e in t)||t[e])}))})),e)},e.makeObservable=function(e,t,n){return $t((function(){var r=Ut(e,n)[N];t??=function(e){return g(e,gn)||u(e,gn,ee({},e[gn])),e[gn]}(e),hn(t).forEach((function(e){return r.o(e,t[e])}))})),e},e.observable=En,e.observe=function(e,t,n,r){return a(n)?function(e,t,n,r){return Zt(e,t)._t(n,r)}(e,t,n,r):function(e,t,n){return Zt(e)._t(t,n)}(e,t,n)},e.onBecomeObserved=dt,e.onBecomeUnobserved=ft,e.onReactionError=function(e){return z.globalReactionErrorHandlers.push(e),function(){var t=z.globalReactionErrorHandlers.indexOf(e);t>=0&&z.globalReactionErrorHandlers.splice(t,1)}},e.override=yn,e.ownKeys=wt,e.reaction=function(e,t,n){function r(){if(p=!1,!h.isDisposed){var t=!1,r=s;h.track((function(){var n=Le(!1,(function(){return e(h)}));t=f||!m(s,n),s=n})),(f&&n.fireImmediately||!f&&t)&&l(s,r,h),f=!1}}var i;n===void 0&&(n=un);var a,o,s,c=n.name??`Reaction`,l=Yn(c,n.onError?(a=n.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){a.call(this,e)}}):t),u=!n.scheduler&&!n.delay,d=ut(n),f=!0,p=!1,m=n.compareStructural?vn.structural:n.equals||vn.default,h=new Un(c,(function(){f||u?r():p||(p=!0,d(r))}),n.onError,n.requiresObservable);return(i=n)!=null&&(i=i.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Gt(e)?e[N].Ut(n):hr(e)||V(e)?e.delete(n):Bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=st,e.set=function e(n,r,i){if(arguments.length!==2||V(n))Gt(n)?n[N].ht(r,i):hr(n)?n.set(r,i):V(n)?n.add(r):Bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(`Invalid index: '`+r+`'`),$e(),r>=n.length&&(n.length=r+1),n[r]=i,et()):t(8);else{$e();var a=r;try{for(var o in a)e(n,o,a[o])}finally{et()}}},e.spy=at,e.toJS=function(e){return function e(t,n){if(typeof t!=`object`||!t||t instanceof Date||!xt(t))return t;if(Pn(t)||Ln(t))return e(t.get(),n);if(n.has(t))return n.get(t);if(Bt(t)){var r=Tt(n,t,Array(t.length));return t.forEach((function(t,i){r[i]=e(t,n)})),r}if(V(t)){var i=Tt(n,t,new Set);return t.forEach((function(t){i.add(e(t,n))})),i}if(hr(t)){var a=Tt(n,t,new Map);return t.forEach((function(t,r){a.set(r,e(t,n))})),a}var o=Tt(n,t,{});return wt(t).forEach((function(r){cn.propertyIsEnumerable.call(t,r)&&(o[r]=e(t[r],n))})),o}(e,new Map)},e.trace=function(){},e.transaction=Et,e.untracked=We,e.values=function(e){return Gt(e)?St(e).map((function(t){return e[t]})):hr(e)?St(e).map((function(t){return e.get(t)})):V(e)?Array.from(e.values()):Bt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ot(e,t):Dt(e,t,n||{})}})),Fx=ve((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1:function(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.`,17:function(e,t){return`[mobx.array] Index out of bounds, `+e+` is larger than `+t},18:`mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js`,19:function(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20:function(e){return`Cannot initialize map from `+e},21:function(e){return`Cannot convert to map from '`+e+`'`},22:`mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js`,23:`It is not possible to get index atoms from arrays`,24:function(e){return`Cannot obtain administration from `+e},25:function(e,t){return`the entry '`+e+`' does not exist in the observable map '`+t+`'`},26:`please specify a property`,27:function(e,t){return`no observable property '`+e.toString()+`' found on the observable object '`+t+`'`},28:function(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:function(e,t){return`Cycle detected in computation `+e+`: `+t},33:function(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:function(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:function(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`};function n(e){var n=[...arguments].slice(1),r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] `+r)}var r={};function i(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:r}var a=Object.assign,o=Object.getOwnPropertyDescriptor,s=Object.defineProperty,c=Object.prototype,l=[];Object.freeze(l);var u={};Object.freeze(u);var d=typeof Proxy<`u`,f=Object.toString();function p(){d||n("`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`")}function m(e){I.verifyProxies&&n(`MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to `+e)}function h(){return++I.mobxGuid}function g(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var _=function(){};function v(e){return typeof e==`function`}function y(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===f}function S(e){var t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function C(e,t,n){s(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function ee(e,t,n){s(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function w(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return b(e)&&e[n]===!0}}function te(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function ne(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function re(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}var ie=Object.getOwnPropertySymbols!==void 0;function T(e){var t=Object.keys(e);if(!ie)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter(function(t){return c.propertyIsEnumerable.call(e,t)})):t}var E=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:ie?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function ae(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function oe(e){return e===null?null:typeof e==`object`?``+e:e}function se(e,t){return c.hasOwnProperty.call(e,t)}var ce=Object.getOwnPropertyDescriptors||function(e){var t={};return E(e).forEach(function(n){t[n]=o(e,n)}),t};function le(e,t){return!!(e&t)}function ue(e,t,n){return n?e|=t:e&=~t,e}function de(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function fe(e,t,n){if(be())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&D(i,n.prototype),i}function pe(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,Se(r.key),r)}}function me(e,t,n){return t&&pe(e.prototype,t),n&&pe(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function he(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=Ce(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
58
+ '`+s.i+`' can only be used on properties with a function value.`)}function me(e,t,n,r,i){var a,o,s;i===void 0&&(i=z.safeDescriptors);var c=r.value;return(a=t.u)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:Ne(t.u?.name??n.toString(),c,(o=t.u?.autoAction)!=null&&o,(s=t.u)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function he(e,t){return{i:e,u:t,o:ge,s:_e,t:ve}}function ge(e,t,n,r){var i;return r===e.h?this.s(e,t,n,!1)===null?0:2:(i=this.u)!=null&&i.bound&&(!g(e.h,t)||!vt(e.h[t]))&&this.s(e,t,n,!1)===null?0:vt(n.value)?1:(sn(r,t,ye(e,0,0,n,!1,!1)),2)}function _e(e,t,n,r){var i=ye(e,0,0,n,this.u?.bound);return e.l(t,i,r)}function ve(e,t){var n,r=t.name,i=t.addInitializer;return vt(e)||(e=nr(e)),(n=this.u)!=null&&n.bound&&i((function(){var e=this[r].bind(this);e.isMobXFlow=!0,this[r]=e})),e}function ye(e,t,n,r,i,a){a===void 0&&(a=z.safeDescriptors);var o=r.value;return vt(o)||(o=nr(o)),i&&((o=o.bind(e.v??e.h)).isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function be(e,t){return{i:e,u:t,o:D,s:xe,t:Se}}function D(e,t,n){return this.s(e,t,n,!1)===null?0:1}function xe(e,t,n,r){return e.m(t,ee({},this.u,{get:n.get,set:n.set}),r)}function Se(e,t){var n=this,r=t.name;return(0,t.addInitializer)((function(){var t=Ut(this)[N],i=ee({},n.u,{get:e,context:this});i.name||=`ObservableObject.`+r.toString(),t.j.set(r,new Fn(i))})),function(){return this[N].O(r)}}function Ce(e,t){return{i:e,u:t,o:we,s:Te,t:Ee}}function we(e,t,n){return this.s(e,t,n,!1)===null?0:1}function Te(e,t,n,r){return e.g(t,n.value,this.u?.enhancer??ce,r)}function Ee(e,t){function n(e,t){var n=Ut(e)[N],i=new Nn(t,r.u?.enhancer??ce,`ObservableObject.`+a.toString(),!1);n.j.set(a,i),o.add(e)}var r=this,i=t.kind,a=t.name,o=new WeakSet;if(i==`accessor`)return{get:function(){return o.has(this)||n(this,e.get.call(this)),this[N].O(a)},set:function(e){return o.has(this)||n(this,e),this[N].S(a,e)},init:function(e){return o.has(this)||n(this,e),e}}}function De(e){return{i:`true`,u:e,o:Oe,s:ke,t:Ae}}function Oe(e,t,n,r){var i,a,o;if(n.get)return kn.o(e,t,n,r);if(n.set){var s=ct(n.set)?n.set:Ne(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!z.safeDescriptors||e.p,set:s})===null?0:2:(sn(r,t,{configurable:!0,set:s}),2)}if(r!==e.h&&typeof n.value==`function`)return l(n.value)?((o=this.u)!=null&&o.autoBind?nr.bound:nr).o(e,t,n,r):((a=this.u)!=null&&a.autoBind?Xn.bound:Xn).o(e,t,n,r);var c=!1===this.u?.deep?En.ref:En;return typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function ke(e,t,n,r){var i;return n.get?kn.s(e,t,n,r):n.set?e.l(t,{configurable:!z.safeDescriptors||e.p,set:Ne(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.u?.deep?En.ref:En).s(e,t,n,r))}function Ae(){t(`'`+this.i+`' cannot be used as a decorator`)}function je(e){return e||bn}function O(e){return!0===e.deep?ce:!1===e.deep?le:(t=e.defaultDecorator)&&(n=(r=t.u)?.enhancer)!=null?n:ce;var t,n,r}function Me(e,t,n){return oe(t)?xn.t(e,t):o(t)?void ae(e,t,xn):xt(e)?e:c(e)?En.object(e,t,n):Array.isArray(e)?En.array(e,t):p(e)?En.map(e,t):m(e)?En.set(e,t):typeof e==`object`&&e?e:En.box(e,t)}function Ne(e,t,n,r){function i(){return Pe(0,n,t,r||this,arguments)}return n===void 0&&(n=!1),i.isMobxAction=!0,i.toString=function(){return t.toString()},jn&&(Mn.value=e,sn(i,`name`,Mn)),i}function Pe(e,t,n,r,i){var a=Fe(0,t);try{return n.apply(r,i)}catch(e){throw a._=e,e}finally{Ie(a)}}function Fe(e,t){var n=z.trackingDerivation,r=!t||!n;$e();var i=z.allowStateChanges;r&&(Ge(),i=Re(!0));var a={A:r,k:n,M:i,V:qe(!0),R:!1,N:0,T:L++,C:An};return An=a.T,a}function Ie(e){An!==e.T&&t(30),An=e.C,e._!==void 0&&(z.suppressReactionErrors=!0),ze(e.M),Je(e.V),et(),e.A&&Ke(e.k),z.suppressReactionErrors=!1}function Le(e,t){var n=Re(e);try{return t()}finally{ze(n)}}function Re(e){var t=z.allowStateChanges;return z.allowStateChanges=e,t}function ze(e){z.allowStateChanges=e}function Be(e){return e instanceof Rn}function Ve(e){switch(e.I){case R.L:return!1;case R.P:case R.K:return!0;case R.B:for(var t=qe(!0),n=Ge(),r=e.D,i=r.length,a=0;a<i;a++){var o=r[a];if(Ln(o)){if(z.disableErrorBoundaries)o.get();else try{o.get()}catch{return Ke(n),Je(t),!0}if(e.I===R.K)return Ke(n),Je(t),!0}}return Ye(e),Ke(n),Je(t),!1}}function He(e,t,n){var r=qe(!0);Ye(e),e.W=Array(e.q===0?100:e.D.length),e.G=0,e.q=++z.runId;var i,a=z.trackingDerivation;if(z.trackingDerivation=e,z.inBatch++,!0===z.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Rn(e)}return z.inBatch--,z.trackingDerivation=a,function(e){for(var t=e.D,n=e.D=e.W,r=R.L,i=0,a=e.G,o=0;o<a;o++){var s=n[o];s.diffValue===0&&(s.diffValue=1,i!==o&&(n[i]=s),i++),s.I>r&&(r=s.I)}for(n.length=i,e.W=null,a=t.length;a--;){var c=t[a];c.diffValue===0&&Ze(c,e),c.diffValue=0}for(;i--;){var l=n[i];l.diffValue===1&&(l.diffValue=0,Xe(l,e))}r!==R.L&&(e.I=r,e.H())}(e),Je(r),i}function Ue(e){var t=e.D;e.D=[];for(var n=t.length;n--;)Ze(t[n],e);e.I=R.P}function We(e){var t=Ge();try{return e()}finally{Ke(t)}}function Ge(){var e=z.trackingDerivation;return z.trackingDerivation=null,e}function Ke(e){z.trackingDerivation=e}function qe(e){var t=z.allowStateReads;return z.allowStateReads=e,t}function Je(e){z.allowStateReads=e}function Ye(e){if(e.I!==R.L){e.I=R.L;for(var t=e.D,n=t.length;n--;)t[n].U=R.L}}function Xe(e,t){e.F.add(t),e.U>t.I&&(e.U=t.I)}function Ze(e,t){e.F.delete(t),e.F.size===0&&Qe(e)}function Qe(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,z.pendingUnobservations.push(e))}function $e(){z.inBatch++}function et(){if(--z.inBatch==0){rt();for(var e=z.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,n.F.size===0&&(n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof Fn&&n.X())}z.pendingUnobservations=[]}}function tt(e){var t=z.trackingDerivation;return t===null?(e.F.size===0&&z.inBatch>0&&Qe(e),!1):(t.q!==e.$&&(e.$=t.q,t.W[t.G++]=e,!e.isBeingObserved&&z.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function nt(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(e){e.I===R.L&&e.H(),e.I=R.K})))}function rt(){z.inBatch>0||z.isRunningReactions||B(it)}function it(){z.isRunningReactions=!0;for(var e=z.pendingReactions,t=0;e.length>0;){++t==100&&(console.error(`[mobx] cycle in reaction: `+e[0]),e.splice(0));for(var n=e.splice(0),r=0,i=n.length;r<i;r++)n[r].J()}z.isRunningReactions=!1}function at(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}}function ot(e){return function(t,n){return a(t)?Ne(t.name||`<unnamed action>`,t,e):a(n)?Ne(t,n,e):oe(n)?(e?qn:Gn).t(t,n):o(n)?ae(t,n,e?qn:Gn):o(t)?E(ue(e?`autoAction`:`action`,{name:t,autoAction:e})):void 0}}function st(e){return Pe(0,!1,e,this,void 0)}function ct(e){return a(e)&&!0===e.isMobxAction}function lt(e,t){function n(){e(i)}var r;t===void 0&&(t=un);var i,a=t?.name??`Autorun`;if(t.scheduler||t.delay){var o=ut(t),s=!1;i=new Un(a,(function(){s||(s=!0,o((function(){s=!1,i.isDisposed||i.track(n)})))}),t.onError,t.requiresObservable)}else i=new Un(a,(function(){this.track(n)}),t.onError,t.requiresObservable);return(r=t)!=null&&(r=r.signal)!=null&&r.aborted||i.Y(),i.Z(t?.signal)}function ut(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:Zn}function dt(e,t,n){return pt(`onBO`,e,t,n)}function ft(e,t,n){return pt(`onBUO`,e,t,n)}function pt(e,t,n,r){var i=typeof r==`function`?Xt(t,n):Xt(t),o=a(r)?r:n,s=e+`L`;return i[s]?i[s].add(o):i[s]=new Set([o]),function(){var e=i[s];e&&(e.delete(o),e.size===0&&delete i[s])}}function mt(e,t,n,r){var i=M(t);return $t((function(){var t=Ut(e,r)[N];hn(i).forEach((function(e){t.s(e,i[e],!n||!(e in n)||n[e])}))})),e}function ht(e){var t,n={name:e.tt};return e.D&&e.D.length>0&&(n.dependencies=(t=e.D,Array.from(new Set(t))).map(ht)),n}function gt(e){var t={name:e.tt};return function(e){return e.F&&e.F.size>0}(e)&&(t.observers=Array.from(function(e){return e.F}(e)).map(gt)),t}function _t(e){a(e.cancel)&&e.cancel()}function vt(e){return!0===e?.isMobXFlow}function yt(e,t){return t===void 0?Ln(e):!1===Gt(e)||!e[N].j.has(t)?!1:Ln(Xt(e,t))}function bt(e,t){return!!e&&(t===void 0?Gt(e)||!!e[N]||_n(e)||Wn(e)||Ln(e):!!Gt(e)&&e[N].j.has(t))}function xt(e){return bt(e)}function St(e){return Gt(e)?e[N].nt():hr(e)||V(e)?Array.from(e.keys()):Bt(e)?e.map((function(e,t){return t})):void t(5)}function Ct(e,n){return Gt(e)?e[N].it(n):hr(e)||V(e)?e.has(n):Bt(e)?n>=0&&n<e.length:void t(10)}function wt(e){if(Gt(e))return e[N].rt();t(38)}function Tt(e,t,n){return e.set(t,n),n}function Et(e,t){t===void 0&&(t=void 0),$e();try{return e.apply(t)}finally{et()}}function Dt(e,t,n){var r;if(typeof n.timeout==`number`){var i=Error(`WHEN_TIMEOUT`);r=setTimeout((function(){if(!o[N].isDisposed){if(o(),!n.onError)throw i;n.onError(i)}}),n.timeout)}n.name=`When`;var a=Ne(`When-effect`,t),o=lt((function(t){Le(!1,e)&&(t.dispose(),r&&clearTimeout(r),a())}),n);return o}function Ot(e,t){var n,r,i;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Object.assign(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:function(){return null}});var a=new Promise((function(n,a){var o,s=Dt(e,n,ee({},t,{onError:a}));r=function(){s(),a(Error(`WHEN_CANCELLED`))},i=function(){s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)})).finally((function(){var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)}));return a.cancel=r,a}function kt(e){return e[N]}function At(e){return e.et!==void 0&&e.et.length>0}function jt(e,t){var n=e.et||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Mt(e,n){var r=Ge();try{for(var i=[].concat(e.et||[]),a=0,o=i.length;a<o&&((n=i[a](n))&&!n.type&&t(14),n);a++);return n}finally{Ke(r)}}function Nt(e){return e.ut!==void 0&&e.ut.length>0}function Pt(e,t){var n=e.ut||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Ft(e,t){var n=Ge(),r=e.ut;if(r){for(var i=0,a=(r=r.slice()).length;i<a;i++)r[i](t);Ke(n)}}function It(e,t,n,i){return n===void 0&&(n=`ObservableArray`),i===void 0&&(i=!1),r(),$t((function(){var r=new sr(n,t,i,!1);d(r.j,N,r);var a=new Proxy(r.j,or);return r.v=a,e&&e.length&&r.ot(0,0,e),a}))}function Lt(e,t){typeof Array.prototype[e]==`function`&&(cr[e]=t(e))}function Rt(e){return function(){var t=this[N];t.st.reportObserved();var n=t.ft(t.j);return n[e].apply(n,arguments)}}function k(e){return function(t,n){var r=this,i=this[N];return i.st.reportObserved(),i.ft(i.j)[e]((function(e,i){return t.call(n,e,i,r)}))}}function zt(e){return function(){var t=this,n=this[N];n.st.reportObserved();var r=n.ft(n.j),i=arguments[0];return arguments[0]=function(e,n,r){return i(e,n,r,t)},r[e].apply(r,arguments)}}function Bt(e){return s(e)&&dr(e[N])}function Vt(e){return e[Symbol.toStringTag]=`MapIterator`,nn(e)}function Ht(e){return e[Symbol.toStringTag]=`SetIterator`,nn(e)}function Ut(e,t){if(g(e,N))return e;var n=t?.name??`ObservableObject`;return u(e,N,new yr(e,new Map,String(n),function(e){return e?e.defaultDecorator??De(e):void 0}(t))),e}function Wt(e){return vr[e]||(vr[e]={get:function(){return this[N].O(e)},set:function(t){return this[N].S(e,t)}})}function Gt(e){return!!s(e)&&br(e[N])}function A(e,t,n){var r;(r=e.h[gn])==null||delete r[n]}function Kt(e){return{enumerable:!1,configurable:!0,get:function(){return this[N].ct(e)},set:function(t){this[N].ht(e,t)}}}function qt(e){sn(Tr.prototype,``+e,Kt(e))}function Jt(e){if(e>Cr){for(var t=Cr;t<e+100;t++)qt(t);Cr=e}}function Yt(e,t,n){return new Tr(e,t,n)}function Xt(e,n){if(typeof e==`object`&&e){if(Bt(e))return n!==void 0&&t(23),e[N].st;if(V(e))return e.st;if(hr(e)){if(n===void 0)return e.lt;var r=e.vt.get(n)||e.dt.get(n);return r||t(25,n,Qt(e)),r}if(Gt(e)){if(!n)return t(26);var i=e[N].j.get(n);return i||t(27,n,Qt(e)),i}if(_n(e)||Ln(e)||Wn(e))return e}else if(a(e)&&Wn(e[N]))return e[N];t(28)}function Zt(e,n){return e||t(29),n===void 0?_n(e)||Ln(e)||Wn(e)||hr(e)||V(e)?e:e[N]?e[N]:void t(24,e):Zt(Xt(e,n))}function Qt(e,t){var n;if(t!==void 0)n=Xt(e,t);else{if(ct(e))return e.name;n=Gt(e)||hr(e)||V(e)?Zt(e):Xt(e)}return n.tt}function $t(e){var t=Ge(),n=Re(!0);$e();try{return e()}finally{et(),ze(n),Ke(t)}}function en(e,t,n){return n===void 0&&(n=-1),function e(t,n,r,i,o){if(t===n)return t!==0||1/t==1/n;if(t==null||n==null)return!1;if(t!=t)return n!=n;var s=typeof t;if(s!==`function`&&s!==`object`&&typeof n!=`object`)return!1;var c=Er.call(t);if(c!==Er.call(n))return!1;switch(c){case`[object RegExp]`:case`[object String]`:return``+t==``+n;case`[object Number]`:return+t==+t?+t==0?1/t==1/n:+t==+n:+n!=+n;case`[object Date]`:case`[object Boolean]`:return+t==+n;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(t)===Symbol.valueOf.call(n);case`[object Map]`:case`[object Set]`:r>=0&&r++}t=tn(t),n=tn(n);var l=c===`[object Array]`;if(!l){if(typeof t!=`object`||typeof n!=`object`)return!1;var u=t.constructor,d=n.constructor;if(u!==d&&!(a(u)&&u instanceof u&&a(d)&&d instanceof d)&&`constructor`in t&&`constructor`in n)return!1}if(r===0)return!1;r<0&&(r=-1),o||=[];for(var f=(i||=[]).length;f--;)if(i[f]===t)return o[f]===n;if(i.push(t),o.push(n),l){if((f=t.length)!==n.length)return!1;for(;f--;)if(!e(t[f],n[f],r-1,i,o))return!1}else{var p=Object.keys(t),m=p.length;if(Object.keys(n).length!==m)return!1;for(var h=0;h<m;h++){var _=p[h];if(!g(n,_)||!e(t[_],n[_],r-1,i,o))return!1}}return i.pop(),o.pop(),!0}(e,t,n)}function tn(e){return Bt(e)?e.slice():p(e)||hr(e)||m(e)||V(e)?Array.from(e.entries()):e}function nn(e){return e[Symbol.iterator]=rn,Object.assign(Object.create(Dr),e)}function rn(){return this}Object.defineProperty(e,`__esModule`,{value:!0});var an={},j=Object.assign,on=Object.getOwnPropertyDescriptor,sn=Object.defineProperty,cn=Object.prototype,ln=[];Object.freeze(ln);var un={};Object.freeze(un);var dn=typeof Proxy<`u`,fn=Object.toString(),pn=function(){},mn=Object.getOwnPropertySymbols!==void 0,hn=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:mn?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,M=Object.getOwnPropertyDescriptors||function(e){var t={};return hn(e).forEach((function(n){t[n]=on(e,n)})),t},gn=Symbol(`mobx-stored-annotations`),N=Symbol(`mobx administration`),P=function(){function e(e){e===void 0&&(e=`Atom`),this.tt=void 0,this.bt=0,this.F=new Set,this.$=0,this.U=R.P,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return tt(this)},t.reportChanged=function(){$e(),nt(this),et()},t.toString=function(){return this.tt},S(e,[{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();P.pt=1,P.yt=2,P.wt=4;var _n=f(`Atom`,P),vn={identity:function(e,t){return e===t},structural:function(e,t){return en(e,t)},default:function(e,t){return Object.is?Object.is(e,t):e===t?e!==0||1/e==1/t:e!=e&&t!=t},shallow:function(e,t){return en(e,t,1)}},yn=E({i:`override`,o:function(){return 0},s:function(){t(`'`+this.i+`' can only be used with 'makeObservable'`)},t:function(){console.warn(`'`+this.i+`' cannot be used with decorators - this is a no-op`)}}),F=De(),bn={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};Object.freeze(bn);var xn=Ce(`observable`),Sn=Ce(`observable.ref`,{enhancer:le}),I=Ce(`observable.shallow`,{enhancer:function(e,t,n){return e==null||Gt(e)||Bt(e)||hr(e)||V(e)?e:Array.isArray(e)?En.array(e,{name:n,deep:!1}):c(e)?En.object(e,void 0,{name:n,deep:!1}):p(e)?En.map(e,{name:n,deep:!1}):m(e)?En.set(e,{name:n,deep:!1}):void 0}}),Cn=Ce(`observable.struct`,{enhancer:function(e,t){return en(e,t)?t:e}}),wn=E(xn);j(Me,wn);var Tn,En=j(Me,{box:function(e,t){var n=je(t);return new Nn(e,O(n),n.name,!0,n.equals)},array:function(e,t){var n=je(t);return(!1===z.useProxies||!1===n.proxy?Yt:It)(e,O(n),n.name)},map:function(e,t){var n=je(t);return new mr(e,O(n),n.name)},set:function(e,t){var n=je(t);return new _r(e,O(n),n.name)},object:function(e,t,n){return $t((function(){return mt(!1===z.useProxies||!1===n?.proxy?Ut({},n):function(e,t){var n;return r(),(n=(e=Ut(e,t))[N]).v??(n.v=new Proxy(e,rr))}({},n),e,t)}))},ref:E(Sn),shallow:E(I),deep:wn,struct:E(Cn)}),Dn=be(`computed`),On=be(`computed.struct`,{equals:vn.structural}),kn=function(e,t){if(oe(t))return Dn.t(e,t);if(o(t))return ae(e,t,Dn);if(c(e))return E(be(`computed`,e));var n=c(t)?t:{};return n.get=e,n.name||=e.name||``,new Fn(n)};Object.assign(kn,Dn),kn.struct=E(On);var An=0,L=1,jn=(Tn=on((function(){}),`name`)?.configurable)!=null&&Tn,Mn={value:`action`,configurable:!0,writable:!1,enumerable:!1},Nn=function(e){function t(t,n,r,i,a){var o;return r===void 0&&(r=`ObservableValue`),a===void 0&&(a=vn.default),(o=e.call(this,r)||this).enhancer=void 0,o.tt=void 0,o.equals=void 0,o.jt=!1,o.et=void 0,o.ut=void 0,o.Ot=void 0,o.dehancer=void 0,o.enhancer=n,o.tt=r,o.equals=a,o.Ot=n(t,void 0,r),o}te(t,e);var n=t.prototype;return n.dehanceValue=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.set=function(e){(e=this.xt(e))!==z.UNCHANGED&&this.gt(e)},n.xt=function(e){if(At(this)){var t=Mt(this,{object:this,type:ar,newValue:e});if(!t)return z.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.Ot,this.tt),this.equals(this.Ot,e)?z.UNCHANGED:e},n.gt=function(e){var t=this.Ot;this.Ot=e,this.reportChanged(),Nt(this)&&Ft(this,{type:ar,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.Ot)},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t&&e({observableKind:`value`,debugObjectName:this.tt,object:this,type:ar,newValue:this.Ot,oldValue:void 0}),Pt(this,e)},n.raw=function(){return this.Ot},n.toJSON=function(){return this.get()},n.toString=function(){return this.tt+`[`+this.Ot+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},t}(P),Pn=f(`ObservableValue`,Nn),Fn=function(){function e(e){this.I=R.P,this.D=[],this.W=null,this.F=new Set,this.q=0,this.$=0,this.U=R.L,this.G=0,this.Ot=new Rn(null),this.tt=void 0,this.At=void 0,this.bt=0,this.derivation=void 0,this.kt=void 0,this.Mt=In.NONE,this.Et=void 0,this.Vt=void 0,this.Rt=void 0,this.Nt=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.kt=Ne(`ComputedValue-setter`,e.set)),this.Vt=e.equals||(e.compareStructural||e.struct?vn.structural:vn.default),this.Et=e.context,this.Rt=e.requiresReaction,this.Nt=!!e.keepAlive}var n=e.prototype;return n.H=function(){(function(e){e.U===R.L&&(e.U=R.B,e.F.forEach((function(e){e.I===R.L&&(e.I=R.B,e.H())})))})(this)},n.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},n.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},n.get=function(){if(this.isComputing&&t(32,this.tt,this.derivation),z.inBatch!==0||this.F.size!==0||this.Nt){if(tt(this),Ve(this)){var e=z.trackingContext;this.Nt&&!e&&(z.trackingContext=this),this.trackAndCompute()&&function(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(t){t.I===R.B?t.I=R.K:t.I===R.L&&(e.U=R.L)})))}(this),z.trackingContext=e}}else Ve(this)&&(this.Tt(),$e(),this.Ot=this.Ct(!1),et());var n=this.Ot;if(Be(n))throw n.cause;return n},n.set=function(e){if(this.kt){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.kt.call(this.Et,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)},n.trackAndCompute=function(){var e=this.Ot,t=this.I===R.P,n=this.Ct(!0),r=t||Be(e)||Be(n)||!this.Vt(e,n);return r&&(this.Ot=n),r},n.Ct=function(e){this.isComputing=!0;var t,n=Re(!1);if(e)t=He(this,this.derivation,this.Et);else if(!0===z.disableErrorBoundaries)t=this.derivation.call(this.Et);else try{t=this.derivation.call(this.Et)}catch(e){t=new Rn(e)}return ze(n),this.isComputing=!1,t},n.X=function(){this.Nt||(Ue(this),this.Ot=void 0)},n._t=function(e,t){var n=this,r=!0,i=void 0;return lt((function(){var a=n.get();if(!r||t){var o=Ge();e({observableKind:`computed`,debugObjectName:n.tt,type:ar,object:n,newValue:a,oldValue:i}),Ke(o)}r=!1,i=a}))},n.Tt=function(){},n.toString=function(){return this.tt+`[`+this.derivation.toString()+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},S(e,[{key:`isComputing`,get:function(){return _(this.bt,e.It)},set:function(t){this.bt=v(this.bt,e.It,t)}},{key:`isRunningSetter`,get:function(){return _(this.bt,e.Lt)},set:function(t){this.bt=v(this.bt,e.Lt,t)}},{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Fn.It=1,Fn.Lt=2,Fn.pt=4,Fn.yt=8,Fn.wt=16;var R,In,Ln=f(`ComputedValue`,Fn);(function(e){e[e.P=-1]=`NOT_TRACKING_`,e[e.L=0]=`UP_TO_DATE_`,e[e.B=1]=`POSSIBLY_STALE_`,e[e.K=2]=`STALE_`})(R||={}),function(e){e[e.NONE=0]=`NONE`,e[e.LOG=1]=`LOG`,e[e.BREAK=2]=`BREAK`}(In||={});var Rn=function(e){this.cause=void 0,this.cause=e},zn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`,`useProxies`],Bn=function(){this.version=6,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.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.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Vn=!0,Hn=!1,z=function(){var e=n();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Vn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==new Bn().version&&(Vn=!1),Vn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Bn):(setTimeout((function(){Hn||t(35)}),1),new Bn)}(),Un=function(){function e(e,t,n,r){e===void 0&&(e=`Reaction`),this.tt=void 0,this.Pt=void 0,this.Kt=void 0,this.Bt=void 0,this.D=[],this.W=[],this.I=R.P,this.q=0,this.G=0,this.bt=0,this.Mt=In.NONE,this.tt=e,this.Pt=t,this.Kt=n,this.Bt=r}var t=e.prototype;return t.H=function(){this.Y()},t.Y=function(){this.isScheduled||(this.isScheduled=!0,z.pendingReactions.push(this),rt())},t.J=function(){if(!this.isDisposed){$e(),this.isScheduled=!1;var e=z.trackingContext;if(z.trackingContext=this,Ve(this)){this.isTrackPending=!0;try{this.Pt()}catch(e){this.Dt(e)}}z.trackingContext=e,et()}},t.track=function(e){if(!this.isDisposed){$e(),this.isRunning=!0;var t=z.trackingContext;z.trackingContext=this;var n=He(this,e,void 0);z.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ue(this),Be(n)&&this.Dt(n.cause),et()}},t.Dt=function(e){var t=this;if(this.Kt)this.Kt(e,this);else{if(z.disableErrorBoundaries)throw e;z.suppressReactionErrors||console.error(`[mobx] uncaught error in '`+this+`'`,e),z.globalReactionErrorHandlers.forEach((function(n){return n(e,t)}))}},t.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.isRunning||($e(),Ue(this),et()))},t.Z=function(e){var t=this,n=function n(){t.dispose(),e==null||e.removeEventListener==null||e.removeEventListener(`abort`,n)};return e==null||e.addEventListener==null||e.addEventListener(`abort`,n),n[N]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(n[Symbol.dispose]=n),n},t.toString=function(){return`Reaction[`+this.tt+`]`},t.trace=function(){},S(e,[{key:`isDisposed`,get:function(){return _(this.bt,e.Wt)},set:function(t){this.bt=v(this.bt,e.Wt,t)}},{key:`isScheduled`,get:function(){return _(this.bt,e.qt)},set:function(t){this.bt=v(this.bt,e.qt,t)}},{key:`isTrackPending`,get:function(){return _(this.bt,e.Gt)},set:function(t){this.bt=v(this.bt,e.Gt,t)}},{key:`isRunning`,get:function(){return _(this.bt,e.Ht)},set:function(t){this.bt=v(this.bt,e.Ht,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Un.Wt=1,Un.qt=2,Un.Gt=4,Un.Ht=8,Un.wt=16;var B=function(e){return e()},Wn=f(`Reaction`,Un),Gn=ue(`action`),Kn=ue(`action.bound`,{bound:!0}),qn=ue(`autoAction`,{autoAction:!0}),Jn=ue(`autoAction.bound`,{autoAction:!0,bound:!0}),Yn=ot(!1);Object.assign(Yn,Gn);var Xn=ot(!0);Object.assign(Xn,qn),Yn.bound=E(Kn),Xn.bound=E(Jn);var Zn=function(e){return e()},Qn=0,$n=function(e){function t(){var n;return n=e.call(this,`FLOW_CANCELLED`)||this,Object.setPrototypeOf(n,(this instanceof t?this.constructor:void 0).prototype),n.name=`FlowCancellationError`,n}return te(t,e),t.prototype.toString=function(){return`Error: `+this.message},t}(T(Error)),er=he(`flow`),tr=he(`flow.bound`,{bound:!0}),nr=Object.assign((function(e,t){if(oe(t))return er.t(e,t);if(o(t))return ae(e,t,er);var n=e,r=n.name||`<unnamed flow>`,i=function(){var e,t=this,i=arguments,o=++Qn,s=Yn(r+` - runid: `+o+` - init`,n).apply(t,i),c=void 0,l=new Promise((function(t,n){function i(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.next).call(s,e)}catch(e){return n(e)}u(t)}function l(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.throw).call(s,e)}catch(e){return n(e)}u(t)}function u(e){if(!a(e?.then))return e.done?t(e.value):(c=Promise.resolve(e.value)).then(i,l);e.then(u,n)}var d=0;e=n,i(void 0)}));return l.cancel=Yn(r+` - runid: `+o+` - cancel`,(function(){try{c&&_t(c);var t=s.return(void 0),n=Promise.resolve(t.value);n.then(pn,pn),_t(n),e(new $n)}catch(t){e(t)}})),l};return i.isMobXFlow=!0,i}),er);nr.bound=E(tr);var rr={has:function(e,t){return kt(e).it(t)},get:function(e,t){return kt(e).ct(t)},set:function(e,t,n){var r;return!!o(t)&&((r=kt(e).ht(t,n,!0))==null||r)},deleteProperty:function(e,t){var n;return!!o(t)&&((n=kt(e).Ut(t,!0))==null||n)},defineProperty:function(e,t,n){var r;return(r=kt(e).l(t,n))==null||r},ownKeys:function(e){return kt(e).rt()},preventExtensions:function(){t(13)}},ir=Symbol(`mobx-keys`),ar=`update`,or={get:function(e,t){var n=e[N];return t===N?n:t===`length`?n.Ft():typeof t!=`string`||isNaN(t)?g(cr,t)?cr[t]:e[t]:n.ct(parseInt(t))},set:function(e,t,n){var r=e[N];return t===`length`&&r.Xt(n),typeof t==`symbol`||isNaN(t)?e[t]=n:r.ht(parseInt(t),n),!0},preventExtensions:function(){t(15)}},sr=function(){function e(e,t,n,r){e===void 0&&(e=`ObservableArray`),this.zt=void 0,this.$t=void 0,this.st=void 0,this.j=[],this.et=void 0,this.ut=void 0,this.Jt=void 0,this.dehancer=void 0,this.v=void 0,this.Yt=0,this.zt=n,this.$t=r,this.st=new P(e),this.Jt=function(e,n){return t(e,n,`ObservableArray[..]`)}}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.ft=function(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t===void 0&&(t=!1),t&&e({observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:0,added:this.j.slice(),addedCount:this.j.length,removed:[],removedCount:0}),Pt(this,e)},n.Ft=function(){return this.st.reportObserved(),this.j.length},n.Xt=function(e){(typeof e!=`number`||isNaN(e)||e<0)&&t(`Out of range: `+e);var n=this.j.length;if(e!==n)if(e>n){for(var r=Array(e-n),i=0;i<e-n;i++)r[i]=void 0;this.ot(n,0,r)}else this.ot(e,n-e)},n.Zt=function(e,n){e!==this.Yt&&t(16),this.Yt+=n,this.$t&&n>0&&Jt(e+n+1)},n.ot=function(e,t,n){var r=this,i=this.j.length;if(e===void 0?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=arguments.length===1?i-e:t==null?0:Math.max(0,Math.min(t,i-e)),n===void 0&&(n=ln),At(this)){var a=Mt(this,{object:this.v,type:`splice`,index:e,removedCount:t,added:n});if(!a)return ln;t=a.removedCount,n=a.added}if(n=n.length===0?n:n.map((function(e){return r.Jt(e,void 0)})),this.$t){var o=n.length-t;this.Zt(i,o)}var s=this.tn(e,t,n);return t===0&&n.length===0||this.nn(e,n,s),this.ft(s)},n.tn=function(e,t,n){var r;if(n.length<1e4)return(r=this.j).splice.apply(r,[e,t].concat(n));var i=this.j.slice(e,e+t),a=this.j.slice(e+t);this.j.length+=n.length-t;for(var o=0;o<n.length;o++)this.j[e+o]=n[o];for(var s=0;s<a.length;s++)this.j[e+n.length+s]=a[s];return i},n.in=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,type:ar,debugObjectName:this.st.tt,index:e,newValue:t,oldValue:n}:null;this.st.reportChanged(),i&&Ft(this,a)},n.nn=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.st.reportChanged(),i&&Ft(this,a)},n.ct=function(e){if(!(this.$t&&e>=this.j.length))return this.st.reportObserved(),this.Qt(this.j[e]);console.warn(`[mobx] Out of bounds read: `+e)},n.ht=function(e,n){var r=this.j;if(this.$t&&e>r.length&&t(17,e,r.length),e<r.length){var i=r[e];if(At(this)){var a=Mt(this,{type:ar,object:this.v,index:e,newValue:n});if(!a)return;n=a.newValue}(n=this.Jt(n,i))!==i&&(r[e]=n,this.in(e,n,i))}else{for(var o=Array(e+1-r.length),s=0;s<o.length-1;s++)o[s]=void 0;o[o.length-1]=n,this.ot(r.length,0,o)}},e}(),cr={clear:function(){return this.splice(0)},replace:function(e){var t=this[N];return t.ot(0,t.j.length,e)},toJSON:function(){return this.slice()},splice:function(e,t){var n=[...arguments].slice(2),r=this[N];switch(arguments.length){case 0:return[];case 1:return r.ot(e);case 2:return r.ot(e,t)}return r.ot(e,t,n)},spliceWithArray:function(e,t,n){return this[N].ot(e,t,n)},push:function(){for(var e=this[N],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(e.j.length,0,n),e.j.length},pop:function(){return this.splice(Math.max(this[N].j.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=this[N],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(0,0,n),e.j.length},reverse:function(){return z.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort:function(){z.trackingDerivation&&t(37,`sort`);var e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove:function(e){var t=this[N],n=t.ft(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};Lt(`at`,Rt),Lt(`concat`,Rt),Lt(`flat`,Rt),Lt(`includes`,Rt),Lt(`indexOf`,Rt),Lt(`join`,Rt),Lt(`lastIndexOf`,Rt),Lt(`slice`,Rt),Lt(`toString`,Rt),Lt(`toLocaleString`,Rt),Lt(`toSorted`,Rt),Lt(`toSpliced`,Rt),Lt(`with`,Rt),Lt(`every`,k),Lt(`filter`,k),Lt(`find`,k),Lt(`findIndex`,k),Lt(`findLast`,k),Lt(`findLastIndex`,k),Lt(`flatMap`,k),Lt(`forEach`,k),Lt(`map`,k),Lt(`some`,k),Lt(`toReversed`,k),Lt(`reduce`,zt),Lt(`reduceRight`,zt);var lr,ur,dr=f(`ObservableArrayAdministration`,sr),fr={},pr=`add`,mr=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableMap`),this.Jt=void 0,this.tt=void 0,this[N]=fr,this.vt=void 0,this.dt=void 0,this.lt=void 0,this.et=void 0,this.ut=void 0,this.dehancer=void 0,this.Jt=n,this.tt=r,a(Map)||t(18),$t((function(){i.lt=se(`ObservableMap.keys()`),i.vt=new Map,i.dt=new Map,e&&i.merge(e)}))}var n=e.prototype;return n.it=function(e){return this.vt.has(e)},n.has=function(e){var t=this;if(!z.trackingDerivation)return this.it(e);var n=this.dt.get(e);if(!n){var r=n=new Nn(this.it(e),le,`ObservableMap.key?`,!1);this.dt.set(e,r),ft(r,(function(){return t.dt.delete(e)}))}return n.get()},n.set=function(e,t){var n=this.it(e);if(At(this)){var r=Mt(this,{type:n?ar:pr,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.rn(e,t):this.en(e,t),this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,name:e}))return!1;if(this.it(e)){var n=Nt(this),r=n?{observableKind:`map`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:this.vt.get(e).Ot,name:e}:null;return Et((function(){var n;t.lt.reportChanged(),(n=t.dt.get(e))==null||n.gt(!1),t.vt.get(e).gt(void 0),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.rn=function(e,t){var n=this.vt.get(e);if((t=n.xt(t))!==z.UNCHANGED){var r=Nt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:ar,object:this,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),r&&Ft(this,i)}},n.en=function(e,t){var n=this;Et((function(){var r,i=new Nn(t,n.Jt,`ObservableMap.key`,!1);n.vt.set(e,i),t=i.Ot,(r=n.dt.get(e))==null||r.gt(!0),n.lt.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`map`,debugObjectName:this.tt,type:pr,object:this,name:e,newValue:t}:null)},n.get=function(e){return this.has(e)?this.Qt(this.vt.get(e).get()):this.Qt(void 0)},n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.keys=function(){return this.lt.reportObserved(),this.vt.keys()},n.values=function(){var e=this,t=this.keys();return Vt({next:function(){var n=t.next(),r=n.done;return{done:r,value:r?void 0:e.get(n.value)}}})},n.entries=function(){var e=this,t=this.keys();return Vt({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:[i,e.get(i)]}}})},n[Symbol.iterator]=function(){return this.entries()},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i[1],i[0],this)}},n.merge=function(e){var n=this;return hr(e)&&(e=new Map(e)),Et((function(){var r,i;c(e)?function(e){var t=Object.keys(e);if(!mn)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter((function(t){return cn.propertyIsEnumerable.call(e,t)}))):t}(e).forEach((function(t){return n.set(t,e[t])})):Array.isArray(e)?e.forEach((function(e){return n.set(e[0],e[1])})):p(e)?(r=Object.getPrototypeOf(e),i=Object.getPrototypeOf(r),Object.getPrototypeOf(i)!==null&&t(19,e),e.forEach((function(e,t){return n.set(t,e)}))):e!=null&&t(20,e)})),this},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.keys());!(t=n()).done;)e.delete(t.value)}))}))},n.replace=function(e){var n=this;return Et((function(){for(var r,i=function(e){if(p(e)||hr(e))return e;if(Array.isArray(e))return new Map(e);if(c(e)){var n=new Map;for(var r in e)n.set(r,e[r]);return n}return t(21,e)}(e),a=new Map,o=!1,s=C(n.vt.keys());!(r=s()).done;){var l=r.value;if(!i.has(l))if(n.delete(l))o=!0;else{var u=n.vt.get(l);a.set(l,u)}}for(var d,f=C(i.entries());!(d=f()).done;){var m=d.value,h=m[0],g=m[1],_=n.vt.has(h);if(n.set(h,g),n.vt.has(h)){var v=n.vt.get(h);a.set(h,v),_||(o=!0)}}if(!o)if(n.vt.size!==a.size)n.lt.reportChanged();else for(var y=n.vt.keys(),b=a.keys(),x=y.next(),S=b.next();!x.done;){if(x.value!==S.value){n.lt.reportChanged();break}x=y.next(),S=b.next()}n.vt=a})),this},n.toString=function(){return`[object ObservableMap]`},n.toJSON=function(){return Array.from(this)},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},S(e,[{key:`size`,get:function(){return this.lt.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Map`}}])}(),hr=f(`ObservableMap`,mr),gr={},_r=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableSet`),this.tt=void 0,this[N]=gr,this.vt=new Set,this.st=void 0,this.ut=void 0,this.et=void 0,this.dehancer=void 0,this.Jt=void 0,this.tt=r,a(Set)||t(22),this.Jt=function(e,t){return n(e,t,r)},$t((function(){i.st=se(i.tt),e&&i.replace(e)}))}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.vt.values());!(t=n()).done;)e.delete(t.value)}))}))},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i,i,this)}},n.add=function(e){var t=this;if(At(this)){var n=Mt(this,{type:pr,object:this,newValue:e});if(!n)return this;e=n.newValue}if(!this.has(e)){Et((function(){t.vt.add(t.Jt(e,void 0)),t.st.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`set`,debugObjectName:this.tt,type:pr,object:this,newValue:e}:null)}return this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,oldValue:e}))return!1;if(this.has(e)){var n=Nt(this),r=n?{observableKind:`set`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:e}:null;return Et((function(){t.st.reportChanged(),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.has=function(e){return this.st.reportObserved(),this.vt.has(this.Qt(e))},n.entries=function(){var e=this.values();return Ht({next:function(){var t=e.next(),n=t.value,r=t.done;return r?{value:void 0,done:r}:{value:[n,n],done:r}}})},n.keys=function(){return this.values()},n.values=function(){this.st.reportObserved();var e=this,t=this.vt.values();return Ht({next:function(){var n=t.next(),r=n.done;return r?{value:void 0,done:r}:{value:e.Qt(n.value),done:r}}})},n.intersection=function(e){return m(e)&&!V(e)?e.intersection(this):new Set(this).intersection(e)},n.union=function(e){return m(e)&&!V(e)?e.union(this):new Set(this).union(e)},n.difference=function(e){return new Set(this).difference(e)},n.symmetricDifference=function(e){return m(e)&&!V(e)?e.symmetricDifference(this):new Set(this).symmetricDifference(e)},n.isSubsetOf=function(e){return new Set(this).isSubsetOf(e)},n.isSupersetOf=function(e){return new Set(this).isSupersetOf(e)},n.isDisjointFrom=function(e){return m(e)&&!V(e)?e.isDisjointFrom(this):new Set(this).isDisjointFrom(e)},n.replace=function(e){var n=this;return V(e)&&(e=new Set(e)),Et((function(){Array.isArray(e)||m(e)?(n.clear(),e.forEach((function(e){return n.add(e)}))):e!=null&&t(`Cannot initialize set from `+e)})),this},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.toJSON=function(){return Array.from(this)},n.toString=function(){return`[object ObservableSet]`},n[Symbol.iterator]=function(){return this.values()},S(e,[{key:`size`,get:function(){return this.st.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Set`}}])}(),V=f(`ObservableSet`,_r),vr=Object.create(null),yr=function(){function e(e,t,n,r){t===void 0&&(t=new Map),r===void 0&&(r=F),this.h=void 0,this.j=void 0,this.tt=void 0,this.un=void 0,this.lt=void 0,this.ut=void 0,this.et=void 0,this.v=void 0,this.p=void 0,this.on=void 0,this.sn=void 0,this.h=e,this.j=t,this.tt=n,this.un=r,this.lt=new P(`ObservableObject.keys`),this.p=c(this.h)}var n=e.prototype;return n.O=function(e){return this.j.get(e).get()},n.S=function(e,t){var n=this.j.get(e);if(n instanceof Fn)return n.set(t),!0;if(At(this)){var r=Mt(this,{type:ar,object:this.v||this.h,name:e,newValue:t});if(!r)return null;t=r.newValue}if((t=n.xt(t))!==z.UNCHANGED){var i=Nt(this),a=i?{type:ar,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),i&&Ft(this,a)}return!0},n.ct=function(e){return z.trackingDerivation&&!g(this.h,e)&&this.it(e),this.h[e]},n.ht=function(e,t,n){return n===void 0&&(n=!1),g(this.h,e)?this.j.has(e)?this.S(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.s(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.un,n)},n.it=function(e){if(!z.trackingDerivation)return e in this.h;this.sn||=new Map;var t=this.sn.get(e);return t||(t=new Nn(e in this.h,le,`ObservableObject.key?`,!1),this.sn.set(e,t)),t.get()},n.o=function(e,n){if(!0===n&&(n=this.un),!1!==n){if(!(e in this.h)){var r;if((r=this.h[gn])!=null&&r[e])return;t(1,n.i,this.tt+`.`+e.toString())}for(var i=this.h;i&&i!==cn;){var a=on(i,e);if(a){var o=n.o(this,e,a,i);if(o===0)return;if(o===1)break}i=Object.getPrototypeOf(i)}A(this,0,e)}},n.s=function(e,t,n,r){if(r===void 0&&(r=!1),!0===n&&(n=this.un),!1===n)return this.l(e,t,r);var i=n.s(this,e,t,r);return i&&A(this,0,e),i},n.l=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)){var i=Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:t.value});if(!i)return null;var a=i.newValue;t.value!==a&&(t=ee({},t,{value:a}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else sn(this.h,e,t);this.fn(e,t.value)}finally{et()}return!0},n.g=function(e,t,n,r){r===void 0&&(r=!1);try{$e();var i=this.Ut(e);if(!i)return i;if(At(this)){var a=Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:t});if(!a)return null;t=a.newValue}var o=Wt(e),s={configurable:!z.safeDescriptors||this.p,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.h,e,s))return!1}else sn(this.h,e,s);var c=new Nn(t,n,`ObservableObject.key`,!1);this.j.set(e,c),this.fn(e,c.Ot)}finally{et()}return!0},n.m=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:pr,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;var i=Wt(e),a={configurable:!z.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else sn(this.h,e,a);this.j.set(e,new Fn(t)),this.fn(e,void 0)}finally{et()}return!0},n.Ut=function(e,t){if(t===void 0&&(t=!1),!g(this.h,e))return!0;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:`remove`}))return null;try{var n;$e();var r=Nt(this),i=this.j.get(e),a=void 0;if(!i&&r&&(a=on(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 Nn&&(a=i.Ot),nt(i)),this.lt.reportChanged(),(n=this.sn)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&Ft(this,{type:`remove`,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{et()}return!0},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.fn=function(e,t){var n,r=Nt(this);r&&r&&Ft(this,r?{type:pr,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.sn)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()},n.rt=function(){return this.lt.reportObserved(),hn(this.h)},n.nt=function(){return this.lt.reportObserved(),Object.keys(this.h)},e}(),br=f(`ObservableObjectAdministration`,yr),xr=Kt(0),Sr=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,!1===e}(),Cr=0,wr=function(){};lr=wr,ur=Array.prototype,Object.setPrototypeOf?Object.setPrototypeOf(lr.prototype,ur):lr.prototype.__proto__===void 0?lr.prototype=ur:lr.prototype.__proto__=ur;var Tr=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray`),i===void 0&&(i=!1),a=e.call(this)||this,$t((function(){var e=new sr(r,n,i,!0);e.v=a,d(a,N,e),t&&t.length&&a.spliceWithArray(0,0,t),Sr&&Object.defineProperty(a,`0`,xr)})),a}te(t,e);var n=t.prototype;return n.concat=function(){this[N].st.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map((function(e){return Bt(e)?e.slice():e})))},n[Symbol.iterator]=function(){var e=this,t=0;return nn({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},S(t,[{key:`length`,get:function(){return this[N].Ft()},set:function(e){this[N].Xt(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(wr);Object.entries(cr).forEach((function(e){var t=e[0];t!==`concat`&&u(Tr.prototype,t,e[1])})),Jt(1e3);var Er=cn.toString,Dr=n().Iterator?.prototype||{};[`Symbol`,`Map`,`Set`].forEach((function(e){n()[e]===void 0&&t(`MobX requires global '`+e+`' to be available or polyfilled`)})),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:at,extras:{getDebugName:Qt},$mobx:N}),e.$mobx=N,e.FlowCancellationError=$n,e.ObservableMap=mr,e.ObservableSet=_r,e.Reaction=Un,e._allowStateChanges=Le,e._allowStateChangesInsideComputed=st,e._allowStateReadsEnd=Je,e._allowStateReadsStart=qe,e._autoAction=Xn,e._endAction=Ie,e._getAdministration=Zt,e._getGlobalState=function(){return z},e._interceptReads=function(e,t,n){var r;return hr(e)||Bt(e)||Pn(e)?r=Zt(e):Gt(e)&&(r=Zt(e,t)),r.dehancer=typeof t==`function`?t:n,function(){r.dehancer=void 0}},e._isComputingDerivation=function(){return z.trackingDerivation!==null},e._resetGlobalState=function(){var e=new Bn;for(var t in e)zn.indexOf(t)===-1&&(z[t]=e[t]);z.allowStateChanges=!z.enforceActions},e._startAction=Fe,e.action=Yn,e.autorun=lt,e.comparer=vn,e.computed=kn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((z.pendingReactions.length||z.inBatch||z.isRunningReactions)&&t(36),Hn=!0,Vn){var e=n();--e.__mobxInstanceCount==0&&(e.__mobxGlobals=void 0),z=new Bn}}();var r,i,a=e.useProxies,o=e.enforceActions;if(a!==void 0&&(z.useProxies=a===`always`||a!==`never`&&typeof Proxy<`u`),a===`ifavailable`&&(z.verifyProxies=!0),o!==void 0){var s=o===`always`?`always`:o===`observed`;z.enforceActions=s,z.allowStateChanges=!0!==s&&s!==`always`}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach((function(t){t in e&&(z[t]=!!e[t])})),z.allowStateReads=!z.observableRequiresReaction,e.reactionScheduler&&(r=e.reactionScheduler,i=B,B=function(e){return r((function(){return i(e)}))})},e.createAtom=se,e.defineProperty=function(e,n,r){if(Gt(e))return e[N].l(n,r);t(39)},e.entries=function(e){return Gt(e)?St(e).map((function(t){return[t,e[t]]})):hr(e)?St(e).map((function(t){return[t,e.get(t)]})):V(e)?Array.from(e.entries()):Bt(e)?e.map((function(e,t){return[t,e]})):void t(7)},e.extendObservable=mt,e.flow=nr,e.flowResult=function(e){return e},e.get=function(e,n){if(Ct(e,n))return Gt(e)?e[N].ct(n):hr(e)?e.get(n):Bt(e)?e[n]:void t(11)},e.getAtom=Xt,e.getDebugName=Qt,e.getDependencyTree=function(e,t){return ht(Xt(e,t))},e.getObserverTree=function(e,t){return gt(Xt(e,t))},e.has=Ct,e.intercept=function(e,t,n){return a(n)?function(e,t,n){return Zt(e,t).St(n)}(e,t,n):function(e,t){return Zt(e).St(t)}(e,t)},e.isAction=ct,e.isBoxedObservable=Pn,e.isComputed=function(e){return yt(e)},e.isComputedProp=function(e,t){return yt(e,t)},e.isFlow=vt,e.isFlowCancellationError=function(e){return e instanceof $n},e.isObservable=xt,e.isObservableArray=Bt,e.isObservableMap=hr,e.isObservableObject=Gt,e.isObservableProp=function(e,t){return bt(e,t)},e.isObservableSet=V,e.keys=St,e.makeAutoObservable=function(e,t,n){return c(e)?mt(e,e,t,n):($t((function(){var r=Ut(e,n)[N];if(!e[ir]){var i=Object.getPrototypeOf(e),a=new Set([].concat(hn(e),hn(i)));a.delete(`constructor`),a.delete(N),u(i,ir,a)}e[ir].forEach((function(e){return r.o(e,!t||!(e in t)||t[e])}))})),e)},e.makeObservable=function(e,t,n){return $t((function(){var r=Ut(e,n)[N];t??=function(e){return g(e,gn)||u(e,gn,ee({},e[gn])),e[gn]}(e),hn(t).forEach((function(e){return r.o(e,t[e])}))})),e},e.observable=En,e.observe=function(e,t,n,r){return a(n)?function(e,t,n,r){return Zt(e,t)._t(n,r)}(e,t,n,r):function(e,t,n){return Zt(e)._t(t,n)}(e,t,n)},e.onBecomeObserved=dt,e.onBecomeUnobserved=ft,e.onReactionError=function(e){return z.globalReactionErrorHandlers.push(e),function(){var t=z.globalReactionErrorHandlers.indexOf(e);t>=0&&z.globalReactionErrorHandlers.splice(t,1)}},e.override=yn,e.ownKeys=wt,e.reaction=function(e,t,n){function r(){if(p=!1,!h.isDisposed){var t=!1,r=s;h.track((function(){var n=Le(!1,(function(){return e(h)}));t=f||!m(s,n),s=n})),(f&&n.fireImmediately||!f&&t)&&l(s,r,h),f=!1}}var i;n===void 0&&(n=un);var a,o,s,c=n.name??`Reaction`,l=Yn(c,n.onError?(a=n.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){a.call(this,e)}}):t),u=!n.scheduler&&!n.delay,d=ut(n),f=!0,p=!1,m=n.compareStructural?vn.structural:n.equals||vn.default,h=new Un(c,(function(){f||u?r():p||(p=!0,d(r))}),n.onError,n.requiresObservable);return(i=n)!=null&&(i=i.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Gt(e)?e[N].Ut(n):hr(e)||V(e)?e.delete(n):Bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=st,e.set=function e(n,r,i){if(arguments.length!==2||V(n))Gt(n)?n[N].ht(r,i):hr(n)?n.set(r,i):V(n)?n.add(r):Bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(`Invalid index: '`+r+`'`),$e(),r>=n.length&&(n.length=r+1),n[r]=i,et()):t(8);else{$e();var a=r;try{for(var o in a)e(n,o,a[o])}finally{et()}}},e.spy=at,e.toJS=function(e){return function e(t,n){if(typeof t!=`object`||!t||t instanceof Date||!xt(t))return t;if(Pn(t)||Ln(t))return e(t.get(),n);if(n.has(t))return n.get(t);if(Bt(t)){var r=Tt(n,t,Array(t.length));return t.forEach((function(t,i){r[i]=e(t,n)})),r}if(V(t)){var i=Tt(n,t,new Set);return t.forEach((function(t){i.add(e(t,n))})),i}if(hr(t)){var a=Tt(n,t,new Map);return t.forEach((function(t,r){a.set(r,e(t,n))})),a}var o=Tt(n,t,{});return wt(t).forEach((function(r){cn.propertyIsEnumerable.call(t,r)&&(o[r]=e(t[r],n))})),o}(e,new Map)},e.trace=function(){},e.transaction=Et,e.untracked=We,e.values=function(e){return Gt(e)?St(e).map((function(t){return e[t]})):hr(e)?St(e).map((function(t){return e.get(t)})):V(e)?Array.from(e.values()):Bt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ot(e,t):Dt(e,t,n||{})}})),Ix=ve((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1:function(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.`,17:function(e,t){return`[mobx.array] Index out of bounds, `+e+` is larger than `+t},18:`mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js`,19:function(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20:function(e){return`Cannot initialize map from `+e},21:function(e){return`Cannot convert to map from '`+e+`'`},22:`mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js`,23:`It is not possible to get index atoms from arrays`,24:function(e){return`Cannot obtain administration from `+e},25:function(e,t){return`the entry '`+e+`' does not exist in the observable map '`+t+`'`},26:`please specify a property`,27:function(e,t){return`no observable property '`+e.toString()+`' found on the observable object '`+t+`'`},28:function(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:function(e,t){return`Cycle detected in computation `+e+`: `+t},33:function(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:function(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:function(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`};function n(e){var n=[...arguments].slice(1),r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] `+r)}var r={};function i(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:r}var a=Object.assign,o=Object.getOwnPropertyDescriptor,s=Object.defineProperty,c=Object.prototype,l=[];Object.freeze(l);var u={};Object.freeze(u);var d=typeof Proxy<`u`,f=Object.toString();function p(){d||n("`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`")}function m(e){I.verifyProxies&&n(`MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to `+e)}function h(){return++I.mobxGuid}function g(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var _=function(){};function v(e){return typeof e==`function`}function y(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===f}function S(e){var t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function C(e,t,n){s(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function ee(e,t,n){s(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function w(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return b(e)&&e[n]===!0}}function te(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function ne(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function re(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}var ie=Object.getOwnPropertySymbols!==void 0;function T(e){var t=Object.keys(e);if(!ie)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter(function(t){return c.propertyIsEnumerable.call(e,t)})):t}var E=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:ie?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function ae(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function oe(e){return e===null?null:typeof e==`object`?``+e:e}function se(e,t){return c.hasOwnProperty.call(e,t)}var ce=Object.getOwnPropertyDescriptors||function(e){var t={};return E(e).forEach(function(n){t[n]=o(e,n)}),t};function le(e,t){return!!(e&t)}function ue(e,t,n){return n?e|=t:e&=~t,e}function de(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function fe(e,t,n){if(be())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&D(i,n.prototype),i}function pe(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,Se(r.key),r)}}function me(e,t,n){return t&&pe(e.prototype,t),n&&pe(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function he(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=Ce(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
59
59
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ge(){return ge=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ge.apply(null,arguments)}function _e(e){return _e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_e(e)}function ve(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,D(e,t)}function ye(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function be(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(be=function(){return!!e})()}function D(e,t){return D=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},D(e,t)}function xe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Se(e){var t=xe(e,`string`);return typeof t==`symbol`?t:t+``}function Ce(e,t){if(e){if(typeof e==`string`)return de(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?de(e,t):void 0}}function we(e){var t=typeof Map==`function`?new Map:void 0;return we=function(e){if(e===null||!ye(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return fe(e,arguments,_e(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),D(n,e)},we(e)}var Te=Symbol(`mobx-stored-annotations`);function Ee(e){function t(t,n){if(Ae(n))return e.decorate_20223_(t,n);De(t,n,e)}return Object.assign(t,e)}function De(e,t,r){se(e,Te)||C(e,Te,ge({},e[Te])),Ke(r)&&!se(e[Te],t)&&n(`'`+(e.constructor.name+`.prototype.`+t.toString())+`' is decorated with 'override', but no such decorated member was found on prototype.`),Oe(e,r,t),Ke(r)||(e[Te][t]=r)}function Oe(e,t,r){if(!Ke(t)&&se(e[Te],r)){var i=e.constructor.name+`.prototype.`+r.toString(),a=e[Te][r].annotationType_,o=t.annotationType_;n(`Cannot apply '@`+o+`' to '`+i+`':`+(`
60
60
  The field is already decorated with '@`+a+`'.`)+`
61
61
  Re-decorating fields is not allowed.
@@ -85,18 +85,18 @@ The target is already observable of different type.
85
85
  Extending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);var r=t?.name??(x(e)?`ObservableObject`:e.constructor.name)+`@`+h();return C(e,O,new Xi(e,new Map,String(r),It(t))),e}var Qi=w(`ObservableObjectAdministration`,Xi);function $i(e){return Ji[e]||(Ji[e]={get:function(){return this[O].getObservablePropValue_(e)},set:function(t){return this[O].setObservablePropValue_(e,t)}})}function ea(e){return b(e)?Qi(e[O]):!1}function ta(e,t,n){var r;e.appliedAnnotations_[n]=t,(r=e.target_[Te])==null||delete r[n]}function na(e,t,r){if(Ca(t)||n(`Cannot annotate '`+e.name_+`.`+r.toString()+`': Invalid annotation.`),!Ke(t)&&se(e.appliedAnnotations_,r)){var i=e.name_+`.`+r.toString(),a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '`+o+`' to '`+i+`':`+(`
86
86
  The field is already annotated with '`+a+`'.`)+`
87
87
  Re-annotating fields is not allowed.
88
- Use 'override' annotation for methods overridden by subclass.`)}}var ra=la(0),ia=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),aa=0,oa=function(){};function sa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}sa(oa,Array.prototype);var ca=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ga(function(){var e=new ki(r,n,i,!0);e.proxy_=a,ee(a,O,e),t&&t.length&&a.spliceWithArray(0,0,t),ia&&Object.defineProperty(a,`0`,ra)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[O].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Li(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return W({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},me(t,[{key:`length`,get:function(){return this[O].getArrayLength_()},set:function(e){this[O].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(oa);Object.entries(ji).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&C(ca.prototype,t,n)});function la(e){return{enumerable:!1,configurable:!0,get:function(){return this[O].get_(e)},set:function(t){this[O].set_(e,t)}}}function ua(e){s(ca.prototype,``+e,la(e))}function da(e){if(e>aa){for(var t=aa;t<e+100;t++)ua(t);aa=e}}da(1e3);function fa(e,t,n){return new ca(e,t,n)}function pa(e,t){if(typeof e==`object`&&e){if(Li(e))return t!==void 0&&n(23),e[O].atom_;if(Ki(e))return e.atom_;if(Hi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,ha(e)),r}if(ea(e)){if(!t)return n(26);var i=e[O].values_.get(t);return i||n(27,t,ha(e)),i}if(Ne(e)||an(e)||z(e))return e}else if(v(e)&&z(e[O]))return e[O];n(28)}function ma(e,t){if(e||n(29),t!==void 0)return ma(pa(e,t));if(Ne(e)||an(e)||z(e)||Hi(e)||Ki(e))return e;if(e[O])return e[O];n(24,e)}function ha(e,t){var n;if(t!==void 0)n=pa(e,t);else if(cr(e))return e.name;else n=ea(e)||Hi(e)||Ki(e)?ma(e):pa(e);return n.name_}function ga(e){var t=N(),n=Qt(!0);L();try{return e()}finally{jn(),$t(n),P(t)}}var _a=c.toString;function va(e,t,n){return n===void 0&&(n=-1),ya(e,t,n)}function ya(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;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=_a.call(e);if(o!==_a.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=ba(e),t=ba(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!ya(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(se(t,m)&&ya(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function ba(e){return Li(e)?e.slice():te(e)||Hi(e)||re(e)||Ki(e)?Array.from(e.entries()):e}var xa=i().Iterator?.prototype||{};function W(e){return e[Symbol.iterator]=Sa,Object.assign(Object.create(xa),e)}function Sa(){return this}function Ca(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:ha},$mobx:O}),e.$mobx=O,e.FlowCancellationError=kr,e.ObservableMap=Vi,e.ObservableSet=Gi,e.Reaction=Ln,e._allowStateChanges=Zt,e._allowStateChangesInsideComputed=sr,e._allowStateReadsEnd=vn,e._allowStateReadsStart=_n,e._autoAction=or,e._endAction=Xt,e._getAdministration=ma,e._getGlobalState=wn,e._interceptReads=Lr,e._isComputingDerivation=un,e._resetGlobalState=Tn,e._startAction=Yt,e.action=ar,e.autorun=lr,e.comparer=ze,e.computed=Ut,e.configure=xr,e.createAtom=Pe,e.defineProperty=ei,e.entries=Yr,e.extendObservable=Sr,e.flow=Nr,e.flowResult=Fr,e.get=$r,e.getAtom=pa,e.getDebugName=ha,e.getDependencyTree=Cr,e.getObserverTree=Tr,e.has=Qr,e.intercept=Rr,e.isAction=cr,e.isBoxedObservable=nn,e.isComputed=Hr,e.isComputedProp=Ur,e.isFlow=Ir,e.isFlowCancellationError=Ar,e.isObservable=Gr,e.isObservableArray=Li,e.isObservableMap=Hi,e.isObservableObject=ea,e.isObservableProp=Kr,e.isObservableSet=Ki,e.keys=qr,e.makeAutoObservable=Ti,e.makeObservable=Ci,e.observable=k,e.observe=ni,e.onBecomeObserved=gr,e.onBecomeUnobserved=_r,e.onReactionError=Rn,e.override=Ge,e.ownKeys=ti,e.reaction=fr,e.remove=Zr,e.runInAction=sr,e.set=Xr,e.spy=Jn,e.toJS=si,e.trace=ci,e.transaction=ui,e.untracked=gn,e.values=Jr,e.when=di})),Ix=ve(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Px():t.exports=Fx()}))();function Lx(e){if(Array.isArray(e))return Object.freeze(e.map(Lx));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]=Lx(r);return Object.freeze(t)}return e}function Rx(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 zx(e){return typeof e==`string`?e:String(e)}function Bx(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 Vx(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")`)}function Hx(e,t){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=ki(e.style,t),n}function Ux(e){return{fn:(t=>Hx(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Wx(e){return{fn:((t,n)=>Hx(n,new H({[e]:L.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Gx(e,t){return new H({[e]:t})}function Kx(){let e={};for(let t of Si)e[t]=Ux(Gx(t,!0)),e[`not_${t}`]=Ux(Gx(t,!1));for(let[t,n]of Object.entries(wi))e[t]=Ux(Gx(n,!0));return e}const qx={fn:((e,t)=>Hx(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},Jx={fn:((e,t)=>Hx(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function Yx(){return{fg:Wx(`color`),bg:Wx(`bgcolor`),...Kx(),link:Jx,style:qx}}function Xx(e,t){let n;try{n=Un(e.trim())}catch(n){throw n instanceof kn?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 Zx(n,t,JSON.stringify(e))}function Zx(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 Qx(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function $x(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 eS=Qx([`string`,`int`],((e,t)=>Tr(Xx(e,`darken`),t).hex)),tS=Qx([`string`,`int`],((e,t)=>Tr(Xx(e,`lighten`),-t).hex)),nS={min:0,max:100,note:`0 = from, 100 = toward`},rS=Qx([`string`,`string`,`float`],((e,t,n)=>B(Xx(e,`mix`),Xx(t,`mix`),$x(n,`mix`,`percentage`,nS)/100).hex)),iS={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},aS=Qx([`string`],(e=>Dr(Xx(e,`contrastOn`)).hex)),oS={depth:F.TRUECOLOR},sS=e=>Qx([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Or(Xx(t,`readableOn`),Xx(n,`readableOn`),$x(r,`readableOn`,`ratio`,iS),i,void 0,a).hex})),cS={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function lS(){let e={};for(let[t,n]of Object.entries(cS)){let r=t;e[n]=Qx([`string`,`float`],((e,t)=>{let i={...sr,[r]:$x(t,n,`amount`)};return V.fromRgba(Xx(e,n)).applyKey(i).toRgba().hex}))}return e}function uS(e=()=>oS){return{darken:eS,lighten:tS,mix:rS,contrastOn:aS,readableOn:sS(e),...lS()}}function dS(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:Zx(yr(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function fS(e){return{color:{fn:(t=>yr(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new di(_i(n),dS(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function pS(e){return{...Yx(),...uS(e)}}new H({color:`red`,dim:!0});const mS=/^(?:(?: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,hS=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function gS(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(mS);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(hS);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 _S(e){let t=e.match(hS);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 vS(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 yS(e){return e.toLocaleString()}function bS(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 xS(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 SS=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],CS=SS.length;function wS(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*(CS-1));o+=SS[t]}return o}function TS(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 ES(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 DS=jc(),OS=[...Xc];function kS(){return{basename:{fn:e=>u(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>d(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>vS(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Bx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>zx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Vx(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>DS,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>OS,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ES(`sparkline`,[`width`],n),wS(TS(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>xS(e,bS(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function AS(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>yS(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>gS(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>_S(e),argTypes:[`string`],arity:{kind:`exact`}}}}function jS(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return _g({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,clock:t,missingKey:`error`,funcs:{...ov(),...bb(),...Jv(),...gy(),...Q_(t),...Hg(),...Sv(),...bv(),...pS(n&&(()=>({depth:n()}))),...kS(),...AS(t),...r??{}}})}function MS(e){return NS(e,new Set(e.names()),``)}function NS(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?FS(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return NS(e,t,a)}})}function PS(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 FS(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function J(e){return{kind:`ok`,value:e}}const Y={kind:`absent`};function X(e){return{kind:`failed`,reason:e}}function IS(e,t){return e?.kind===`ok`?e.value:t}function LS(e,t,n){return t.ok?J(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?Y:X(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??RS(t.stderr)].filter(Boolean).join(`, `)}`)}function RS(e){return e.trim().split(`
89
- `,1)[0]??``}function zS(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Y:J(n)}function BS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?J(t):Y}const VS=/^[A-Za-z]:[\\/]/;function HS(e){let t=e.trim();if(VS.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 US(e){return HS(e)?.host||null}function WS(e){let t=US(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function GS(e){let t=new Map;for(let n of e.split(`
90
- `)){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 KS(e){return e.urls.find(e=>ZS(e)!==null)??e.urls[0]??null}function qS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function JS(e){let t=qS(e);return t?KS(t):null}function YS(e){let t=qS(e);return t?t.urls.find(e=>WS(e)!==null)??KS(t):null}function XS(e){let t=(HS(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function ZS(e){let t=HS(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 QS(e){let t=JS(e);return t===null?null:ZS(t)}function $S(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Y:X(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??RS(t.stderr)].filter(Boolean).join(`, `)}`)}function eC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tC(e){let t=`detached`,n=Y,r=Y,i=Y,a=0,o=0,s=0,c=0;for(let l of e.split(`
91
- `)){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)`?Y:J(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=J(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=J({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 nC(e){let t;try{t=JSON.parse(e)}catch(e){return X(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!eC(t))return X(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i}=t;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`gh pr view: missing number/state/url`):r.toUpperCase()===`OPEN`?J({number:n,state:r,url:i}):Y}function rC(e){let t;try{t=JSON.parse(e)}catch(e){return X(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!eC(t))return X(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`glab mr view: missing iid/state/web_url`):r.toLowerCase()===`opened`?J({number:n,state:r,url:i}):Y}function iC(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var aC=class{isGitRepo(e){try{return r.existsSync(l.join(e,`.git`))}catch{return!1}}async execGitAsync(e,t){return je({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?J(e):t&&this.isGitRepo(t)?J(t):this.isGitRepo(e)?J(e):this.findGitRoot(e)}async findGitRoot(e){let t=l.resolve(e);for(;;){if(this.isGitRepo(t))return J(t);let e=l.dirname(t);if(e===t)return Y;t=e}}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return X(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=await this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=zS(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=zS(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=zS(s,QS)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),J(o)}resolveGitDir(e){let t=l.join(e,`.git`);try{if(r.existsSync(t)&&r.statSync(t).isFile()){let n=r.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return l.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return r.existsSync(l.join(t,`MERGE_HEAD`))?J(`MERGE`):r.existsSync(l.join(t,`CHERRY_PICK_HEAD`))?J(`CHERRY-PICK`):r.existsSync(l.join(t,`REVERT_HEAD`))?J(`REVERT`):r.existsSync(l.join(t,`BISECT_LOG`))?J(`BISECT`):r.existsSync(l.join(t,`rebase-merge`))||r.existsSync(l.join(t,`rebase-apply`))?J(`REBASE`):Y}catch(e){return X(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return BS(LS(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestampMs(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestampMs(e,t){let n=BS(LS(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10)*1e3;return Number.isNaN(r)?X(`git log -1: unparseable timestamp "${n.value}"`):J(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=r.readFileSync(l.join(t,`commondir`),`utf-8`).trim();if(e)return l.resolve(t,e)}catch{}return t}getStashCount(e){let t=l.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=r.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?J(0):X(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let i=n.trim();return J(i?i.split(`
92
- `).length:0)}async getRemotesAsync(e){let t=iC(l.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=LS(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:J(t.kind===`ok`?GS(t.value):[])}repoNameFrom(e,t){let n=JS(e);return(n===null?null:XS(n))??l.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=YS(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return je({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=WS(t);return n===`github`?$S(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,nC):n===`gitlab`?$S(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,rC):Y}isWorktree(e){try{let t=l.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=LS(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J(tC(t.value)):t}};let oC=null;function sC(e){if(oC!==null)return oC;r.mkdirSync(l.dirname(e),{recursive:!0});try{oC=r.statSync(e).size}catch{oC=0}return oC}function cC(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}oC=0}const lC=(e,t)=>D(t);function Z(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Qe(),t=sC(e);r.appendFileSync(e,n),oC=t+Buffer.byteLength(n,`utf8`),oC>=5242880&&cC(e)}catch(e){oC=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const uC=(e,t)=>D(t);var dC=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??uC}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},fC=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const pC={showSha:!0,showStashCount:!0};function mC(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function hC(e){let t=t=>{try{return r.statSync(l.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function gC(e,t){return e.head!==t.head||e.index!==t.index}function _C(e){let t=[],n=l.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[l.join(e,`HEAD`),l.join(e,`index`)],dirs:t}}var vC=class extends aC{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new fC;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new aC,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??lC,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new dC({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${mC(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(J(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=hC(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,_C(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Y;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,_C(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...pC});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...pC}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=hC(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),gC(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const yC=/\r\n|\r|\n/g,bC=e=>J(e.replace(yC,` `).trim());function xC(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(yC,` `))}}const SC=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}},CC=e=>e.getTime()/1e3,wC=e=>new Date(e*1e3);function TC(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function EC(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 DC=`session.id`;function OC(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await je({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?J(r.stdout):X(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function kC(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return J(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return X(`file unreadable: ${e}`)}}}}function AC(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?X(`${r.reason} in ${n}`):r}const jC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],MC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],NC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],PC=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function FC(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>jC[e.getMonth()]],[`Monday`,e=>NC[e.getDay()]],[`Jan`,e=>MC[e.getMonth()]],[`Mon`,e=>PC[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const IC={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function LC(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=IC[t];try{return GC(r,e)}catch{return KC(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return IS(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return IS(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return IS(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return IS(e.stashCount,0)}}function RC(e){try{return o(e)}catch{return e}}function zC(e){try{return s(e).isDirectory()}catch{return!1}}function BC(e){let t=RC(e);return zC(t)?{dir:t,name:null,leaf:!0}:Mx(t)}const VC=e=>`${e.dir}\0${e.name??``}`;var HC=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:BC(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=BC(e);if(t.watcher!==null&&VC(n)===VC(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=l.basename(r);try{return c(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},UC=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ne(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(te(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())te(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WC(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GC(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`?zx(e):t===`number`?Bx(e):Vx(e)}function KC(e){return e===`number`?0:e===`boolean`?!1:``}var qC=class{inputMetas=new Map;lastErrors=new Map;watchFaults=new Map;watchMgr=new HC;ttlMgr=new UC;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fC;abort=new AbortController;drawn=Ix.observable.box(F.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=Ix.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return wC(e)};engine=jS({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new vC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Rx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,X(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,OC(t,n.cwd,this.abort.signal),TC(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,kC(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,bC,t.default,n);case`regex`:return this.scalarPublisher(e,xC(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=AC(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,IS(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?Y:o,c=AC(s,SC,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(MS(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>FC(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=IC[t.field],r=t.varDefault===void 0?KC(n):GC(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,LC(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(DC);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(DC):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WC(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GC(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.watchFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.watchFaults.set(e,{timestamp:Date.now(),message:t}));this.cleanups.push(r);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Ix.reaction)(()=>{let t=MS(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Ix.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GC(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KC(t))}}defaultFor(e){try{return GC(this.defaultEmptyValue,e)}catch{return KC(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const JC={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[DC]:{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:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"effect.effective":{kind:`input`,path:`effect.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"shade.effective":{kind:`input`,path:`shade.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"transitions.effective":{kind:`input`,path:`transitions.effective`,type:`boolean`,default:!1},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,default:!0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},YC=`ne .tmux.pane ""`,XC={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`,label:`🎨`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`,label:`▦`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`,label:`◐`},effect:{configKey:`effect`,sessionKey:`effect`,effectiveVar:`effect.effective`,label:`✨`},endcaps:{configKey:`endcaps`,sessionKey:`endcaps`,effectiveVar:`endcaps.effective`,label:`✦`},variation:{configKey:`variation`,sessionKey:`variation`,effectiveVar:`variation.effective`,label:`🎼`},shade:{configKey:`shade`,sessionKey:`shade`,effectiveVar:`shade.effective`,label:`🔆`},transitions:{configKey:`transitions`,sessionKey:`transitions`,effectiveVar:`transitions.effective`,label:`fade in`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`,label:`wrap`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`,label:`padding`},updateNotice:{configKey:`updateNotice`,sessionKey:`updateNotice`,effectiveVar:`updateNotice.effective`,label:`update notice`}},ZC=Object.values(XC),QC=[{configKey:`charset`,effectiveVar:`charset.effective`},{configKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`}],$C=new Set(QC.map(e=>e.configKey)),ew=new Map([...ZC,...QC].map(e=>[e.configKey,e.effectiveVar])),tw=new Map(ZC.map(e=>[e.sessionKey,e.effectiveVar]));function nw(e){return Object.fromEntries(Object.keys(XC).map(t=>[t,e(t)]))}const rw=new Map(Object.keys(XC).map(e=>[XC[e].sessionKey,e]));function iw(e,t,n){let r=new Set,i=e=>{for(let t of Sx(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of wu(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(DC);for(let t of Object.values(e.actions)){r.add(DC),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?tw.get(t.set):void 0,n=`persist`in t?ew.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function aw(e,t,n){let r=Ax({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of iw(e,t,n.helpers)){if(kx(a,r))continue;let e=JC[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}const ow=new Map;function sw(e){let t=lw(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 cw(e,t){return e===`bar`?t:sw(e)}function lw(e){let t=ow.get(e);if(t!==void 0)return t;let n=Qr(e);return n===null?null:(ow.set(e,n),n)}function uw(e,t){return dw(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>ui(e,t))}const dw=vs();function fw(e){let t=lw(e);return t===null?null:{kind:`decided`,name:e,value:t}}function pw(e,t,n){let r=fw(e);return r===null?(n(`${t} rendered "${kc}": "${e}" names no installed theme${Oc(e)}`),hw()):r}function mw(e,t,n){return Rc(e,t,n,hw(),fw)}function hw(){return{kind:`decided`,name:kc,value:sw(kc)}}const gw=new Map;function _w(e,t,n){gw.set(e,{permanent:!0,resolve:t,paletteOf:n})}_w(`themes`,()=>jc(),e=>sw(e));const vw=`placementThemes`;_w(vw,Mc,(e,t)=>cw(e,t.palette)),_w(`endcaps`,()=>Xc),_w(`variations`,()=>ol),_w(`shades`,()=>ll),_w(`charsets`,()=>tl),_w(`colorCompatibilities`,()=>il);function yw(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>uw(n.basePalette,e.styles[t])}],[`presets`,{members:Mb(e.presets)}]])}function bw(e){return[...new Set([...gw.keys(),...e.keys()])]}function xw(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=gw.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(Cw(e,t))}const Sw=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function Cw(e,t){let n=Sw.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${bw(t).join(`, `)})`}function ww(e,t,n){return e===`bool`?gl(t)!==null:`from`in e?xw(e.from,n).members.includes(t):_l(t,e)!==null}function Tw(e,t){if(e===`bool`)return ml.join(` or `);if(`from`in e){let{members:n}=xw(e.from,t),r=n.map(e=>JSON.stringify(e));if(n.length<=8)return`one of ${r.join(`, `)}`;let i=typeof e.from==`string`?` "${e.from}"`:``;return`one of the ${n.length}${i} names, such as ${r.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function Ew(e){return{label:e.label,domain:Dw(e.domain)}}function Dw(e){return e===`theme`?{from:vw}:e===`bool`||`min`in e?e:{from:e}}function Ow(e,t,n,r,i){let a=Wd(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...ml]}},variables:{}};if(`from`in o)return kw(a,t,r,i,o.from);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 kw(e,t,n,r,i){let a={variable:r,key:r,member:n},o=wb(r,n),s=`${n}.open`,c=Tb(r),l=`${c}.first`;return{kind:`picker`,template:`{{ "${e}" }} {{ carousel "${n}" 0 "${s}" }}`,actions:{[n]:{set:t,from:i},[o]:Qd(r,n),[c]:{set:c,int:!0},[l]:{set:c,to:`0`},[s]:{do:[o,l]}},variables:{[r]:Zd(r,Bd),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,template:`{{ picker "${n}" "${c}" false true true }}`}}}const Aw=/^segments\.([^.]+)\.palette$/,jw=/^presets\.(.+)\.root$/,Mw=/^presets\.(.+)\.globals\.([^.]+)$/,Nw=/^themeDefaults\.(.+)\.([^.]+)$/;function Pw(e){return`presets.${e}.root`}function Fw(e,t){return`themeDefaults.${e}.${t}`}const Iw=e=>ku.includes(e);function Lw(e,t){return`presets.${e}.globals.${t}`}function Rw(e){if(jf(e))return{scope:`globals`,field:e};let t=Aw.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Mw.exec(e);if(n&&xf(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=Nw.exec(e);if(r&&Iw(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=jw.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function zw(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 Bw=`open`;function Vw(e,t,n,r){let i={variable:e,key:e,member:Bw};return r.variables[e]=Zd(e,Bd),r.actions[e]=Qd(e,Bw),r.segments[e]={template:Jd(e,`(?)`,`✕`),...Hw(n)},Gd(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 Hw(e){let[t,...n]=e;return t===void 0?{}:{when:Kd(t,...n)}}const Uw=`none`;function Ww(e){return yr(e,`background`)}var Gw=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Kw(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=qw(n,i),l=c!==Uw,u=l?c===void 0?o:Jw(a,c,`bg`):Ww(a);e.bg=u;let d=qw(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:nc(a,e,t))(u):void 0:Jw(a,d,`fg`);return new H({...l&&{bgcolor:L.fromRgba(u)},...f!==void 0&&{color:L.fromRgba(f)}})}function qw(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Jw(e,t,n){try{return yr(e,t)}catch(e){throw e instanceof vr?new Gw(t,n,e.message):e}}const Yw={help:[`-h`,`--help`],version:[`-V`,`--version`]},Xw=[`✚ inserts`,`✖ removes`,`⚙️ configures`,`↺ resets layout`],Zw=`
88
+ Use 'override' annotation for methods overridden by subclass.`)}}var ra=la(0),ia=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),aa=0,oa=function(){};function sa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}sa(oa,Array.prototype);var ca=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ga(function(){var e=new ki(r,n,i,!0);e.proxy_=a,ee(a,O,e),t&&t.length&&a.spliceWithArray(0,0,t),ia&&Object.defineProperty(a,`0`,ra)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[O].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Li(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return W({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},me(t,[{key:`length`,get:function(){return this[O].getArrayLength_()},set:function(e){this[O].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(oa);Object.entries(ji).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&C(ca.prototype,t,n)});function la(e){return{enumerable:!1,configurable:!0,get:function(){return this[O].get_(e)},set:function(t){this[O].set_(e,t)}}}function ua(e){s(ca.prototype,``+e,la(e))}function da(e){if(e>aa){for(var t=aa;t<e+100;t++)ua(t);aa=e}}da(1e3);function fa(e,t,n){return new ca(e,t,n)}function pa(e,t){if(typeof e==`object`&&e){if(Li(e))return t!==void 0&&n(23),e[O].atom_;if(Ki(e))return e.atom_;if(Hi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,ha(e)),r}if(ea(e)){if(!t)return n(26);var i=e[O].values_.get(t);return i||n(27,t,ha(e)),i}if(Ne(e)||an(e)||z(e))return e}else if(v(e)&&z(e[O]))return e[O];n(28)}function ma(e,t){if(e||n(29),t!==void 0)return ma(pa(e,t));if(Ne(e)||an(e)||z(e)||Hi(e)||Ki(e))return e;if(e[O])return e[O];n(24,e)}function ha(e,t){var n;if(t!==void 0)n=pa(e,t);else if(cr(e))return e.name;else n=ea(e)||Hi(e)||Ki(e)?ma(e):pa(e);return n.name_}function ga(e){var t=N(),n=Qt(!0);L();try{return e()}finally{jn(),$t(n),P(t)}}var _a=c.toString;function va(e,t,n){return n===void 0&&(n=-1),ya(e,t,n)}function ya(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;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=_a.call(e);if(o!==_a.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=ba(e),t=ba(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!ya(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(se(t,m)&&ya(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function ba(e){return Li(e)?e.slice():te(e)||Hi(e)||re(e)||Ki(e)?Array.from(e.entries()):e}var xa=i().Iterator?.prototype||{};function W(e){return e[Symbol.iterator]=Sa,Object.assign(Object.create(xa),e)}function Sa(){return this}function Ca(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:ha},$mobx:O}),e.$mobx=O,e.FlowCancellationError=kr,e.ObservableMap=Vi,e.ObservableSet=Gi,e.Reaction=Ln,e._allowStateChanges=Zt,e._allowStateChangesInsideComputed=sr,e._allowStateReadsEnd=vn,e._allowStateReadsStart=_n,e._autoAction=or,e._endAction=Xt,e._getAdministration=ma,e._getGlobalState=wn,e._interceptReads=Lr,e._isComputingDerivation=un,e._resetGlobalState=Tn,e._startAction=Yt,e.action=ar,e.autorun=lr,e.comparer=ze,e.computed=Ut,e.configure=xr,e.createAtom=Pe,e.defineProperty=ei,e.entries=Yr,e.extendObservable=Sr,e.flow=Nr,e.flowResult=Fr,e.get=$r,e.getAtom=pa,e.getDebugName=ha,e.getDependencyTree=Cr,e.getObserverTree=Tr,e.has=Qr,e.intercept=Rr,e.isAction=cr,e.isBoxedObservable=nn,e.isComputed=Hr,e.isComputedProp=Ur,e.isFlow=Ir,e.isFlowCancellationError=Ar,e.isObservable=Gr,e.isObservableArray=Li,e.isObservableMap=Hi,e.isObservableObject=ea,e.isObservableProp=Kr,e.isObservableSet=Ki,e.keys=qr,e.makeAutoObservable=Ti,e.makeObservable=Ci,e.observable=k,e.observe=ni,e.onBecomeObserved=gr,e.onBecomeUnobserved=_r,e.onReactionError=Rn,e.override=Ge,e.ownKeys=ti,e.reaction=fr,e.remove=Zr,e.runInAction=sr,e.set=Xr,e.spy=Jn,e.toJS=si,e.trace=ci,e.transaction=ui,e.untracked=gn,e.values=Jr,e.when=di})),Lx=ve(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Fx():t.exports=Ix()}))();function Rx(e){if(Array.isArray(e))return Object.freeze(e.map(Rx));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]=Rx(r);return Object.freeze(t)}return e}function zx(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 Bx(e){return typeof e==`string`?e:String(e)}function Vx(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 Hx(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")`)}function Ux(e,t){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=ki(e.style,t),n}function Wx(e){return{fn:(t=>Ux(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Gx(e){return{fn:((t,n)=>Ux(n,new H({[e]:L.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Kx(e,t){return new H({[e]:t})}function qx(){let e={};for(let t of Si)e[t]=Wx(Kx(t,!0)),e[`not_${t}`]=Wx(Kx(t,!1));for(let[t,n]of Object.entries(wi))e[t]=Wx(Kx(n,!0));return e}const Jx={fn:((e,t)=>Ux(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},Yx={fn:((e,t)=>Ux(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function Xx(){return{fg:Gx(`color`),bg:Gx(`bgcolor`),...qx(),link:Yx,style:Jx}}function Zx(e,t){let n;try{n=Un(e.trim())}catch(n){throw n instanceof kn?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 Qx(n,t,JSON.stringify(e))}function Qx(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 $x(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function eS(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 tS=$x([`string`,`int`],((e,t)=>Tr(Zx(e,`darken`),t).hex)),nS=$x([`string`,`int`],((e,t)=>Tr(Zx(e,`lighten`),-t).hex)),rS={min:0,max:100,note:`0 = from, 100 = toward`},iS=$x([`string`,`string`,`float`],((e,t,n)=>B(Zx(e,`mix`),Zx(t,`mix`),eS(n,`mix`,`percentage`,rS)/100).hex)),aS={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},oS=$x([`string`],(e=>Dr(Zx(e,`contrastOn`)).hex)),sS={depth:F.TRUECOLOR},cS=e=>$x([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Or(Zx(t,`readableOn`),Zx(n,`readableOn`),eS(r,`readableOn`,`ratio`,aS),i,void 0,a).hex})),lS={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function uS(){let e={};for(let[t,n]of Object.entries(lS)){let r=t;e[n]=$x([`string`,`float`],((e,t)=>{let i={...sr,[r]:eS(t,n,`amount`)};return V.fromRgba(Zx(e,n)).applyKey(i).toRgba().hex}))}return e}function dS(e=()=>sS){return{darken:tS,lighten:nS,mix:iS,contrastOn:oS,readableOn:cS(e),...uS()}}function fS(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:Qx(yr(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function pS(e){return{color:{fn:(t=>yr(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new di(_i(n),fS(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function mS(e){return{...Xx(),...dS(e)}}new H({color:`red`,dim:!0});const hS=/^(?:(?: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,gS=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function _S(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(hS);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(gS);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 vS(e){let t=e.match(gS);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 yS(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 bS(e){return e.toLocaleString()}function xS(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 SS(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 CS=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],wS=CS.length;function TS(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*(wS-1));o+=CS[t]}return o}function ES(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 DS(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 OS=jc(),kS=[...Xc];function AS(){return{basename:{fn:e=>u(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>d(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>yS(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Vx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Bx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Hx(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>OS,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>kS,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(DS(`sparkline`,[`width`],n),TS(ES(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>SS(e,xS(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function jS(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>bS(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>_S(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>vS(e),argTypes:[`string`],arity:{kind:`exact`}}}}function MS(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return vg({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,clock:t,missingKey:`error`,funcs:{...sv(),...xb(),...Yv(),..._y(),...$_(t),...Ug(),...Cv(),...xv(),...mS(n&&(()=>({depth:n()}))),...AS(),...jS(t),...r??{}}})}function NS(e){return PS(e,new Set(e.names()),``)}function PS(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?IS(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return PS(e,t,a)}})}function FS(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 IS(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function J(e){return{kind:`ok`,value:e}}const Y={kind:`absent`};function X(e){return{kind:`failed`,reason:e}}function LS(e,t){return e?.kind===`ok`?e.value:t}function RS(e,t,n){return t.ok?J(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?Y:X(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??zS(t.stderr)].filter(Boolean).join(`, `)}`)}function zS(e){return e.trim().split(`
89
+ `,1)[0]??``}function BS(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Y:J(n)}function VS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?J(t):Y}const HS=/^[A-Za-z]:[\\/]/;function US(e){let t=e.trim();if(HS.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 WS(e){return US(e)?.host||null}function GS(e){let t=WS(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function KS(e){let t=new Map;for(let n of e.split(`
90
+ `)){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 qS(e){return e.urls.find(e=>QS(e)!==null)??e.urls[0]??null}function JS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function YS(e){let t=JS(e);return t?qS(t):null}function XS(e){let t=JS(e);return t?t.urls.find(e=>GS(e)!==null)??qS(t):null}function ZS(e){let t=(US(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function QS(e){let t=US(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 $S(e){let t=YS(e);return t===null?null:QS(t)}function eC(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Y:X(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??zS(t.stderr)].filter(Boolean).join(`, `)}`)}function tC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nC(e){let t=`detached`,n=Y,r=Y,i=Y,a=0,o=0,s=0,c=0;for(let l of e.split(`
91
+ `)){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)`?Y:J(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=J(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=J({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 rC(e){let t;try{t=JSON.parse(e)}catch(e){return X(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!tC(t))return X(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i}=t;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`gh pr view: missing number/state/url`):r.toUpperCase()===`OPEN`?J({number:n,state:r,url:i}):Y}function iC(e){let t;try{t=JSON.parse(e)}catch(e){return X(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!tC(t))return X(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`glab mr view: missing iid/state/web_url`):r.toLowerCase()===`opened`?J({number:n,state:r,url:i}):Y}function aC(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var oC=class{isGitRepo(e){try{return r.existsSync(l.join(e,`.git`))}catch{return!1}}async execGitAsync(e,t){return je({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?J(e):t&&this.isGitRepo(t)?J(t):this.isGitRepo(e)?J(e):this.findGitRoot(e)}async findGitRoot(e){let t=l.resolve(e);for(;;){if(this.isGitRepo(t))return J(t);let e=l.dirname(t);if(e===t)return Y;t=e}}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return X(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=await this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=BS(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=BS(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=BS(s,$S)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),J(o)}resolveGitDir(e){let t=l.join(e,`.git`);try{if(r.existsSync(t)&&r.statSync(t).isFile()){let n=r.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return l.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return r.existsSync(l.join(t,`MERGE_HEAD`))?J(`MERGE`):r.existsSync(l.join(t,`CHERRY_PICK_HEAD`))?J(`CHERRY-PICK`):r.existsSync(l.join(t,`REVERT_HEAD`))?J(`REVERT`):r.existsSync(l.join(t,`BISECT_LOG`))?J(`BISECT`):r.existsSync(l.join(t,`rebase-merge`))||r.existsSync(l.join(t,`rebase-apply`))?J(`REBASE`):Y}catch(e){return X(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return VS(RS(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestampMs(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestampMs(e,t){let n=VS(RS(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10)*1e3;return Number.isNaN(r)?X(`git log -1: unparseable timestamp "${n.value}"`):J(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=r.readFileSync(l.join(t,`commondir`),`utf-8`).trim();if(e)return l.resolve(t,e)}catch{}return t}getStashCount(e){let t=l.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=r.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?J(0):X(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let i=n.trim();return J(i?i.split(`
92
+ `).length:0)}async getRemotesAsync(e){let t=aC(l.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=RS(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:J(t.kind===`ok`?KS(t.value):[])}repoNameFrom(e,t){let n=YS(e);return(n===null?null:ZS(n))??l.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=XS(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return je({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=GS(t);return n===`github`?eC(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,rC):n===`gitlab`?eC(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,iC):Y}isWorktree(e){try{let t=l.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=RS(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J(nC(t.value)):t}};let sC=null;function cC(e){if(sC!==null)return sC;r.mkdirSync(l.dirname(e),{recursive:!0});try{sC=r.statSync(e).size}catch{sC=0}return sC}function lC(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}sC=0}const uC=(e,t)=>D(t);function Z(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Qe(),t=cC(e);r.appendFileSync(e,n),sC=t+Buffer.byteLength(n,`utf8`),sC>=5242880&&lC(e)}catch(e){sC=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const dC=(e,t)=>D(t);var fC=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??dC}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},pC=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const mC={showSha:!0,showStashCount:!0};function hC(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function gC(e){let t=t=>{try{return r.statSync(l.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function _C(e,t){return e.head!==t.head||e.index!==t.index}function vC(e){let t=[],n=l.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[l.join(e,`HEAD`),l.join(e,`index`)],dirs:t}}var yC=class extends oC{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new pC;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new oC,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??uC,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new fC({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${hC(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(J(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=gC(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,vC(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Y;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,vC(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...mC});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...mC}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=gC(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),_C(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const bC=/\r\n|\r|\n/g,xC=e=>J(e.replace(bC,` `).trim());function SC(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(bC,` `))}}const CC=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}},wC=e=>e.getTime()/1e3,TC=e=>new Date(e*1e3);function EC(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function DC(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 OC=`session.id`;function kC(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await je({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?J(r.stdout):X(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function AC(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return J(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return X(`file unreadable: ${e}`)}}}}function jC(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?X(`${r.reason} in ${n}`):r}const MC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],NC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],PC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],FC=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function IC(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>MC[e.getMonth()]],[`Monday`,e=>PC[e.getDay()]],[`Jan`,e=>NC[e.getMonth()]],[`Mon`,e=>FC[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const LC={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function RC(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=LC[t];try{return KC(r,e)}catch{return qC(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return LS(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return LS(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return LS(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return LS(e.stashCount,0)}}function zC(e){try{return o(e)}catch{return e}}function BC(e){try{return s(e).isDirectory()}catch{return!1}}function VC(e){let t=zC(e);return BC(t)?{dir:t,name:null,leaf:!0}:Nx(t)}const HC=e=>`${e.dir}\0${e.name??``}`;var UC=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:VC(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=VC(e);if(t.watcher!==null&&HC(n)===HC(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=l.basename(r);try{return c(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},WC=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ne(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(te(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())te(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function GC(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function KC(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`?Bx(e):t===`number`?Vx(e):Hx(e)}function qC(e){return e===`number`?0:e===`boolean`?!1:``}var JC=class{inputMetas=new Map;lastErrors=new Map;watchFaults=new Map;watchMgr=new UC;ttlMgr=new WC;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new pC;abort=new AbortController;drawn=Lx.observable.box(F.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=Lx.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return TC(e)};engine=MS({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,zx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,X(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,kC(t,n.cwd,this.abort.signal),EC(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,AC(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,xC,t.default,n);case`regex`:return this.scalarPublisher(e,SC(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=jC(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,LS(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?Y:o,c=jC(s,CC,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(NS(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>IC(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=LC[t.field],r=t.varDefault===void 0?qC(n):KC(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,RC(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(OC);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(OC):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=GC(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,KC(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.watchFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.watchFaults.set(e,{timestamp:Date.now(),message:t}));this.cleanups.push(r);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Lx.reaction)(()=>{let t=NS(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Lx.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,KC(this.defaultEmptyValue,t))}catch{this.store.setBox(e,qC(t))}}defaultFor(e){try{return KC(this.defaultEmptyValue,e)}catch{return qC(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const YC={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[OC]:{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:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"effect.effective":{kind:`input`,path:`effect.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"shade.effective":{kind:`input`,path:`shade.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"transitions.effective":{kind:`input`,path:`transitions.effective`,type:`boolean`,default:!1},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,default:!0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},XC=`ne .tmux.pane ""`,ZC={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`,label:`🎨`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`,label:`▦`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`,label:`◐`},effect:{configKey:`effect`,sessionKey:`effect`,effectiveVar:`effect.effective`,label:`✨`},endcaps:{configKey:`endcaps`,sessionKey:`endcaps`,effectiveVar:`endcaps.effective`,label:`✦`},variation:{configKey:`variation`,sessionKey:`variation`,effectiveVar:`variation.effective`,label:`🎼`},shade:{configKey:`shade`,sessionKey:`shade`,effectiveVar:`shade.effective`,label:`🔆`},transitions:{configKey:`transitions`,sessionKey:`transitions`,effectiveVar:`transitions.effective`,label:`fade in/out`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`,label:`wrap`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`,label:`padding`},updateNotice:{configKey:`updateNotice`,sessionKey:`updateNotice`,effectiveVar:`updateNotice.effective`,label:`update notice`}},QC=Object.values(ZC),$C=[{configKey:`charset`,effectiveVar:`charset.effective`},{configKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`}],ew=new Set($C.map(e=>e.configKey)),tw=new Map([...QC,...$C].map(e=>[e.configKey,e.effectiveVar])),nw=new Map(QC.map(e=>[e.sessionKey,e.effectiveVar]));function rw(e){return Object.fromEntries(Object.keys(ZC).map(t=>[t,e(t)]))}const iw=new Map(Object.keys(ZC).map(e=>[ZC[e].sessionKey,e]));function aw(e,t,n){let r=new Set,i=e=>{for(let t of Cx(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of wu(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(OC);for(let t of Object.values(e.actions)){r.add(OC),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?nw.get(t.set):void 0,n=`persist`in t?tw.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function ow(e,t,n){let r=jx({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of aw(e,t,n.helpers)){if(Ax(a,r))continue;let e=YC[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}const sw=new Map;function cw(e){let t=uw(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 lw(e,t){return e===`bar`?t:cw(e)}function uw(e){let t=sw.get(e);if(t!==void 0)return t;let n=Qr(e);return n===null?null:(sw.set(e,n),n)}function dw(e,t){return fw(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>ui(e,t))}const fw=vs();function pw(e){let t=uw(e);return t===null?null:{kind:`decided`,name:e,value:t}}function mw(e,t,n){let r=pw(e);return r===null?(n(`${t} rendered "${kc}": "${e}" names no installed theme${Oc(e)}`),gw()):r}function hw(e,t,n){return Rc(e,t,n,gw(),pw)}function gw(){return{kind:`decided`,name:kc,value:cw(kc)}}const _w=new Map;function vw(e,t,n){_w.set(e,{permanent:!0,resolve:t,paletteOf:n})}vw(`themes`,()=>jc(),e=>cw(e));const yw=`placementThemes`;vw(yw,Mc,(e,t)=>lw(e,t.palette)),vw(`endcaps`,()=>Xc),vw(`variations`,()=>ol),vw(`shades`,()=>ll),vw(`charsets`,()=>tl),vw(`colorCompatibilities`,()=>il);function bw(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>dw(n.basePalette,e.styles[t])}],[`presets`,{members:Nb(e.presets)}]])}function xw(e){return[...new Set([..._w.keys(),...e.keys()])]}function Sw(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=_w.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(ww(e,t))}const Cw=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function ww(e,t){let n=Cw.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${xw(t).join(`, `)})`}function Tw(e,t,n){return e===`bool`?gl(t)!==null:`from`in e?Sw(e.from,n).members.includes(t):_l(t,e)!==null}function Ew(e,t){if(e===`bool`)return ml.join(` or `);if(`from`in e){let{members:n}=Sw(e.from,t),r=n.map(e=>JSON.stringify(e));if(n.length<=8)return`one of ${r.join(`, `)}`;let i=typeof e.from==`string`?` "${e.from}"`:``;return`one of the ${n.length}${i} names, such as ${r.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function Dw(e){return{label:e.label,domain:Ow(e.domain)}}function Ow(e){return e===`theme`?{from:yw}:e===`bool`||`min`in e?e:{from:e}}function kw(e,t,n,r,i){let a=Wd(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...ml]}},variables:{}};if(`from`in o)return Aw(a,t,r,i,o.from);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 Aw(e,t,n,r,i){let a={variable:r,key:r,member:n},o=Tb(r,n),s=`${n}.open`,c=Eb(r),l=`${c}.first`;return{kind:`picker`,template:`{{ "${e}" }} {{ carousel "${n}" 0 "${s}" }}`,actions:{[n]:{set:t,from:i},[o]:Qd(r,n),[c]:{set:c,int:!0},[l]:{set:c,to:`0`},[s]:{do:[o,l]}},variables:{[r]:Zd(r,Bd),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,template:`{{ picker "${n}" "${c}" false true true }}`}}}const jw=/^segments\.([^.]+)\.palette$/,Mw=/^presets\.(.+)\.root$/,Nw=/^presets\.(.+)\.globals\.([^.]+)$/,Pw=/^themeDefaults\.(.+)\.([^.]+)$/;function Fw(e){return`presets.${e}.root`}function Iw(e,t){return`themeDefaults.${e}.${t}`}const Lw=e=>ku.includes(e);function Rw(e,t){return`presets.${e}.globals.${t}`}function zw(e){if(jf(e))return{scope:`globals`,field:e};let t=jw.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Nw.exec(e);if(n&&xf(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=Pw.exec(e);if(r&&Lw(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Mw.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function Bw(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 Vw=`open`;function Hw(e,t,n,r){let i={variable:e,key:e,member:Vw};return r.variables[e]=Zd(e,Bd),r.actions[e]=Qd(e,Vw),r.segments[e]={template:Jd(e,`(?)`,`✕`),...Uw(n)},Gd(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 Uw(e){let[t,...n]=e;return t===void 0?{}:{when:Kd(t,...n)}}const Ww=`none`;function Gw(e){return yr(e,`background`)}var Kw=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function qw(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=Jw(n,i),l=c!==Ww,u=l?c===void 0?o:Yw(a,c,`bg`):Gw(a);e.bg=u;let d=Jw(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:nc(a,e,t))(u):void 0:Yw(a,d,`fg`);return new H({...l&&{bgcolor:L.fromRgba(u)},...f!==void 0&&{color:L.fromRgba(f)}})}function Jw(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Yw(e,t,n){try{return yr(e,t)}catch(e){throw e instanceof vr?new Kw(t,n,e.message):e}}const Xw={help:[`-h`,`--help`],version:[`-V`,`--version`]},Zw=[`✚ inserts`,`✖ removes`,`⚙️ configures`,`↺ resets layout`],Qw=`
93
93
  cc-candybar - Beautiful powerline statusline for Claude Code
94
94
 
95
95
  Usage: cc-candybar [options]
96
96
 
97
97
  Standalone Commands:
98
- ${Yw.help.join(`, `).padEnd(25)}Show this help
99
- ${Yw.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
98
+ ${Xw.help.join(`, `).padEnd(25)}Show this help
99
+ ${Xw.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
100
100
 
101
101
  Debugging:
102
102
  CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
@@ -119,7 +119,7 @@ Configuration:
119
119
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
120
120
 
121
121
  Anywhere the bar shows (?), clicking it reveals these same instructions
122
- in place. In edit mode: ${Xw.join(`, `)}.
122
+ in place. In edit mode: ${Zw.join(`, `)}.
123
123
 
124
124
  Subcommands:
125
125
  install One-shot setup: stages the runtime (native render
@@ -160,28 +160,28 @@ Config tooling:
160
160
  config [--json] The effective merged config. (All three query the
161
161
  running daemon; none spawn one.)
162
162
 
163
- `,Qw=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,$w={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function eT(e){let t=e[$w.socket]??``,n=e[$w.pane]??``;if(t===``||n===``)return null;let r=e[$w.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}function tT(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const nT=$w.truecolor,rT={name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettings: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`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[nT];return typeof n==`string`&&n!==``?{ok:!1,reason:`${nT} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings`,path:[`env`,nT],value:`1`}}}}}},iT={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},aT={name:`config`,label:`config`,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
164
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return tT([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${iT[e]}`)])}}},oT="re-run `cc-candybar install`";function sT(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:// — ${oT}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${oT}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${oT}`)}const cT=[aT,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${oT}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${oT}`};case`lost`:return tT([...sT(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}},rT,{name:`effectRefresh`,label:`effect refresh`,probe:({effect:e,placementEffects:t,transitions:n,claudeSettings:r})=>{let i=[...e.kind===`decided`?e.value===`none`?[]:[`the bar wears the ${e.name} effect`]:[`a globals.effect rule can give the bar an effect`],...t.map(({placement:e,effect:t})=>`${e} wears the ${t} effect`),...n?[`placements fade in as they appear`]:[]];if(i.length===0)return{ok:!0};let a=i.join(` and `),{path:o,statusLine:s}=r;switch(s.kind){case`absent`:return{ok:!1,reason:`${a}, and ${o} sets no statusLine — set "refreshInterval": 1 beside the statusLine command that runs the bar`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${o} sets statusLine to ${JSON.stringify(s.value)}, not a statusLine object — re-run \`cc-candybar install\` to write one`};case`present`:break}let c=s.refreshInterval;return c===1?{ok:!0}:{ok:!1,reason:c===void 0?`${a}, but Claude Code redraws it only on events`:typeof c==`number`&&c>1?`${a}, but Claude Code redraws it only every ${c} s`:`${a}, but statusLine.refreshInterval is ${JSON.stringify(c)}, not a number of seconds Claude Code accepts (its minimum is 1)`,fix:{kind:`claude-settings`,path:[`statusLine`,`refreshInterval`],value:1}}}}];function lT(e){return cT.map(t=>({check:t,verdict:t.probe(e)}))}function uT(e){return cT.find(t=>t.name===e)}const dT=`${wp}doctor.`;function fT(e){let t=`${dT}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function pT(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function mT(e){return e.flatMap(({check:e,verdict:t})=>{let n=fT(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:pl}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:pT(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?pl:fl}]})}const hT={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function gT(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(hT).map(([t,n])=>[`${e}${t}`,n]))}}const _T=`armed`,vT=`disarmed`,yT=`.armed`,bT=e=>e.endsWith(yT);function xT(e,t,n){let r=`${e}${yT}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${_T}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:_T},[a]:{set:r,to:vT},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:vT}},disarm:a}}const ST=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function CT(e){return typeof e==`string`&&ST.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 wT(e){let t=CT(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const TT=[`/compact`,`/model`],ET=`/clear`;function DT(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=xT(`${e}clear`,{arm:ET,confirm:`${ET} ✓ confirm`},[n]);return{template:TT.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${YC} }}`,actions:{...Object.fromEntries(TT.map(e=>[t(e),{slash:wT(e)}])),...r.actions,[n]:{slash:wT(ET)}},variables:r.variables,disarm:r.disarm}}function OT(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:l.resolve(t,n)}function kT(e){return e??l.join(h.homedir(),`.claude`)}function AT(e){return l.join(e,`settings.json`)}function jT(e){return l.join(e,`plugins`,`installed_plugins.json`)}function MT(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function NT(e){let t;try{let n=MT(e);if(/^\s*$/.test(n))return{};t=Rl.parse(n)}catch(t){throw Error(`cannot read ${e}: ${FT(t)}`,{cause:t})}if(!PT(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const PT=e=>typeof e==`object`&&!!e&&!Array.isArray(e),FT=e=>e instanceof Error?e.message:String(e),IT=Array.from({length:10},(e,t)=>(t+1)*1e5),LT=IT[0],RT=IT[IT.length-1];function zT(e){let t;try{t=NT(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=LT&&n<=RT?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${LT}–${RT} tokens)`)}function BT(e,t){let n=Math.min(t??RT,RT),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:IT.filter(e=>e<r).at(-1)??0,higher:IT.find(e=>e>r&&e<=n)??0}}function VT(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${YC} }}{{ 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:wT(`/autocompact auto`)},...Object.fromEntries(IT.map(t=>[`${e}${t}`,{slash:wT(`/autocompact ${t}`)}]))}}}const HT=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 }}`,UT=`${wp}menu`,WT=`open`,GT=`${wp}edit`,KT=`${wp}toolbar`,qT=gT(wp),JT=`${wp}commands`,YT=DT(`${JT}.`),XT=`${wp}autocompact`,ZT=VT(`${XT}.`,HT),QT=e=>({kind:`segment`,name:e}),$T=`${wp}tab`,eE=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],tE=e=>`${$T}.${e}`,nE=e=>`${tE(e)}.toggle`,rE=e=>({variable:$T,key:$T,member:e}),iE=`${wp}save`,aE=`${wp}preset.save`,oE=`${wp}preset.delete`,sE=`${wp}themeDefault.save`,cE=`${wp}themeDefault.differs`,lE=`${wp}themeDefault.theme`,uE={when:`{{ .${cE} }}`,template:`{{ action "${sE}" (printf "⤓ default for %s" .${lE}) }}`},dE=`${wp}resetAll`,fE=`${UT}.toggle`,pE={variable:UT,key:UT,member:WT},mE=`${wp}undo`,hE=`${wp}back`,gE=`${hE}.step`,_E=`${wp}navigation.back`,vE=hE,yE={template:`{{ if gt .${_E} 0 }}{{ action "${hE}" "◁" }}{{ else }}{{ fg (${Qw}) "◁" }}{{ end }}`},bE=`${wp}redo`,xE=`${wp}doctor`,SE=`${xE}.run`,CE=e=>`${xE}.fix.${e}`,wE=e=>`${xE}.${e}`,TE=Cb(`${wp}pickers`),EE=[{template:`{{ themePreview }}`}],DE={template:`{{ layoutPreview }}`},OE={preset:[DE,{when:`{{ not .preset.bundled }}`,template:`{{ action "${oE}" (printf "🗑 delete %s" .${XC.preset.effectiveVar}) }}`}],theme:EE,style:EE,variation:[DE],shade:[DE]},kE=e=>`${wp}${e}`,AE=e=>`${wp}apply.${e}`,jE=e=>`${wp}reset.${e}`,ME=e=>`${wp}list.${e}`,NE=(e,t)=>`${ME(e)}.${t}`,PE=e=>`${wp}resettable.${e}`,FE=e=>e.length===0?`false`:`(or ${e.map(e=>`.${PE(e)}`).join(` `)})`,IE=Object.keys(XC).map(e=>{let t=XC[e],n=ff(t.configKey),r=Ow({label:t.label,domain:n},t.sessionKey,t.effectiveVar,AE(e),TE);return{...t,name:e,control:r,beneath:OE[e]??[]}}),LE={preset:`door`,theme:`look`,style:`look`,effect:`look`,variation:`look`,shade:`look`,endcaps:`look`,transitions:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},RE=e=>IE.filter(t=>LE[t.name]===e),zE=e=>RE(e).map(ZE);new Set(IE.flatMap(e=>[e.sessionKey,e.configKey]));const BE=xT(dE,{arm:`⟲`,confirm:`⟲ reset all?`},IE.map(e=>jE(e.name))),VE=[`unsaved`,`history.undo`,`history.redo`],HE=e=>`${wp}${e}`,UE=HE(`unsaved`),WE=(e,t)=>({body:t,shown:`(gt .${HE(e)} 0)`}),GE=[WE(`unsaved`,`{{ action "${iE}" (printf "💾 save %d" .${UE}) }}`),WE(`history.undo`,`{{ action "${mE}" "↶" }}`),WE(`history.redo`,`{{ action "${bE}" "↷" }}`),{body:BE.template,shown:`(or ${FE(IE.map(e=>e.name))} ${BE.armed})`}],KE={when:`{{ or ${GE.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+GE.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},qE=[{step:BE,place:`door`},{step:YT,place:`session`}],JE=e=>e.map(e=>e.step.disarm),YE=JE(qE),XE=JE(qE.filter(e=>e.place!==`door`));function ZE(e){let t=kE(e.name);return e.control.kind===`inline`?QT(t):Gd(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[QT(ME(e.name)),...e.beneath.map((t,n)=>QT(NE(e.name,n)))]},`drop`)}function QE(e){return e===UT}function $E(e){let t=QT(UT);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[$E(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function eD(e){return tD(e)>0?e:$E(e)}function tD(e){let t=0;for(let n of wu(e))n.kind===`segment`&&QE(n.name)&&(t+=1);return t}function nD(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&QE(e.name)||e.opens!==void 0&&nD(e.opens.body,!0):e.children.some(e=>nD(e,n))}const rD={session:{direction:`vertical`,content:[QT(KT),{kind:`container`,direction:`horizontal`,children:[QT(JT),QT(XT)]}],after:[]},look:{direction:`horizontal`,content:[],after:[QT(sE)]},layout:{direction:`horizontal`,content:[QT(aE),QT(GT)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[QT(xE),...cT.map(e=>QT(wE(e.name)))],after:[]}},iD=e=>({kind:`container`,direction:rD[e].direction,children:[...rD[e].content,...zE(e),...rD[e].after]});function aD(e){return e.kind===`segment`?QE(e.name)?Gd(e.name,pE,sD,`above`):e:lD(e)}function oD(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[QT(vE),...zE(`door`),QT(iE)]},{kind:`container`,direction:`horizontal`,children:eE.map(({member:e})=>Gd(tE(e),rE(e),iD(e),`drop`))}]}}const sD=oD();function cD(e){let t=new Map;for(let e of wu(sD))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${UT}.fold.${bp(t)}`;return e.actions[i]={set:t,to:r.default},i})}function lD(e){return{...e,children:e.children.map(e=>aD(e))}}function uD(e){let t={variables:{[UT]:Zd(UT,Bd)},actions:{[fE]:Qd(UT,WT),[SE]:{doctor:`run`},[GT]:{do:[...ex]},...qT.actions,...YT.actions,...ZT.actions,[iE]:{save:!0},[mE]:{undo:!0},[gE]:{back:!0},[hE]:{do:[gE,...YE]},[bE]:{redo:!0},[aE]:{preset:`save`},[sE]:{themeDefault:`save`},[oE]:{preset:`delete`,name:`{{ .${XC.preset.effectiveVar} }}`}},segments:{[UT]:{template:`{{ $door := ${Yd(UT,Xd(e),Xd(`✖`))} }}{{ if ${qd(pE)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[KT]:{template:qT.template},[JT]:{template:YT.template,when:YT.when},[XT]:{template:ZT.template,bg:ZT.bg,when:ZT.when},[vE]:yE,[iE]:KE,[sE]:uE,[aE]:{template:`{{ action "${aE}" "+ preset" }}`},[xE]:{template:`{{ action "${SE}" "🩺 doctor" }}`},[GT]:{template:`{{ action "${GT}" "✎ arrange" "✎ done" }}`}}};t.variables[cE]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[lE]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[_E]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of VE)t.variables[HE(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[$T]=Zd($T,`session`);for(let{member:e,label:n}of eE){t.actions[nE(e)]=Qd($T,e),t.actions[tE(e)]={do:[nE(e),...XE]};let r=FE(RE(e).map(e=>e.name)),i=`(ternary ${Xd(` •`)} "" ${r})`,a=e=>`(print ${Xd(e)} ${i})`;t.segments[tE(e)]={template:`{{ ${Yd(tE(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,YT.variables,BE.variables),fD(t),dD(t),t.actions[UT]={do:[fE,...YE,...cD(t)]},t}function dD(e){for(let t of cT){let n=fT(t.name),r=CE(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},e.segments[wE(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${fl}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function fD(e){for(let t of IE){Object.assign(e.actions,t.control.actions);let n=jE(t.name);e.actions[n]={reset:t.configKey},e.variables[PE(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${PE(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[kE(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[ME(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[NE(t.name,r)]=n})}Object.assign(e.actions,BE.actions)}function pD(e){let{variables:t,actions:n}=lx();Object.assign(e.variables,t),Object.assign(e.actions,n)}function mD(e){let t=uD(e.globals.menuGlyph??`🍫`);pD(t);let n={...e.presets},r=[];for(let t of Mb(e.presets)){let{node:i}=Fb(e,t),a=aD(eD(i));r.push(a),n[t]={...Pb(e.presets,t),root:a}}let i=aw(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const hD=`${Cp}live`,gD=[`☐ live`,`☑ live`],_D=`${Cp}done`,vD=`${Cp}cancel`,yD=`${Cp}rewind`,bD=`${Cp}changes`,xD=`(gt .${bD} 0)`,SD=`(or ${xD} (gt .${UE} 0))`,CD={variable:hD,key:hD,member:`open`};function wD(e){return`${Cp}configuring.p${e}`}function TD(e){return`and ${qd(ix)} (not ${qd(CD)}) (ne .${wD(e)} "true")`}function ED(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Zb} "${Wd(e)}")`).join(` `)} false }}`}}function DD(e,t,n){return`{{ if ${TD(e)} }}${t}{{ else }}${n}{{ end }}`}const OD=`{{ and ${qd(ix)} .preset.customized }}`,kD=Ep;function AD(e){return new Map([...yw(e),...MD(e)])}const jD=`${Cp}addable`;function MD(e){return new Map([[jD,{members:Object.keys(e.segments).filter(e=>!kD(e)),library:{groups:vp.map(e=>({id:e,label:yp[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function ND(e,t,n){return n.segments[e]={template:t,when:ax,bg:Uw},{kind:`segment`,name:e}}function PD(e,t,n){let r=`${Cp}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${tc}`}) (action "${r}" "✖") }}`}function FD(e){return`{{ if ${qd(ix)} }}${e}{{ end }}`}function ID(e,t){return e.reduce((e,t)=>`{{ if and ${qd(ix)} ${qd(t)} }}true{{ else }}${e}{{ end }}`,t)}function LD(e){return e.flatMap(e=>[...wu(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function RD(e,t,n){return`${nx}${e}.${t}.${n}`}function zD(e,t,n,r){let i=bu(n),a=`${Cp}${e.presetIdent}`,o=rx(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=Cb(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Bd},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:Zb,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=RD(e.presetIdent,i,r),l=`${nx}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Vu(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=Ow(Ew(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};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Gd(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:Zb,key:Zb,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const BD=`${Cp}label:`;function VD(e){if(e.startsWith(BD)){let t=e.slice(BD.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function HD(e,t,n,r){let{artifacts:i}=n,a=bu(e),o=`${BD}${a}:${e.name}`;i.segments[o]={template:`{{ "${Wd(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Iu.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Gd(o,r.ref,r.body,`drop`,ID([r.ref],`{{ ${TD(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Iu.map(e=>[e,r.drafts[e]]))}}function UD(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Cp}${i}.insert.${t}`,s=`${Cp}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:jD,anchor:n,relation:r};let c=xb(o),l=Sb(s,o,void 0),u=Tb(l),d=wb(l,c);return a.variables[l]=Zd(l,Bd),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Qd(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${qd({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${tc}`}) $m }}{{ end }}`}}function WD(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!kD(e.name)),i=e=>WD(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Cu(o,i);if(kD(o.name)){n.push(s);continue}let c=bu(o),l=a===r?[UD(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=UD(t,u,c,`after`),f=PD(t,u,c),p=t.segments[o.name],m=zD(t,u,o,Lu(p)),h=FD(f),g=FD(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>ND(e.host,e.template,t.artifacts)),{...HD(o,p,t,m),lead:h,trail:g},{...s,when:DD(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},ND(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:ID(LD(n),DD(t.presetIdent,`true`,e.when))}}}function GD(e,t,n,r,i,a,o){let s=`${Cp}${t}.resetLayout`,c=`${Cp}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:OD},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},KD(e,o)]}}function KD(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),KD(n,t)]}:{...e,children:[...e.children,t]}}function qD(e,t,n,r,i,a){let{node:o}=Fb(e,t),s={presetIdent:bp(t),rootKey:Pw(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=WD(o,s);return n.variables[wD(s.presetIdent)]=ED(s.configured),GD(c,s.presetIdent,s.rootKey,n,r,i,a)}function JD(e){let t={variables:{},actions:{},segments:{}},n=Vw(`${Cp}help`,Xw,[ix],t);t.variables[hD]=Zd(hD,Bd),t.actions[hD]=Qd(hD,CD.member),t.segments[hD]={template:Jd(hD,...gD),when:ax};let r={kind:`segment`,name:hD},i=n;t.variables[bD]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[_D]={do:[iE,...ex]},t.segments[_D]={template:`{{ if ${SD} }}{{ action "${_D}" "✓ save" }}{{ else }}{{ action "${_D}" "✓ done" }}{{ end }}`,when:ax},t.actions[yD]={rewind:!0},t.actions[vD]={do:[yD,...ex]},t.segments[vD]={template:`{{ action "${vD}" "↩ cancel" }}`,when:`{{ and ${qd(ix)} ${xD} }}`};let a=[{kind:`segment`,name:_D},{kind:`segment`,name:vD}],o={...e.presets},s=[];for(let n of Mb(e.presets)){let c=qD(e,n,t,a,r,i);s.push(c),o[n]={...Pb(e.presets,n),root:c}}let c=aw(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const YD=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function XD(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function ZD(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function QD(e,t){if(t===void 0)return{};if(!Qu(t))return Q(e,`actions`,`actions must be an object, got ${$u(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=$D(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function $D(e,t,n){if(!Qu(n))return Q(e,t,`${t} must be an action object, got ${$u(n)}`),null;if(`persistWhen`in n)return Q(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=YD.filter(e=>e in n);return r.length===1?eO[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${YD.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const eO={set:(e,t,n)=>NO(e,t,n,`set`,kO),persist:(e,t,n)=>NO(e,t,n,`persist`,AO),copy:tO(`copy`),open:tO(`open`),reset:nO,undo:iO(`undo`),redo:iO(`redo`),back:iO(`back`),rewind:iO(`rewind`),save:iO(`save`),preset:aO,themeDefault:oO,doctor:sO,ceiling:cO,slash:lO,do:uO};function tO(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=qu(t,n,r,e);return i===null?null:{[e]:i}}}function nO(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=dO(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 rO={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 iO(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${rO[e]}), got ${K(r[e])}`),null)}}function aO(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=qu(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function oO(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Q(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}function sO(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||uT(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${cT.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function cO(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function lO(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=CT(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function uO(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${K(r)}`),null):{do:r}}function dO(e,t,n,r,i,a){let o=qu(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const fO={set:`the SessionState key to write`,persist:`the config globals field to write`};function pO(e,t,n,r){let i=fO[r],a=dO(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 mO(e){return e===`set`?`set-state`:`set-config`}const hO={to:PO(`set`)},gO={to:PO(`persist`)},_O={from:FO(`set`)},vO={from:FO(`persist`)},yO={min:BO(),max:BO(),by:BO()},bO={int:LO()},xO={cycle:IO(`set`)},SO={cycle:IO(`persist`)},CO={removeSegment:RO(`removeSegment`)},wO={insertSegment:RO(`insertSegment`),anchor:RO(`anchor`),relation:zO()},TO={insertSegmentFrom:FO(`persist`),anchor:RO(`anchor`),relation:zO()},EO={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},DO={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function OO(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>nd(e,t,n,r),c=bd(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?ud(s,...n):s}}const kO=[OO(`set`,hO),OO(`set`,_O),OO(`set`,yO,[EO,DO]),OO(`set`,bO),OO(`set`,xO)],AO=[OO(`persist`,gO),OO(`persist`,vO),OO(`persist`,yO,[EO,DO]),OO(`persist`,SO),OO(`persist`,CO),OO(`persist`,wO,[],[`insertSegment`]),OO(`persist`,TO,[],[`insertSegmentFrom`])];function jO(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 MO(e){let t=jO(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 NO(e,t,n,r,i){let a=pO(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${MO(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)||Q(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 PO(e){let t=mO(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>dO(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 FO(e){let t=mO(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function IO(e){let t=mO(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${$u(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function LO(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function RO(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=qu(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 zO(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function BO(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function VO(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const HO={noun:`style key`,fields:{hueShift:md(),chromaScale:md({min:0}),lightnessScale:md(),lightnessShift:md()}};function UO(e,t){if(!Qu(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${$u(t)}`,line:G(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:G(e.source,[`styles`,r])});continue}if($c(r)){e.issues.push({path:`styles.${r}`,message:VO(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=ed(e,HO,`styles.${r}`,i);t!==null&&(n[r]={...sr,...t})}return n}const WO={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:gm(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Of(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Df(e,`${t}.${n}`,r[n])}}};function GO(e,t){if(!Qu(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${$u(t)}`,line:G(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:G(e.source,[`presets`,r])});continue}let t=ed(e,WO,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function KO(e,t){if(t===void 0)return{};if(!Qu(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${$u(t)}`,line:G(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 ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const qO=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 JO(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 YO(e){let t=qO.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${JO(t)}`}function XO(e){let t=qO.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${JO(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function ZO(e,t){let n=new Map;for(let e of Object.keys(t)){let t=bp(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:G(e.source,[`presets`])})}function QO(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Lc(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:$c(i)?VO(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(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:G(e.source,[`globals`,`preset`])}),ZO(e,t.presets),xk(e,t);let i=Ax(t);for(let t of i.names)t!==`settings`&&!t.startsWith(tk)||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:G(e.source,[`variables`,t])});let a=(t,n,r)=>{tD(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${UT}" ${tD(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),nD(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${UT}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of wu(t)){if(e.kind!==`segment`)continue;let t=bu(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=Su(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||yu[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of Nd(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(pk(e,`${o}.when`,a.when,i,{line:n}),fk(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(QE(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${UT}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${UT}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${Ap(a.name)}`,line:n}),lk(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,jd(t.root)]]);for(let e of Mb(t.presets)){let{node:n,path:r}=Fb(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,G(e.source,t.split(`.`)));bk(e,t,i,()=>!0)}const $O=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function ek(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!Mb(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Mb(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(`, `)})${Ap(i)}`,line:c})},p=new Set(xu(Fb(t,a).node)),m=(r,i)=>{!kp.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${Ap(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 tk=`settings.`;function nk(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>tk+e)])}}function rk(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=ok(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of zu(n,ak(n)))i(e,`the defaults do not stand together: ${t}`)}function ik(e){return ok(e).length>0||zu(e,ak(e)).length>0}function ak(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function ok(e){let t=t=>Ru(sk(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Ru(sk(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${ck(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 sk(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function ck(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Ru(n)!==void 0).map(([e])=>e)}function lk(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=Lu(a),s=`${r}: placement "${bu(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(`, `)})`:Bu(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Oc(a):``}, but it must be ${Wu(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])=>Bu(o[e],t))||ik(o)))for(let{message:t}of zu(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function uk(e,t,n,r,i){n.kind===`template`&&pk(e,`${t}.template`,n.template,r,{segCtx:i}),Mu(n)&&n.cache&&`key`in n.cache&&pk(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function dk(e,t,n,r,i){if(Mu(n)&&n.cache&&`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:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function fk(e,t,n,r){try{Yb.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function pk(e,t,n,r,i){for(let[a,o]of Sx(n,r.helpers)){if(kx(a,r))continue;if(a.startsWith(tk)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){mk(e,o,`Template references unknown variable ".${a}"${XO(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&kx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:XO(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function mk(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function hk(e,t,n,r,i){let a=n.set,o=ff(XC[r].configKey),s=`${a} takes ${Tw(o,i)}`;if(`min`in n&&(o===`bool`||`from`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:G(e.source,[`actions`,t,`min`])});return}let c=vk(n,i);if(c===_k){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:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!ww(o,e.value,i));if(l.length!==0){if(a===XC.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>$c(e.value)))){let r=XC.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:VO(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(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:G(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<=gk?r.join(`, `):`${r.slice(0,gk).join(`, `)} and ${r.length-gk} 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:G(e.source,[`actions`,t,n])})}}}const gk=3,_k=Symbol(`any integer`);function vk(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?xw(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)}]:_k}function yk(e,t){return Object.entries(e).filter(([e])=>t(e))}function bk(e,t,n,r){let i=AD(t),a=bw(i);for(let[n,o]of yk(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 ${Cw(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;$C.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:G(e.source,[`actions`,n,`set`])});let s=rw.get(o.set);s!==void 0&&hk(e,n,o,s,i)}for(let[n,i]of yk(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&&ZD(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:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of yk(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=Rw(r);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a config globals field (have: ${Mf().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`,line:G(e.source,[`actions`,n,a])});continue}let s=$O.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:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){ek(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Mb(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: ${Mb(t.presets).join(`, `)})`,line:G(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${Oc(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(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(`, `)})${Ap(o.segment)}`,line:G(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:G(e.source,[`actions`,n,a])})}}for(let[i,a]of yk(t.variables,r)){uk(e,`variables.${i}`,a,n);let t=YO(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of yk(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))uk(e,`segments.${i}.vars.${t}`,r,n,i);let r=Lu(a);rk(e,i,r);let o=nk(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){pk(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of Ex(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu or carousel)`:``;if(o!==null){mk(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,i,n])})}}}}for(let[i,a]of yk(t.variables,r))dk(e,`variables.${i}`,a,n);for(let[i,a]of yk(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))dk(e,`segments.${i}.vars.${t}`,r,n,i)}function xk(e,t){let n=new Set;for(let r of Mb(t.presets)){let i=Ib(t,r),a=[{},t.editGlobals];for(let o of a){let a=o.charset??i.charset??`unicode`,s=o.default_separator??i.default_separator;if(a!==`ascii`||nl(s??``))continue;let c=o.default_separator===void 0?Pb(t.presets,r).globals?.default_separator===void 0?[`globals`]:[`presets`,r,`globals`]:[`editGlobals`],l=[...c,`default_separator`].join(`.`);n.has(l)||(n.add(l),e.issues.push({path:l,message:`${l} ${JSON.stringify(s)} is not ASCII, but charset is "ascii" — under ascii a joiner draws only ASCII; write an ASCII separator or set charset: "unicode"`,line:G(e.source,[...c,`default_separator`])}))}}}function Sk(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=Ck(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:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function Ck(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of Sx(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Mu(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const wk=[`json5`,`json`];function Tk(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Ek(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function Dk(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?wk.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...wk.map(e=>l.join(r,`.cc-candybar.${e}`)),...wk.map(e=>`${Ok()}.${e}`)])]}function Ok(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function kk(e,t,n){let i=[],a=new Map;for(let o of Dk(e,t,n)){let e=Tk(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:Ak(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function Ak(e){let t=Ok();return e.find(e=>wk.some(n=>e===`${t}.${n}`))??`${t}.${wk[0]}`}function jk(e,t,n){let r=kk(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null}}function Mk(e){return Nk(e).join(`
165
- `)||null}function Nk(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 Pk(e,t){let n=Dk(e,t).filter(e=>Tk(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Fk(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const Ik=new Set([`data`,`segments`,`helpers`,`actions`]),Lk=`plugin.json5`,Rk=/^[a-z][a-z0-9_]*$/;function zk(e){let t=l.basename(l.dirname(e));return Rk.test(t)?t:void 0}const Bk=`plugins.`;function Vk(e){return`${Bk}${e}.data`}function Hk(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Uk(e)}}}function Uk(e){return e instanceof pu?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 Wk(e,t){return e.map(e=>l.resolve(l.dirname(t),Ek(e)))}function Gk(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=zk(n),s=(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,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${Lk}, and the folder's name is the plugin's: move this file to <dir>/<name>/${Lk} and list that`;return s(t,o===void 0?e.config:Jk(qk(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${Rk}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=qk(e.config,o),d=Hk(()=>{let a=r.readFileSync(n,`utf-8`),s=Id(eA(n,o,{source:a,json:at.default.parse(a)},t),u);return i(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={path:n,plugin:o,reason:d.reason};return s(d.reason,Jk(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function Kk(e){let t=`${Bk}${e}.`;return e=>e.startsWith(t)}function qk(e,t){let n=Kk(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 Jk(e,t,n){return{...e,variables:{...e.variables,[Vk(t)]:{kind:`dropped`,reason:Fk(n),definition:n.path}}}}function Yk(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Xk(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Yk)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:Fk(e)}));return t=>{let i=Yk(t);if(i===void 0)return[];let a=e.config.variables[Vk(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function Zk(e,t){let n=Mb(e.presets).flatMap(t=>[...wu(Fb(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,Qk(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Yk(t),r=n===void 0?void 0:e.variables[Vk(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>Ex(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Ox(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${Vk(Yk(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function Qk(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,$k(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function $k(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 eA(e,t,{source:n,json:r},{projectDir:i}){let a=[],o=()=>{throw new pu(e,a)};if(!Qu(r))return a.push({path:``,message:`a plugin definition must be an object, got ${$u(r)}`}),o();for(let e of Object.keys(r))Ik.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...Ik].join(`, `)}`});let s=rA(r.data,e,i,a);if(Qu(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(jc()),groups:[]},l=Wf(c,`data`,{[Vk(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))Qu(t)&&`vars`in t&&a.push({path:`segments.${e}.vars`,message:`a plugin segment may not declare "vars": a plugin's only source is its data file`});let u={variables:l,segments:nA(t,qp(c,r.segments,new Set)),helpers:nA(t,KO(c,r.helpers)),actions:nA(t,QD(c,r.actions))};for(let[e,t]of tA(u))try{Yb.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*tA(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function nA(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${Bk}${e}.${t}`,n]))}function rA(e,t,n,r){if(typeof e==`string`&&e!==``)return l.resolve(l.dirname(t),Ek(e));if(Qu(e)&&Object.keys(e).length===1&&typeof e.project==`string`&&e.project!==``){let t=e.project;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.sep)[0]===`..`){r.push({path:`data.project`,message:`data.project "${t}" must be a path inside the project, relative to its root (like ".lit/candybar.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.project`,message:`data is read from the session's project, and this load has none`});return}return l.resolve(n,t)}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { project: "<path>" } relative to the session's project`})}function iA(e){let t=(process.env.XDG_DATA_DIRS||aA()).split(`:`).filter(e=>e!==``),n=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`),r=[...[...t].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),l.join(n,`cc-candybar`,`plugins`),...e===null?[]:[l.join(e,`.cc-candybar`,`plugins`)]];return r.filter((e,t)=>r.lastIndexOf(e)===t)}function aA(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function oA(e){let t=iA(e),n=new Map,r=[],i=[];for(let e of t){let t=sA(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,Lk));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${Lk}: move this file to ${l.join(e,`<name>`,Lk)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function sA(e){try{let t=r.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()||cA(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 cA(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}function lA(e,t,n,i){return e===null?{...vA,config:Id(vA.raw,t)}:dA(e,r.readFileSync(e,`utf-8`),t,n,i)}const uA={projectDir:null,beneath:{dropped:[],rendering:new Map}};function dA(e,t,n,r,i){let a=xA(e,t,i,(t,a)=>{let o=Gk(Wk(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>gA(t,n,r,e,i)),s=Xk(o,r.beneath.dropped);return{inherited:new Set([...Kp(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=Zk(Id(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(Fk)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const fA=new WeakMap;function pA(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,mA(e)])]),a=fA.get(n)??new Map;fA.set(n,a);let o=String(t.projectDir),s=a.get(o);if(s?.key===i)return s.layer;let c=Gk(e,t,{config:n,rendering:new Map},(e,t,n)=>gA(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function mA(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function hA(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s=oA(i.projectDir),c=pA(s.definitions,i,t,o),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=dA(t,a(t),d.at(-1)?.config??u,{...i,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},o);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),p=e=>f.has(e.path),m=l.dropped.filter(p),h=l.dropped.filter(e=>!p(e));n.warned(m.map(Fk));let g={roots:s.roots,loaded:l.loaded,dropped:m,unreached:h,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},_=d.at(-1);if(_===void 0)return{layers:d,base:u,installed:g,config:yA(lA(null,u,uA),`<default>`,o)};try{return{layers:d,base:u,installed:g,config:yA(_,_.path,o)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),yA(e,e.path,o);throw n.entered(_.path),e}}function gA(e,t,n,r,i){if(n){yA(_A(e),r,i);return}let a=Kk(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(bk(s,e,Ax(e),a),Sk(s,e,a),o.length>0)throw new pu(r,o)}function _A(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const vA={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function yA({config:e,raw:t,source:n},r=`<config>`,i=new Set(jc())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(QO(o,e,t),Sk(o,e),a.length>0)throw new pu(r,a);let s=Jb(e,a);if(a.length>0)throw new pu(r,a);return JD(mD(s))}function bA(e,t,n=new Set(jc()),r=SA){return xA(e,t,n,()=>({inherited:r,layer:null})).raw}function xA(e,t,n,r){let i=CA(e,t),a=gu(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(jc()),groups:[]};if(!Qu(i))throw new pu(e,[{path:``,message:`Config root must be an object, got ${$u(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:EA({...c,issues:[]},i.plugins)??[],Qu(i.segments)?Object.keys(i.segments):[]),d=wA(c,i,l);if(s.length>0)throw new pu(e,s,o);return{raw:d,warnings:o,layer:u}}const SA=new Set;function CA(e,t){try{return at.default.parse(t)}catch(t){let n=t;throw new pu(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function wA(e,t,n){for(let n of Object.keys(t))TA.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...TA].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Ef(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Wf(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=qp(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.
163
+ `,$w=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,eT={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function tT(e){let t=e[eT.socket]??``,n=e[eT.pane]??``;if(t===``||n===``)return null;let r=e[eT.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}function nT(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const rT=eT.truecolor,iT={name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettings: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`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[rT];return typeof n==`string`&&n!==``?{ok:!1,reason:`${rT} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings`,path:[`env`,rT],value:`1`}}}}}},aT={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},oT={name:`config`,label:`config`,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
164
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return nT([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${aT[e]}`)])}}},sT="re-run `cc-candybar install`";function cT(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:// — ${sT}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${sT}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${sT}`)}const lT=[oT,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${sT}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${sT}`};case`lost`:return nT([...cT(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}},iT,{name:`effectRefresh`,label:`effect refresh`,probe:({effect:e,placementEffects:t,transitions:n,claudeSettings:r})=>{let i=[...e.kind===`decided`?e.value===`none`?[]:[`the bar wears the ${e.name} effect`]:[`a globals.effect rule can give the bar an effect`],...t.map(({placement:e,effect:t})=>`${e} wears the ${t} effect`),...n?[`placements fade in and dissolve out as they come and go`]:[]];if(i.length===0)return{ok:!0};let a=i.join(` and `),{path:o,statusLine:s}=r;switch(s.kind){case`absent`:return{ok:!1,reason:`${a}, and ${o} sets no statusLine — set "refreshInterval": 1 beside the statusLine command that runs the bar`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${o} sets statusLine to ${JSON.stringify(s.value)}, not a statusLine object — re-run \`cc-candybar install\` to write one`};case`present`:break}let c=s.refreshInterval;return c===1?{ok:!0}:{ok:!1,reason:c===void 0?`${a}, but Claude Code redraws it only on events`:typeof c==`number`&&c>1?`${a}, but Claude Code redraws it only every ${c} s`:`${a}, but statusLine.refreshInterval is ${JSON.stringify(c)}, not a number of seconds Claude Code accepts (its minimum is 1)`,fix:{kind:`claude-settings`,path:[`statusLine`,`refreshInterval`],value:1}}}}];function uT(e){return lT.map(t=>({check:t,verdict:t.probe(e)}))}function dT(e){return lT.find(t=>t.name===e)}const fT=`${wp}doctor.`;function pT(e){let t=`${fT}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function mT(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function hT(e){return e.flatMap(({check:e,verdict:t})=>{let n=pT(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:pl}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:mT(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?pl:fl}]})}const gT={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function _T(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(gT).map(([t,n])=>[`${e}${t}`,n]))}}const vT=`armed`,yT=`disarmed`,bT=`.armed`,xT=e=>e.endsWith(bT);function ST(e,t,n){let r=`${e}${bT}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${vT}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:vT},[a]:{set:r,to:yT},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:yT}},disarm:a}}const CT=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function wT(e){return typeof e==`string`&&CT.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 TT(e){let t=wT(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const ET=[`/compact`,`/model`],DT=`/clear`;function OT(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=ST(`${e}clear`,{arm:DT,confirm:`${DT} ✓ confirm`},[n]);return{template:ET.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${XC} }}`,actions:{...Object.fromEntries(ET.map(e=>[t(e),{slash:TT(e)}])),...r.actions,[n]:{slash:TT(DT)}},variables:r.variables,disarm:r.disarm}}function kT(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:l.resolve(t,n)}function AT(e){return e??l.join(h.homedir(),`.claude`)}function jT(e){return l.join(e,`settings.json`)}function MT(e){return l.join(e,`plugins`,`installed_plugins.json`)}function NT(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function PT(e){let t;try{let n=NT(e);if(/^\s*$/.test(n))return{};t=Rl.parse(n)}catch(t){throw Error(`cannot read ${e}: ${IT(t)}`,{cause:t})}if(!FT(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const FT=e=>typeof e==`object`&&!!e&&!Array.isArray(e),IT=e=>e instanceof Error?e.message:String(e),LT=Array.from({length:10},(e,t)=>(t+1)*1e5),RT=LT[0],zT=LT[LT.length-1];function BT(e){let t;try{t=PT(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=RT&&n<=zT?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${RT}–${zT} tokens)`)}function VT(e,t){let n=Math.min(t??zT,zT),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:LT.filter(e=>e<r).at(-1)??0,higher:LT.find(e=>e>r&&e<=n)??0}}function HT(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${XC} }}{{ 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:TT(`/autocompact auto`)},...Object.fromEntries(LT.map(t=>[`${e}${t}`,{slash:TT(`/autocompact ${t}`)}]))}}}const UT=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 }}`,WT=`${wp}menu`,GT=`open`,KT=`${wp}edit`,qT=`${wp}toolbar`,JT=_T(wp),YT=`${wp}commands`,XT=OT(`${YT}.`),ZT=`${wp}autocompact`,QT=HT(`${ZT}.`,UT),$T=e=>({kind:`segment`,name:e}),eE=`${wp}tab`,tE=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],nE=e=>`${eE}.${e}`,rE=e=>`${nE(e)}.toggle`,iE=e=>({variable:eE,key:eE,member:e}),aE=`${wp}save`,oE=`${wp}preset.save`,sE=`${wp}preset.delete`,cE=`${wp}themeDefault.save`,lE=`${wp}themeDefault.differs`,uE=`${wp}themeDefault.theme`,dE={when:`{{ .${lE} }}`,template:`{{ action "${cE}" (printf "⤓ default for %s" .${uE}) }}`},fE=`${wp}resetAll`,pE=`${WT}.toggle`,mE={variable:WT,key:WT,member:GT},hE=`${wp}undo`,gE=`${wp}back`,_E=`${gE}.step`,vE=`${wp}navigation.back`,yE=gE,bE={template:`{{ if gt .${vE} 0 }}{{ action "${gE}" "◁" }}{{ else }}{{ fg (${$w}) "◁" }}{{ end }}`},xE=`${wp}redo`,SE=`${wp}doctor`,CE=`${SE}.run`,wE=e=>`${SE}.fix.${e}`,TE=e=>`${SE}.${e}`,EE=wb(`${wp}pickers`),DE=[{template:`{{ themePreview }}`}],OE={template:`{{ layoutPreview }}`},kE={preset:[OE,{when:`{{ not .preset.bundled }}`,template:`{{ action "${sE}" (printf "🗑 delete %s" .${ZC.preset.effectiveVar}) }}`}],theme:DE,style:DE,variation:[OE],shade:[OE]},AE=e=>`${wp}${e}`,jE=e=>`${wp}apply.${e}`,ME=e=>`${wp}reset.${e}`,NE=e=>`${wp}list.${e}`,PE=(e,t)=>`${NE(e)}.${t}`,FE=e=>`${wp}resettable.${e}`,IE=e=>e.length===0?`false`:`(or ${e.map(e=>`.${FE(e)}`).join(` `)})`,LE=Object.keys(ZC).map(e=>{let t=ZC[e],n=ff(t.configKey),r=kw({label:t.label,domain:n},t.sessionKey,t.effectiveVar,jE(e),EE);return{...t,name:e,control:r,beneath:kE[e]??[]}}),RE={preset:`door`,theme:`look`,style:`look`,effect:`look`,variation:`look`,shade:`look`,endcaps:`look`,transitions:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},zE=e=>LE.filter(t=>RE[t.name]===e),BE=e=>zE(e).map(QE);new Set(LE.flatMap(e=>[e.sessionKey,e.configKey]));const VE=ST(fE,{arm:`⟲`,confirm:`⟲ reset all?`},LE.map(e=>ME(e.name))),HE=[`unsaved`,`history.undo`,`history.redo`],UE=e=>`${wp}${e}`,WE=UE(`unsaved`),GE=(e,t)=>({body:t,shown:`(gt .${UE(e)} 0)`}),KE=[GE(`unsaved`,`{{ action "${aE}" (printf "💾 save %d" .${WE}) }}`),GE(`history.undo`,`{{ action "${hE}" "↶" }}`),GE(`history.redo`,`{{ action "${xE}" "↷" }}`),{body:VE.template,shown:`(or ${IE(LE.map(e=>e.name))} ${VE.armed})`}],qE={when:`{{ or ${KE.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+KE.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},JE=[{step:VE,place:`door`},{step:XT,place:`session`}],YE=e=>e.map(e=>e.step.disarm),XE=YE(JE),ZE=YE(JE.filter(e=>e.place!==`door`));function QE(e){let t=AE(e.name);return e.control.kind===`inline`?$T(t):Gd(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[$T(NE(e.name)),...e.beneath.map((t,n)=>$T(PE(e.name,n)))]},`drop`)}function $E(e){return e===WT}function eD(e){let t=$T(WT);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[eD(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function tD(e){return nD(e)>0?e:eD(e)}function nD(e){let t=0;for(let n of wu(e))n.kind===`segment`&&$E(n.name)&&(t+=1);return t}function rD(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&$E(e.name)||e.opens!==void 0&&rD(e.opens.body,!0):e.children.some(e=>rD(e,n))}const iD={session:{direction:`vertical`,content:[$T(qT),{kind:`container`,direction:`horizontal`,children:[$T(YT),$T(ZT)]}],after:[]},look:{direction:`horizontal`,content:[],after:[$T(cE)]},layout:{direction:`horizontal`,content:[$T(oE),$T(KT)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[$T(SE),...lT.map(e=>$T(TE(e.name)))],after:[]}},aD=e=>({kind:`container`,direction:iD[e].direction,children:[...iD[e].content,...BE(e),...iD[e].after]});function oD(e){return e.kind===`segment`?$E(e.name)?Gd(e.name,mE,cD,`above`):e:uD(e)}function sD(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[$T(yE),...BE(`door`),$T(aE)]},{kind:`container`,direction:`horizontal`,children:tE.map(({member:e})=>Gd(nE(e),iE(e),aD(e),`drop`))}]}}const cD=sD();function lD(e){let t=new Map;for(let e of wu(cD))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${WT}.fold.${bp(t)}`;return e.actions[i]={set:t,to:r.default},i})}function uD(e){return{...e,children:e.children.map(e=>oD(e))}}function dD(e){let t={variables:{[WT]:Zd(WT,Bd)},actions:{[pE]:Qd(WT,GT),[CE]:{doctor:`run`},[KT]:{do:[...tx]},...JT.actions,...XT.actions,...QT.actions,[aE]:{save:!0},[hE]:{undo:!0},[_E]:{back:!0},[gE]:{do:[_E,...XE]},[xE]:{redo:!0},[oE]:{preset:`save`},[cE]:{themeDefault:`save`},[sE]:{preset:`delete`,name:`{{ .${ZC.preset.effectiveVar} }}`}},segments:{[WT]:{template:`{{ $door := ${Yd(WT,Xd(e),Xd(`✖`))} }}{{ if ${qd(mE)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[qT]:{template:JT.template},[YT]:{template:XT.template,when:XT.when},[ZT]:{template:QT.template,bg:QT.bg,when:QT.when},[yE]:bE,[aE]:qE,[cE]:dE,[oE]:{template:`{{ action "${oE}" "+ preset" }}`},[SE]:{template:`{{ action "${CE}" "🩺 doctor" }}`},[KT]:{template:`{{ action "${KT}" "✎ arrange" "✎ done" }}`}}};t.variables[lE]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[uE]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[vE]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of HE)t.variables[UE(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[eE]=Zd(eE,`session`);for(let{member:e,label:n}of tE){t.actions[rE(e)]=Qd(eE,e),t.actions[nE(e)]={do:[rE(e),...ZE]};let r=IE(zE(e).map(e=>e.name)),i=`(ternary ${Xd(` •`)} "" ${r})`,a=e=>`(print ${Xd(e)} ${i})`;t.segments[nE(e)]={template:`{{ ${Yd(nE(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,XT.variables,VE.variables),pD(t),fD(t),t.actions[WT]={do:[pE,...XE,...lD(t)]},t}function fD(e){for(let t of lT){let n=pT(t.name),r=wE(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},e.segments[TE(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${fl}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function pD(e){for(let t of LE){Object.assign(e.actions,t.control.actions);let n=ME(t.name);e.actions[n]={reset:t.configKey},e.variables[FE(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${FE(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[AE(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[NE(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[PE(t.name,r)]=n})}Object.assign(e.actions,VE.actions)}function mD(e){let{variables:t,actions:n}=ux();Object.assign(e.variables,t),Object.assign(e.actions,n)}function hD(e){let t=dD(e.globals.menuGlyph??`🍫`);mD(t);let n={...e.presets},r=[];for(let t of Nb(e.presets)){let{node:i}=Ib(e,t),a=oD(tD(i));r.push(a),n[t]={...Fb(e.presets,t),root:a}}let i=ow(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const gD=`${Cp}live`,_D=[`☐ live`,`☑ live`],vD=`${Cp}done`,yD=`${Cp}cancel`,bD=`${Cp}rewind`,xD=`${Cp}changes`,SD=`(gt .${xD} 0)`,CD=`(or ${SD} (gt .${WE} 0))`,wD={variable:gD,key:gD,member:`open`};function TD(e){return`${Cp}configuring.p${e}`}function ED(e){return`and ${qd(ax)} (not ${qd(wD)}) (ne .${TD(e)} "true")`}function DD(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Qb} "${Wd(e)}")`).join(` `)} false }}`}}function OD(e,t,n){return`{{ if ${ED(e)} }}${t}{{ else }}${n}{{ end }}`}const kD=`{{ and ${qd(ax)} .preset.customized }}`,AD=Ep;function jD(e){return new Map([...bw(e),...ND(e)])}const MD=`${Cp}addable`;function ND(e){return new Map([[MD,{members:Object.keys(e.segments).filter(e=>!AD(e)),library:{groups:vp.map(e=>({id:e,label:yp[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function PD(e,t,n){return n.segments[e]={template:t,when:ox,bg:Ww},{kind:`segment`,name:e}}function FD(e,t,n){let r=`${Cp}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${tc}`}) (action "${r}" "✖") }}`}function ID(e){return`{{ if ${qd(ax)} }}${e}{{ end }}`}function LD(e,t){return e.reduce((e,t)=>`{{ if and ${qd(ax)} ${qd(t)} }}true{{ else }}${e}{{ end }}`,t)}function RD(e){return e.flatMap(e=>[...wu(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function zD(e,t,n){return`${rx}${e}.${t}.${n}`}function BD(e,t,n,r){let i=bu(n),a=`${Cp}${e.presetIdent}`,o=ix(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=wb(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Bd},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:Qb,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=zD(e.presetIdent,i,r),l=`${rx}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Vu(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=kw(Dw(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};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Gd(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:Qb,key:Qb,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const VD=`${Cp}label:`;function HD(e){if(e.startsWith(VD)){let t=e.slice(VD.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function UD(e,t,n,r){let{artifacts:i}=n,a=bu(e),o=`${VD}${a}:${e.name}`;i.segments[o]={template:`{{ "${Wd(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Iu.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Gd(o,r.ref,r.body,`drop`,LD([r.ref],`{{ ${ED(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Iu.map(e=>[e,r.drafts[e]]))}}function WD(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Cp}${i}.insert.${t}`,s=`${Cp}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:MD,anchor:n,relation:r};let c=Sb(o),l=Cb(s,o,void 0),u=Eb(l),d=Tb(l,c);return a.variables[l]=Zd(l,Bd),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Qd(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${qd({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${tc}`}) $m }}{{ end }}`}}function GD(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!AD(e.name)),i=e=>GD(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Cu(o,i);if(AD(o.name)){n.push(s);continue}let c=bu(o),l=a===r?[WD(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=WD(t,u,c,`after`),f=FD(t,u,c),p=t.segments[o.name],m=BD(t,u,o,Lu(p)),h=ID(f),g=ID(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>PD(e.host,e.template,t.artifacts)),{...UD(o,p,t,m),lead:h,trail:g},{...s,when:OD(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},PD(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:LD(RD(n),OD(t.presetIdent,`true`,e.when))}}}function KD(e,t,n,r,i,a,o){let s=`${Cp}${t}.resetLayout`,c=`${Cp}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:kD},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},qD(e,o)]}}function qD(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),qD(n,t)]}:{...e,children:[...e.children,t]}}function JD(e,t,n,r,i,a){let{node:o}=Ib(e,t),s={presetIdent:bp(t),rootKey:Fw(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=GD(o,s);return n.variables[TD(s.presetIdent)]=DD(s.configured),KD(c,s.presetIdent,s.rootKey,n,r,i,a)}function YD(e){let t={variables:{},actions:{},segments:{}},n=Hw(`${Cp}help`,Zw,[ax],t);t.variables[gD]=Zd(gD,Bd),t.actions[gD]=Qd(gD,wD.member),t.segments[gD]={template:Jd(gD,..._D),when:ox};let r={kind:`segment`,name:gD},i=n;t.variables[xD]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[vD]={do:[aE,...tx]},t.segments[vD]={template:`{{ if ${CD} }}{{ action "${vD}" "✓ save" }}{{ else }}{{ action "${vD}" "✓ done" }}{{ end }}`,when:ox},t.actions[bD]={rewind:!0},t.actions[yD]={do:[bD,...tx]},t.segments[yD]={template:`{{ action "${yD}" "↩ cancel" }}`,when:`{{ and ${qd(ax)} ${SD} }}`};let a=[{kind:`segment`,name:vD},{kind:`segment`,name:yD}],o={...e.presets},s=[];for(let n of Nb(e.presets)){let c=JD(e,n,t,a,r,i);s.push(c),o[n]={...Fb(e.presets,n),root:c}}let c=ow(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const XD=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function ZD(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function QD(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function $D(e,t){if(t===void 0)return{};if(!Qu(t))return Q(e,`actions`,`actions must be an object, got ${$u(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=eO(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function eO(e,t,n){if(!Qu(n))return Q(e,t,`${t} must be an action object, got ${$u(n)}`),null;if(`persistWhen`in n)return Q(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=XD.filter(e=>e in n);return r.length===1?tO[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${XD.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const tO={set:(e,t,n)=>PO(e,t,n,`set`,AO),persist:(e,t,n)=>PO(e,t,n,`persist`,jO),copy:nO(`copy`),open:nO(`open`),reset:rO,undo:aO(`undo`),redo:aO(`redo`),back:aO(`back`),rewind:aO(`rewind`),save:aO(`save`),preset:oO,themeDefault:sO,doctor:cO,ceiling:lO,slash:uO,do:dO};function nO(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=qu(t,n,r,e);return i===null?null:{[e]:i}}}function rO(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=fO(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 iO={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 aO(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${iO[e]}), got ${K(r[e])}`),null)}}function oO(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=qu(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function sO(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Q(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}function cO(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||dT(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${lT.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function lO(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function uO(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=wT(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function dO(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${K(r)}`),null):{do:r}}function fO(e,t,n,r,i,a){let o=qu(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const pO={set:`the SessionState key to write`,persist:`the config globals field to write`};function mO(e,t,n,r){let i=pO[r],a=fO(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 hO(e){return e===`set`?`set-state`:`set-config`}const gO={to:FO(`set`)},_O={to:FO(`persist`)},vO={from:IO(`set`)},yO={from:IO(`persist`)},bO={min:VO(),max:VO(),by:VO()},xO={int:RO()},SO={cycle:LO(`set`)},CO={cycle:LO(`persist`)},wO={removeSegment:zO(`removeSegment`)},TO={insertSegment:zO(`insertSegment`),anchor:zO(`anchor`),relation:BO()},EO={insertSegmentFrom:IO(`persist`),anchor:zO(`anchor`),relation:BO()},DO={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},OO={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function kO(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>nd(e,t,n,r),c=bd(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?ud(s,...n):s}}const AO=[kO(`set`,gO),kO(`set`,vO),kO(`set`,bO,[DO,OO]),kO(`set`,xO),kO(`set`,SO)],jO=[kO(`persist`,_O),kO(`persist`,yO),kO(`persist`,bO,[DO,OO]),kO(`persist`,CO),kO(`persist`,wO),kO(`persist`,TO,[],[`insertSegment`]),kO(`persist`,EO,[],[`insertSegmentFrom`])];function MO(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 NO(e){let t=MO(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 PO(e,t,n,r,i){let a=mO(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${NO(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)||Q(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 FO(e){let t=hO(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>fO(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 IO(e){let t=hO(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function LO(e){let t=hO(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${$u(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function RO(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function zO(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=qu(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 BO(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function VO(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function HO(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const UO={noun:`style key`,fields:{hueShift:md(),chromaScale:md({min:0}),lightnessScale:md(),lightnessShift:md()}};function WO(e,t){if(!Qu(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${$u(t)}`,line:G(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:G(e.source,[`styles`,r])});continue}if($c(r)){e.issues.push({path:`styles.${r}`,message:HO(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=ed(e,UO,`styles.${r}`,i);t!==null&&(n[r]={...sr,...t})}return n}const GO={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:_m(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Of(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Df(e,`${t}.${n}`,r[n])}}};function KO(e,t){if(!Qu(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${$u(t)}`,line:G(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:G(e.source,[`presets`,r])});continue}let t=ed(e,GO,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function qO(e,t){if(t===void 0)return{};if(!Qu(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${$u(t)}`,line:G(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 ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const JO=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 YO(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 XO(e){let t=JO.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${YO(t)}`}function ZO(e){let t=JO.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${YO(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function QO(e,t){let n=new Map;for(let e of Object.keys(t)){let t=bp(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:G(e.source,[`presets`])})}function $O(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Lc(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:$c(i)?HO(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(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:G(e.source,[`globals`,`preset`])}),QO(e,t.presets),Sk(e,t);let i=jx(t);for(let t of i.names)t!==`settings`&&!t.startsWith(nk)||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:G(e.source,[`variables`,t])});let a=(t,n,r)=>{nD(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${WT}" ${nD(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),rD(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${WT}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of wu(t)){if(e.kind!==`segment`)continue;let t=bu(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=Su(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||yu[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of Nd(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(mk(e,`${o}.when`,a.when,i,{line:n}),pk(e,`${o}.when`,a.when,n)),a.kind===`segment`){if($E(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${WT}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${WT}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${Ap(a.name)}`,line:n}),uk(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,jd(t.root)]]);for(let e of Nb(t.presets)){let{node:n,path:r}=Ib(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,G(e.source,t.split(`.`)));xk(e,t,i,()=>!0)}const ek=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function tk(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!Nb(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Nb(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(`, `)})${Ap(i)}`,line:c})},p=new Set(xu(Ib(t,a).node)),m=(r,i)=>{!kp.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${Ap(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 nk=`settings.`;function rk(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>nk+e)])}}function ik(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=sk(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of zu(n,ok(n)))i(e,`the defaults do not stand together: ${t}`)}function ak(e){return sk(e).length>0||zu(e,ok(e)).length>0}function ok(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function sk(e){let t=t=>Ru(ck(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Ru(ck(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${lk(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 ck(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function lk(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Ru(n)!==void 0).map(([e])=>e)}function uk(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=Lu(a),s=`${r}: placement "${bu(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(`, `)})`:Bu(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Oc(a):``}, but it must be ${Wu(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])=>Bu(o[e],t))||ak(o)))for(let{message:t}of zu(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function dk(e,t,n,r,i){n.kind===`template`&&mk(e,`${t}.template`,n.template,r,{segCtx:i}),Mu(n)&&n.cache&&`key`in n.cache&&mk(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function fk(e,t,n,r,i){if(Mu(n)&&n.cache&&`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:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function pk(e,t,n,r){try{Xb.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function mk(e,t,n,r,i){for(let[a,o]of Cx(n,r.helpers)){if(Ax(a,r))continue;if(a.startsWith(nk)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){hk(e,o,`Template references unknown variable ".${a}"${ZO(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Ax(n,r)?` (segment-local vars are namespaced — write ".${n}")`:ZO(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function hk(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function gk(e,t,n,r,i){let a=n.set,o=ff(ZC[r].configKey),s=`${a} takes ${Ew(o,i)}`;if(`min`in n&&(o===`bool`||`from`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:G(e.source,[`actions`,t,`min`])});return}let c=yk(n,i);if(c===vk){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:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!Tw(o,e.value,i));if(l.length!==0){if(a===ZC.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>$c(e.value)))){let r=ZC.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:HO(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(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:G(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<=_k?r.join(`, `):`${r.slice(0,_k).join(`, `)} and ${r.length-_k} 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:G(e.source,[`actions`,t,n])})}}}const _k=3,vk=Symbol(`any integer`);function yk(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?Sw(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)}]:vk}function bk(e,t){return Object.entries(e).filter(([e])=>t(e))}function xk(e,t,n,r){let i=jD(t),a=xw(i);for(let[n,o]of bk(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 ${ww(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;ew.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:G(e.source,[`actions`,n,`set`])});let s=iw.get(o.set);s!==void 0&&gk(e,n,o,s,i)}for(let[n,i]of bk(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&&QD(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:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of bk(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=zw(r);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a config globals field (have: ${Mf().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`,line:G(e.source,[`actions`,n,a])});continue}let s=ek.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:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){tk(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Nb(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: ${Nb(t.presets).join(`, `)})`,line:G(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${Oc(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(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(`, `)})${Ap(o.segment)}`,line:G(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:G(e.source,[`actions`,n,a])})}}for(let[i,a]of bk(t.variables,r)){dk(e,`variables.${i}`,a,n);let t=XO(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of bk(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))dk(e,`segments.${i}.vars.${t}`,r,n,i);let r=Lu(a);ik(e,i,r);let o=rk(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){mk(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of Dx(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu or carousel)`:``;if(o!==null){hk(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,i,n])})}}}}for(let[i,a]of bk(t.variables,r))fk(e,`variables.${i}`,a,n);for(let[i,a]of bk(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))fk(e,`segments.${i}.vars.${t}`,r,n,i)}function Sk(e,t){let n=new Set;for(let r of Nb(t.presets)){let i=Lb(t,r),a=[{},t.editGlobals];for(let o of a){let a=o.charset??i.charset??`unicode`,s=o.default_separator??i.default_separator;if(a!==`ascii`||nl(s??``))continue;let c=o.default_separator===void 0?Fb(t.presets,r).globals?.default_separator===void 0?[`globals`]:[`presets`,r,`globals`]:[`editGlobals`],l=[...c,`default_separator`].join(`.`);n.has(l)||(n.add(l),e.issues.push({path:l,message:`${l} ${JSON.stringify(s)} is not ASCII, but charset is "ascii" — under ascii a joiner draws only ASCII; write an ASCII separator or set charset: "unicode"`,line:G(e.source,[...c,`default_separator`])}))}}}function Ck(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=wk(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:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function wk(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of Cx(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Mu(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const Tk=[`json5`,`json`];function Ek(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Dk(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function Ok(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?Tk.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...Tk.map(e=>l.join(r,`.cc-candybar.${e}`)),...Tk.map(e=>`${kk()}.${e}`)])]}function kk(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function Ak(e,t,n){let i=[],a=new Map;for(let o of Ok(e,t,n)){let e=Ek(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:jk(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function jk(e){let t=kk();return e.find(e=>Tk.some(n=>e===`${t}.${n}`))??`${t}.${Tk[0]}`}function Mk(e,t,n){let r=Ak(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null}}function Nk(e){return Pk(e).join(`
165
+ `)||null}function Pk(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 Fk(e,t){let n=Ok(e,t).filter(e=>Ek(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Ik(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const Lk=new Set([`data`,`segments`,`helpers`,`actions`]),Rk=`plugin.json5`,zk=/^[a-z][a-z0-9_]*$/;function Bk(e){let t=l.basename(l.dirname(e));return zk.test(t)?t:void 0}const Vk=`plugins.`;function Hk(e){return`${Vk}${e}.data`}function Uk(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Wk(e)}}}function Wk(e){return e instanceof pu?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 Gk(e,t){return e.map(e=>l.resolve(l.dirname(t),Dk(e)))}function Kk(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=Bk(n),s=(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,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${Rk}, and the folder's name is the plugin's: move this file to <dir>/<name>/${Rk} and list that`;return s(t,o===void 0?e.config:Yk(Jk(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${zk}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=Jk(e.config,o),d=Uk(()=>{let a=r.readFileSync(n,`utf-8`),s=Id(tA(n,o,{source:a,json:at.default.parse(a)},t),u);return i(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={path:n,plugin:o,reason:d.reason};return s(d.reason,Yk(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function qk(e){let t=`${Vk}${e}.`;return e=>e.startsWith(t)}function Jk(e,t){let n=qk(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 Yk(e,t,n){return{...e,variables:{...e.variables,[Hk(t)]:{kind:`dropped`,reason:Ik(n),definition:n.path}}}}function Xk(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Zk(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Xk)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:Ik(e)}));return t=>{let i=Xk(t);if(i===void 0)return[];let a=e.config.variables[Hk(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function Qk(e,t){let n=Nb(e.presets).flatMap(t=>[...wu(Ib(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,$k(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Xk(t),r=n===void 0?void 0:e.variables[Hk(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>Dx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...kx(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${Hk(Xk(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function $k(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,eA(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function eA(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 tA(e,t,{source:n,json:r},{projectDir:i}){let a=[],o=()=>{throw new pu(e,a)};if(!Qu(r))return a.push({path:``,message:`a plugin definition must be an object, got ${$u(r)}`}),o();for(let e of Object.keys(r))Lk.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...Lk].join(`, `)}`});let s=iA(r.data,e,i,a);if(Qu(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(jc()),groups:[]},l=Wf(c,`data`,{[Hk(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))Qu(t)&&`vars`in t&&a.push({path:`segments.${e}.vars`,message:`a plugin segment may not declare "vars": a plugin's only source is its data file`});let u={variables:l,segments:rA(t,Jp(c,r.segments,new Set)),helpers:rA(t,qO(c,r.helpers)),actions:rA(t,$D(c,r.actions))};for(let[e,t]of nA(u))try{Xb.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*nA(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function rA(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${Vk}${e}.${t}`,n]))}function iA(e,t,n,r){if(typeof e==`string`&&e!==``)return l.resolve(l.dirname(t),Dk(e));if(Qu(e)&&Object.keys(e).length===1&&typeof e.project==`string`&&e.project!==``){let t=e.project;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.sep)[0]===`..`){r.push({path:`data.project`,message:`data.project "${t}" must be a path inside the project, relative to its root (like ".lit/candybar.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.project`,message:`data is read from the session's project, and this load has none`});return}return l.resolve(n,t)}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { project: "<path>" } relative to the session's project`})}function aA(e){let t=(process.env.XDG_DATA_DIRS||oA()).split(`:`).filter(e=>e!==``),n=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`),r=[...[...t].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),l.join(n,`cc-candybar`,`plugins`),...e===null?[]:[l.join(e,`.cc-candybar`,`plugins`)]];return r.filter((e,t)=>r.lastIndexOf(e)===t)}function oA(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function sA(e){let t=aA(e),n=new Map,r=[],i=[];for(let e of t){let t=cA(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,Rk));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${Rk}: move this file to ${l.join(e,`<name>`,Rk)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function cA(e){try{let t=r.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()||lA(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 lA(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}function uA(e,t,n,i){return e===null?{...yA,config:Id(yA.raw,t)}:fA(e,r.readFileSync(e,`utf-8`),t,n,i)}const dA={projectDir:null,beneath:{dropped:[],rendering:new Map}};function fA(e,t,n,r,i){let a=SA(e,t,i,(t,a)=>{let o=Kk(Gk(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>_A(t,n,r,e,i)),s=Zk(o,r.beneath.dropped);return{inherited:new Set([...qp(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=Qk(Id(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(Ik)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const pA=new WeakMap;function mA(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,hA(e)])]),a=pA.get(n)??new Map;pA.set(n,a);let o=String(t.projectDir),s=a.get(o);if(s?.key===i)return s.layer;let c=Kk(e,t,{config:n,rendering:new Map},(e,t,n)=>_A(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function hA(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function gA(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s=sA(i.projectDir),c=mA(s.definitions,i,t,o),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=fA(t,a(t),d.at(-1)?.config??u,{...i,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},o);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),p=e=>f.has(e.path),m=l.dropped.filter(p),h=l.dropped.filter(e=>!p(e));n.warned(m.map(Ik));let g={roots:s.roots,loaded:l.loaded,dropped:m,unreached:h,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},_=d.at(-1);if(_===void 0)return{layers:d,base:u,installed:g,config:bA(uA(null,u,dA),`<default>`,o)};try{return{layers:d,base:u,installed:g,config:bA(_,_.path,o)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),bA(e,e.path,o);throw n.entered(_.path),e}}function _A(e,t,n,r,i){if(n){bA(vA(e),r,i);return}let a=qk(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(xk(s,e,jx(e),a),Ck(s,e,a),o.length>0)throw new pu(r,o)}function vA(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const yA={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function bA({config:e,raw:t,source:n},r=`<config>`,i=new Set(jc())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if($O(o,e,t),Ck(o,e),a.length>0)throw new pu(r,a);let s=Yb(e,a);if(a.length>0)throw new pu(r,a);return YD(hD(s))}function xA(e,t,n=new Set(jc()),r=CA){return SA(e,t,n,()=>({inherited:r,layer:null})).raw}function SA(e,t,n,r){let i=wA(e,t),a=gu(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(jc()),groups:[]};if(!Qu(i))throw new pu(e,[{path:``,message:`Config root must be an object, got ${$u(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:DA({...c,issues:[]},i.plugins)??[],Qu(i.segments)?Object.keys(i.segments):[]),d=TA(c,i,l);if(s.length>0)throw new pu(e,s,o);return{raw:d,warnings:o,layer:u}}const CA=new Set;function wA(e,t){try{return at.default.parse(t)}catch(t){let n=t;throw new pu(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function TA(e,t,n){for(let n of Object.keys(t))EA.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...EA].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Ef(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Wf(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=Jp(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.
166
166
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
167
167
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
168
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=gm(e,`root`,t.root)),t.actions!==void 0&&(r.actions=QD(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=UO(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Tf(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=GO(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=kf(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=KO(e,t.helpers)),t.plugins!==void 0&&(r.plugins=EA(e,t.plugins)),wm(e,r),Kb(e,r),cx(e,r),Op(e,r,wp,`the global settings menu`),r}const TA=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function EA(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 ${$u(t)}`,line:G(e.source,[`plugins`])})}function DA(e){let t=NA(e.termCols),n=NA(e.termRows),r=PA(e.ssh),i=jA(e.tmux),a=AA(e.configEnv),o=kA(e.claudeConfigDir),s=OA(e.mementoEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s}}}function OA(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=$e.filter(e=>t[e]!==void 0);return n.every(e=>kA(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function kA(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function AA(e){return typeof e==`string`&&e!==``?Ek(e):void 0}function jA(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 MA=1e4;function NA(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>MA?MA:t}function PA(e){return typeof e==`boolean`?e:void 0}function FA(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var IA=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function LA(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function RA(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 IA(`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 IA(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function zA(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=RA(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(LA(t))})}async function BA(e,t,n){let r=null;try{r=await GA(ze(),t.connectMs);let i=await zA(r,{v:3,...e},t.budgetMs);return UA(e.kind,i,n)}catch(e){return WA(e)}finally{r&&r.destroy()}}function VA(e,t){return typeof e==`string`?e:t}function HA(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function UA(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=VA(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:HA(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function WA(e){if(e instanceof IA||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function GA(e,t){return new Promise((n,r)=>{let i=x.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function KA(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const qA=`1.127.1`,JA={connectMs:50,budgetMs:150},YA={connectMs:50,budgetMs:200};function XA(e){let t=e.output;return typeof t==`string`?t:void 0}function ZA(e,t,n,r){return BA({kind:`render`,hookData:e,args:t,cwd:n,...r},JA,XA)}function QA(e,t){return BA({kind:`click`,verb:e,value:t,clientVersion:qA},YA,XA)}function $A(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
169
- `)}function ej(e,t){return e===`darwin`?[tj(`footprint`,[`-p`,String(t)]),tj(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[nj(`/proc/self/smaps_rollup`),nj(`/proc/self/status`)]:[]}function tj(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=O({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${rj(n.stderr)}`}}}}function nj(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function rj(e){let t=e.split(`
170
- `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const ij=`CC_CANDYBAR_RSS_LIMIT_MB`;function aj(e){let t=e[ij];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ij} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function oj(e){return aj(e)*2}const sj=1024*1024;function cj(e){return aj(e)*sj}const lj={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function uj(e,t,n){let{prefix:r,suffix:i}=lj[t];return l.join(e,`${r}${n}${i}`)}function dj(e){for(let t of Object.keys(lj)){let{prefix:n,suffix:r}=lj[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function fj(e){let t=e.rssLimitBytes??512*sj,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return pj(e.log,`memory report`,()=>{let t=uj(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),pj(e.log,`heap snapshot`,()=>{let t=uj(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),pj(e.log,`artifact rotation`,()=>{hj(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function pj(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function mj(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=dj(t);if(n===null)return t;let{prefix:r,suffix:i}=lj[n];return t.slice(r.length,t.length-i.length)}function hj(e,t,n){let r=new Map;for(let t of e){let e=mj(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function gj(e,t,n={}){let i=Re();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>$A(ej(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>re.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>dj(e)!==null).map(e=>l.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function _j(e={}){if(Nj()!==null)return;let n=e.spawn??Pj,r=Aj();if(r.kind===`contended`){let e=yj();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),vj(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),vj(n);return}try{vj(n)}finally{Mj()}}function vj(e){Ej()&&bj(e)}function yj(){try{let e=r.statSync(Je());return Date.now()-e.mtimeMs}catch{return null}}function bj(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
171
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function xj(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Sj(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Cj(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function wj(e,n){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Tj(){try{r.unlinkSync(Xe())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Ej(){let e=Ye(),n=Xe(),r=Cj(n),i=xj(Dj(e),Sj(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),Oj(e),wj(n,Math.min(r+1,5)),!0)}function Dj(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Oj(e){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let kj=null;function Aj(){let e=Je();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return kj={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!jj(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function jj(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Mj(){if(!kj)return;let{fd:e,path:t}=kj;kj=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function Nj(){try{return r.mkdirSync(Re(),{recursive:!0}),null}catch(e){return`mkdir ${Re()}: ${e.message}`}}function Pj(){let e=t.execPath,n=t.argv[1];return n?Me({bin:e,args:[`--max-old-space-size=${oj(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Fj=`cc-candybar`,Ij=`dispatch`,Lj=`set-state`,Rj=`step-state`,zj=`copy`,Bj=`open-vscode`,Vj=`toolbar-toggle`,Hj=`show-config-error`,Uj=`show-config-warning`,Wj=`set-config`,Gj=`step-config`,Kj=`save`,qj=`save-preset`,Jj=`save-theme-default`,Yj=`delete-preset`,Xj=`reset-config`,Zj=`apply-layout-op`,Qj=`undo`,$j=`redo`,eM=`back`,tM=`rewind`,nM=`apply-update`,rM=`doctor-run`,iM=`doctor-fix`,aM=`doctor-probe`,oM=`ceiling`,sM=`slash`;function cM(e){return e.map(encodeURIComponent).join(`/`)}function lM(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function uM(e){return`${Fj}://${Ij}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${cM(e.args)}`)}`).join(`&`)}`}function dM(e){return new T(e).getAll(`e`).map(hM)}const fM=new Set([Lj,Xj]);function pM(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&mM(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function mM(e,t){if(e.verb!==t.verb||!fM.has(e.verb))return;let[n,r]=[hM(e.value),hM(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function hM(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const gM=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function _M(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function vM(e){return gM.test(e)?e:_M(e)}const yM=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function bM(e){let t=yM.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function xM(e){return e.join(`.`)}function SM([e,t,n],[r,i,a]){return e-r||t-i||n-a}const CM=`@promptctl/cc-candybar`;async function wM(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return X(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?bM(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function TM(e,t){let n=bM(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=SM(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function EM(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${xM(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${xM(t.installed)} is newer than the registry's latest release (${xM(t.latest)}): an unpublished build.\n`};case`stale`:{let n=xM(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${xM(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const DM=`CCCandybarURLHandler`,OM=[],kM={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function AM(e,t){return[e,...t].map(vM).join(` `)}function jM(){return l.join(h.homedir(),`Applications`,`${DM}.app`)}function MM(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function NM(){if(process.platform===`darwin`)return l.join(h.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`)}function PM(){return l.join(NM(),`bin`,`cc-candybar`)}function FM(){return l.join(NM(),`dist`,`index.mjs`)}function IM(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
172
- `)}function LM(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function RM(e){return l.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function zM(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:l.resolve(l.dirname(e),`..`,`dist`,`index.mjs`)}function BM(t){let n=kM[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:l.resolve(l.dirname(t),`..`,`bin`,`cc-candybar`)}}function VM(e,t){l.resolve(e)!==l.resolve(t)&&r.copyFileSync(e,t)}function HM(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${CM}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function UM(){let e=zM(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=BM(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(l.dirname(FM()),{recursive:!0}),r.mkdirSync(l.dirname(PM()),{recursive:!0}),VM(e,FM()),VM(t.sourcePath,PM()),r.chmodSync(PM(),493),r.rmSync(l.join(NM(),`url-handler.mjs`),{force:!0});let n=HM(PM());return process.stdout.write(`Staged cc-candybar v${qA} runtime at ${NM()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:PM(),distPath:FM(),entryKind:n}}function WM(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${Fj}</string>`,` </array>`,` </dict>`,`</array>`].join(`
173
- `)}]}function GM(e){let t=jM();r.mkdirSync(l.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=O({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,IM(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=l.join(t,`Contents`,`Info.plist`);for(let{key:e}of WM())O({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of WM()){let n=O({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${Fj}:// with Launch Services\n`);let a=O({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${DM}.app installed and registered.\n`),process.stdout.write(` Test: open '${Fj}://hello-world' && pbpaste\n`)}function KM(){MM(),GM(UM().distPath)}function qM(e,t=Fj){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:zj,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function JM(e){e||(process.stderr.write(`url-handle: missing URL argument.
174
- `),process.exit(1));let t;try{t=qM(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await QA(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(_j(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(YM(n)+`
175
- `),process.exit(1)}function YM(e){switch(e.cause){case`version_mismatch`:return`url-handle: daemon rejected click (version mismatch: client v${e.clientV} ≠ daemon v${e.daemonV})`;case`bad_request`:return`url-handle: daemon rejected click (bad request: ${e.message})`;case`render_failed`:return`url-handle: daemon rejected click (handler failed: ${e.message})`;case`malformed_response`:return`url-handle: daemon rejected click (malformed response: ${e.message})`}}function XM(){return`✓ install complete.
168
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=_m(e,`root`,t.root)),t.actions!==void 0&&(r.actions=$D(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=WO(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Tf(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=KO(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=kf(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=qO(e,t.helpers)),t.plugins!==void 0&&(r.plugins=DA(e,t.plugins)),Tm(e,r),qb(e,r),lx(e,r),Op(e,r,wp,`the global settings menu`),r}const EA=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function DA(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 ${$u(t)}`,line:G(e.source,[`plugins`])})}function OA(e){let t=PA(e.termCols),n=PA(e.termRows),r=FA(e.ssh),i=MA(e.tmux),a=jA(e.configEnv),o=AA(e.claudeConfigDir),s=kA(e.mementoEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s}}}function kA(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=$e.filter(e=>t[e]!==void 0);return n.every(e=>AA(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function AA(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function jA(e){return typeof e==`string`&&e!==``?Dk(e):void 0}function MA(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 NA=1e4;function PA(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>NA?NA:t}function FA(e){return typeof e==`boolean`?e:void 0}function IA(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var LA=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function RA(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function zA(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 LA(`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 LA(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function BA(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=zA(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(RA(t))})}async function VA(e,t,n){let r=null;try{r=await KA(ze(),t.connectMs);let i=await BA(r,{v:3,...e},t.budgetMs);return WA(e.kind,i,n)}catch(e){return GA(e)}finally{r&&r.destroy()}}function HA(e,t){return typeof e==`string`?e:t}function UA(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function WA(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=HA(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:UA(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function GA(e){if(e instanceof LA||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function KA(e,t){return new Promise((n,r)=>{let i=x.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function qA(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const JA=`1.128.0`,YA={connectMs:50,budgetMs:150},XA={connectMs:50,budgetMs:200};function ZA(e){let t=e.output;return typeof t==`string`?t:void 0}function QA(e,t,n,r){return VA({kind:`render`,hookData:e,args:t,cwd:n,...r},YA,ZA)}function $A(e,t){return VA({kind:`click`,verb:e,value:t,clientVersion:JA},XA,ZA)}function ej(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
169
+ `)}function tj(e,t){return e===`darwin`?[nj(`footprint`,[`-p`,String(t)]),nj(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[rj(`/proc/self/smaps_rollup`),rj(`/proc/self/status`)]:[]}function nj(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=O({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${ij(n.stderr)}`}}}}function rj(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function ij(e){let t=e.split(`
170
+ `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const aj=`CC_CANDYBAR_RSS_LIMIT_MB`;function oj(e){let t=e[aj];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${aj} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function sj(e){return oj(e)*2}const cj=1024*1024;function lj(e){return oj(e)*cj}const uj={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function dj(e,t,n){let{prefix:r,suffix:i}=uj[t];return l.join(e,`${r}${n}${i}`)}function fj(e){for(let t of Object.keys(uj)){let{prefix:n,suffix:r}=uj[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function pj(e){let t=e.rssLimitBytes??512*cj,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return mj(e.log,`memory report`,()=>{let t=dj(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),mj(e.log,`heap snapshot`,()=>{let t=dj(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),mj(e.log,`artifact rotation`,()=>{gj(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function mj(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function hj(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=fj(t);if(n===null)return t;let{prefix:r,suffix:i}=uj[n];return t.slice(r.length,t.length-i.length)}function gj(e,t,n){let r=new Map;for(let t of e){let e=hj(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function _j(e,t,n={}){let i=Re();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>ej(tj(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>re.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>fj(e)!==null).map(e=>l.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function vj(e={}){if(Pj()!==null)return;let n=e.spawn??Fj,r=jj();if(r.kind===`contended`){let e=bj();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),yj(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),yj(n);return}try{yj(n)}finally{Nj()}}function yj(e){Dj()&&xj(e)}function bj(){try{let e=r.statSync(Je());return Date.now()-e.mtimeMs}catch{return null}}function xj(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
171
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function Sj(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Cj(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function wj(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function Tj(e,n){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Ej(){try{r.unlinkSync(Xe())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Dj(){let e=Ye(),n=Xe(),r=wj(n),i=Sj(Oj(e),Cj(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),kj(e),Tj(n,Math.min(r+1,5)),!0)}function Oj(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function kj(e){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let Aj=null;function jj(){let e=Je();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return Aj={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!Mj(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function Mj(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Nj(){if(!Aj)return;let{fd:e,path:t}=Aj;Aj=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function Pj(){try{return r.mkdirSync(Re(),{recursive:!0}),null}catch(e){return`mkdir ${Re()}: ${e.message}`}}function Fj(){let e=t.execPath,n=t.argv[1];return n?Me({bin:e,args:[`--max-old-space-size=${sj(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Ij=`cc-candybar`,Lj=`dispatch`,Rj=`set-state`,zj=`step-state`,Bj=`copy`,Vj=`open-vscode`,Hj=`toolbar-toggle`,Uj=`show-config-error`,Wj=`show-config-warning`,Gj=`set-config`,Kj=`step-config`,qj=`save`,Jj=`save-preset`,Yj=`save-theme-default`,Xj=`delete-preset`,Zj=`reset-config`,Qj=`apply-layout-op`,$j=`undo`,eM=`redo`,tM=`back`,nM=`rewind`,rM=`apply-update`,iM=`doctor-run`,aM=`doctor-fix`,oM=`doctor-probe`,sM=`ceiling`,cM=`slash`;function lM(e){return e.map(encodeURIComponent).join(`/`)}function uM(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function dM(e){return`${Ij}://${Lj}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${lM(e.args)}`)}`).join(`&`)}`}function fM(e){return new T(e).getAll(`e`).map(gM)}const pM=new Set([Rj,Zj]);function mM(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&hM(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function hM(e,t){if(e.verb!==t.verb||!pM.has(e.verb))return;let[n,r]=[gM(e.value),gM(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function gM(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const _M=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function vM(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function yM(e){return _M.test(e)?e:vM(e)}const bM=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function xM(e){let t=bM.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function SM(e){return e.join(`.`)}function CM([e,t,n],[r,i,a]){return e-r||t-i||n-a}const wM=`@promptctl/cc-candybar`;async function TM(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return X(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?xM(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function EM(e,t){let n=xM(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=CM(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function DM(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${SM(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${SM(t.installed)} is newer than the registry's latest release (${SM(t.latest)}): an unpublished build.\n`};case`stale`:{let n=SM(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${SM(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const OM=`CCCandybarURLHandler`,kM=[],AM={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function jM(e,t){return[e,...t].map(yM).join(` `)}function MM(){return l.join(h.homedir(),`Applications`,`${OM}.app`)}function NM(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function PM(){if(process.platform===`darwin`)return l.join(h.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`)}function FM(){return l.join(PM(),`bin`,`cc-candybar`)}function IM(){return l.join(PM(),`dist`,`index.mjs`)}function LM(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
172
+ `)}function RM(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function zM(e){return l.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function BM(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:l.resolve(l.dirname(e),`..`,`dist`,`index.mjs`)}function VM(t){let n=AM[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:l.resolve(l.dirname(t),`..`,`bin`,`cc-candybar`)}}function HM(e,t){l.resolve(e)!==l.resolve(t)&&r.copyFileSync(e,t)}function UM(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${wM}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function WM(){let e=BM(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=VM(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(l.dirname(IM()),{recursive:!0}),r.mkdirSync(l.dirname(FM()),{recursive:!0}),HM(e,IM()),HM(t.sourcePath,FM()),r.chmodSync(FM(),493),r.rmSync(l.join(PM(),`url-handler.mjs`),{force:!0});let n=UM(FM());return process.stdout.write(`Staged cc-candybar v${JA} runtime at ${PM()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:FM(),distPath:IM(),entryKind:n}}function GM(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${Ij}</string>`,` </array>`,` </dict>`,`</array>`].join(`
173
+ `)}]}function KM(e){let t=MM();r.mkdirSync(l.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=O({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,LM(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=l.join(t,`Contents`,`Info.plist`);for(let{key:e}of GM())O({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of GM()){let n=O({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${Ij}:// with Launch Services\n`);let a=O({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${OM}.app installed and registered.\n`),process.stdout.write(` Test: open '${Ij}://hello-world' && pbpaste\n`)}function qM(){NM(),KM(WM().distPath)}function JM(e,t=Ij){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:Bj,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function YM(e){e||(process.stderr.write(`url-handle: missing URL argument.
174
+ `),process.exit(1));let t;try{t=JM(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await $A(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(vj(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(XM(n)+`
175
+ `),process.exit(1)}function XM(e){switch(e.cause){case`version_mismatch`:return`url-handle: daemon rejected click (version mismatch: client v${e.clientV} ≠ daemon v${e.daemonV})`;case`bad_request`:return`url-handle: daemon rejected click (bad request: ${e.message})`;case`render_failed`:return`url-handle: daemon rejected click (handler failed: ${e.message})`;case`malformed_response`:return`url-handle: daemon rejected click (malformed response: ${e.message})`}}function ZM(){return`✓ install complete.
176
176
  Restart Claude Code to pick up the new statusline.
177
- Tip: every bar carries a settings menu — click it (${Vd} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/shade/endcaps/wrap/padding controls.\n`}async function ZM(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...OM],i=UM();process.platform===`darwin`?GM(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
178
- `),QM(i.binPath,r,t),process.stdout.write(XM());let a=EM(CM,TM(qA,await wM(CM,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function QM(e,t,n,i){let a=i??AT(kT(OT(process.env,process.cwd())));r.mkdirSync(l.dirname(a),{recursive:!0});let o=NT(a).statusLine,s=PT(o)?o.command:void 0,c=[e,vM(e),_M(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||c.some(e=>s===e||s.startsWith(`${e} `)));if(s&&!u&&!n){process.stderr.write(`Skipping settings.json update: existing statusLine.command appears customized.\n Current: ${s}\n To overwrite, re-run with --force.\n`);return}let d=AM(e,t);Pe(a,(PT(o)?[[[`statusLine`,`type`],`command`],[[`statusLine`,`command`],d]]:[[[`statusLine`],{type:`command`,command:d}]]).reduce((e,[t,n])=>$l(e,t,JSON.stringify(n,null,2),Rl),MT(a))),process.stdout.write(`Updated ${a}\n`)}function $M(e,t){return e.kind===`owned`?t(e.pid,e.startTime)?{kind:`attach-and-exit`,reason:`live owner pid=${e.pid} holds the socket`}:{kind:`reclaim`,reason:`owner pid=${e.pid} is gone or recycled`}:e.kind===`absent`?{kind:`reclaim`,reason:`no lease — stale socket, no live owner`}:{kind:`reclaim`,reason:`unreadable lease (${e.detail}) — cannot prove a live owner`}}function eN(e){let t;try{t=r.readFileSync(e,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:`read failed: ${e.message}`}}let n;try{n=JSON.parse(t)}catch(e){return{kind:`unreadable`,detail:`bad JSON: ${e.message}`}}let i=n,a=i?.pid;if(typeof a!=`number`||!Number.isInteger(a)||a<=0)return{kind:`unreadable`,detail:`no valid pid (got ${JSON.stringify(a)})`};let o=i?.startTime;return o!=null&&typeof o!=`string`?{kind:`unreadable`,detail:`invalid startTime (got ${JSON.stringify(o)})`}:{kind:`owned`,pid:a,startTime:o??null}}function tN(e,n){let i=`${e}.${t.pid}.tmp`;try{return r.writeFileSync(i,JSON.stringify(n),{mode:384}),r.renameSync(i,e),null}catch(e){let t=e.message;try{r.unlinkSync(i)}catch(e){if(e.code!==`ENOENT`)return`${t}; also failed to remove temp ${i}: ${e.message}`}return t}}function nN(e,t){let n=eN(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function rN(e){try{let t=r.statSync(e);return{kind:`present`,identity:{dev:t.dev,ino:t.ino}}}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:e.message}}}function iN(e,t,n,r){let i=aN(e,t);return i===null?r.kind===`owned`?r.pid===n?{kind:`owned`}:{kind:`displaced`,reason:`lease reassigned (names pid=${r.pid}, we are pid=${n}) — a reclaimer overwrote it`}:{kind:`displaced`,reason:`lease not held (${r.kind}) — no longer the socket owner`}:{kind:`displaced`,reason:i}}function aN(e,t){return t.kind===`present`?t.identity.dev===e.dev&&t.identity.ino===e.ino?null:`socket replaced (bound dev=${e.dev} ino=${e.ino}, now dev=${t.identity.dev} ino=${t.identity.ino})`:t.kind===`absent`?`socket path gone (ENOENT) — unlinked by a reclaimer`:`socket path unreadable (${t.detail}) — cannot prove ownership`}function oN(e){let t=!1;function n(){let n=iN(e.bound,e.readIdentity(),e.myPid,e.readLease());return n.kind===`displaced`&&!t&&(t=!0,e.log(`warn`,`ownership self-check: ${n.reason}; shutting down`),e.shutdown(0)),n}function r(t=e.intervalMs??5e3){let r=setInterval(()=>{n().kind===`displaced`&&clearInterval(r)},t);return r.unref(),{disarm:()=>clearInterval(r)}}return{check:n,arm:r}}function sN(e,t=O){let n=t({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:2e3,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});if(n.ok){let e=n.stdout.trim();return e.length>0?{kind:`start`,token:e}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:n.reason===`spawn-error`?n.error??`ps spawn failed`:`ps ${n.reason} (exit ${n.exitCode})`}}function cN(e,t,n){if(t===null)return n.pidAlive(e);let r=n.readStartTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.pidAlive(e)}}function lN(e,t=sN){let n=t(e);return n.kind===`start`?n.token:null}const uN=`CC_CANDYBAR_PARENT_PID`;function dN(e){let t=e[uN];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${uN} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function fN(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??250);return n.unref(),{disarm:()=>clearInterval(n)}}function pN(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function mN(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function hN(e,t,n){return e?t>=n?{allow:!1,reason:`${t} live isolated daemons registered >= ceiling ${n}`}:{allow:!0,reason:`${t} live isolated daemons registered < ceiling ${n}`}:{allow:!0,reason:`canonical production socket — exempt (bind() already caps it to one)`}}function gN(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>l.join(e,t))}catch{return[]}}function _N(e){let t;try{t=r.readFileSync(e,`utf8`)}catch{return null}try{let e=JSON.parse(t),n=e?.pid;return typeof n!=`number`||!Number.isInteger(n)||n<=0?null:{pid:n,startTime:typeof e?.startTime==`string`?e.startTime:null}}catch{return null}}function vN(e,t,n){let r=0;for(let i of e)t(i.identity.pid,i.identity.startTime)?r++:n(i.path);return r}function yN(e){if(!e.isolated)return{decision:hN(!1,0,e.ceiling),registryPath:null};e.ensureDirSafe(e.registryDir);let t=[];for(let n of e.listFiles(e.registryDir)){let r=e.readEntry(n);r!==null&&r.pid!==e.pid&&t.push({path:n,identity:r})}let n=hN(!0,vN(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=l.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function bN(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function xN(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:qe(),ceiling:mN(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>cN(e,t,{readStartTime:sN,pidAlive:pN}),listFiles:gN,readEntry:_N,removeFile:e=>{try{r.unlinkSync(e)}catch{}},writeEntry:(e,t)=>{let n=`${e}.${t.pid}.tmp`;try{r.writeFileSync(n,JSON.stringify(t),{mode:384}),r.renameSync(n,e)}catch(e){try{r.unlinkSync(n)}catch(e){e.code}throw e}},ensureDirSafe:process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR?Ve:e=>{Ve(l.dirname(e)),Ve(e)},...t}}function SN(e){return e<32||e===127||e>=128&&e<=159}function CN(e){let t=``;for(let n of e)t+=SN(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function wN(e,t){let n=CN(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const TN=`\x1B[38;2;255;255;255m`,EN=`\x1B[48;2;200;40;40m`;function DN(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const ON={fg:DN(TN),bg:DN(EN)},kN={fg:DN(`\x1B[38;2;0;0;0m`),bg:DN(`\x1B[48;2;220;160;40m`)},AN=new Ai({"strip.separator":`default`,"strip.rail":`default`});function jN(e){return AN.resolve(e)}const MN=RegExp(`\\x1b\\[[0-9;]*m|${la.source}`,`g`),NN={kind:`still`},PN=Symbol(`bar`);function FN(e){return e.name!==Wc}function IN(e){return(t,n)=>{let r=e.map(({t:e,effect:t})=>t(e,n));return(e,t)=>r.reduce((e,n)=>n(e,t),e)}}const LN=oi;function RN(e,t){let n=new Wn(t,LN.foregroundColor,LN.ansiColors,LN.palette);return(t,r)=>e(t,{...r,theme:n})}function zN(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 BN=4096;var VN=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Wc,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(e=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:PN,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m},g=(e,n)=>{if(p.has(e))return p.get(e);let r=f===null?null:f.has(e)?f.get(e):(()=>{let r=ds.transitions.fade({span:n.reduce((e,{owner:t})=>e+t.cellLength,0),z:zN(`${this.key}@${e}`)*BN});return{since:t,fade:{effect:RN(r.effect,n[0].placement.ground),done:e=>r.done(e)}}})(),i=r===null||r.fade.done(t-r.since)?null:r;return p.set(e,i),i!==null&&m.push({placement:e,t:t-i.since}),i},_=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},v=(e,t,n)=>{let r=c.get(e)??new Map;c.set(e,r);let i=r.get(t.scope);if(i!==void 0)return i.effect;let a=s.get(e)?.get(t.scope),o=a?.name===t.name&&a.span===n,l=zN(t.scope===PN?e:`${e}@${t.scope}`),u=o?a.effect:ds.loops[t.name]({span:n,z:l*BN});return h[o?`reused`:`made`]++,r.set(t.scope,{name:t.name,span:n,effect:u}),u},y=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:_(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},b=d===`off`?()=>[]:e=>{let n=new Map;for(let t of e){let e=n.get(t.placement.id);e===void 0?n.set(t.placement.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=g(e,n);return r===null?[]:[{t:t-r.since,effect:bo(r.fade.effect,...n.map(({owner:e})=>e))}]})};return{row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?y(t):[{...i,owners:void 0}]).filter(FN),r=b(t);if(n.length===0&&r.length===0)return NN;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:(e,t)=>new go(e,IN([...n.map(e=>{let n=v(a,e,t);return{t:e.t,effect:e.owners===void 0?n:bo(n,...e.owners)}}),...r]),{t:i.t,key:a,theme:LN})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=h}}}},HN=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new VN(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function UN(e){return Math.max(0,...e.split(`
179
- `).map(e=>A(e.replace(MN,``))))}function WN(e,t){return ho(e,{...t,theme:AN,onStyleError:e=>{throw e}})}const GN=new Map;function KN(e){let t=GN.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>({...t,glyph:e}));return{...t,seam:n,divider:n}},{shape:r,ascii:i}=fo.plain,a=new Ya(n(r),nl(e)?n(i):i);return GN.set(e,a),a}function qN(e,t){return e===`plain`&&t!==void 0?KN(t):fo[e]}const JN=e=>({asciiOnly:e===`ascii`}),YN=new Map;function XN(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=YN.get(t);if(n!==void 0)return n;let r=qN(e.endcaps,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=t=>new W(WN(new ka(t,r),{colorSystem:null,...JN(e.charset)}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return YN.set(t,s),s}function ZN(e){return XN(e).chrome}function QN(e){return XN(e).seam}function $N(e,t,n=NN){if(e.length===0)return``;let r=qN(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...JN(t.charset),...i?{width:t.width}:{}},o=i?new _s([...e],{joiner:r}):new ka([...e],r),s=n.kind===`still`?WN(o,a):WN(n.wrap(o,UN(WN(o,a))),a);if(!s.endsWith(`
180
- `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return s.slice(0,-1)}function eP(e){return Math.min(20,e??20)}const tP={heading:`ERROR`,glyph:`⚠`,colors:ON},nP={heading:`WARNING`,glyph:`⚠`,colors:kN},rP={heading:`UPDATE`,glyph:`⬆`,colors:kN};function iP(e,t){return{text:CN(e),link:t}}function aP(e,t,n){let[r,...i]=[oP(e,tP,Hj),t,oP(n,nP,Uj)].flat();return r===void 0?null:{channels:[r,...i]}}function oP(e,t,n){let r=uM([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>iP(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function sP(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
181
- `)}function cP(e,t,n,r){if(t===null)return e;let i=lP(r),a=t.channels.flatMap(e=>uP(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[dP(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
182
- `);return e?`${l}\n${e}`:l}function lP(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function uP(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Kt(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>$N([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Zt(e,r)).map(e=>i(e,t))})],t).split(`
183
- `))}function dP(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ae(a.path).href)):c(`full text unavailable: ${CN(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(CN(o),s.withLink(ae(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,$N([m],r)}const fP=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function pP(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function mP(e,t){return r.readdirSync(t).filter(fP).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?mP(e,i):[[l.relative(e,i).split(l.sep).join(`/`),pP(i,a)]]})}function hP(e){let t=oe.createHash(`sha256`);for(let[n,r]of mP(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const gP=e=>e.slice(0,7);function _P(e){return l.dirname(l.dirname(e))}function vP(){return{version:qA,digest:`145a777640ca83b5b45dc4e67883cd4666c7706b3a383808b5463281fc31ed57`}}function yP(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function bP(e,t){try{let n=_P(E(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=hP(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:yP(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function xP(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function SP(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 CP(e,t,n){let r=Su(e,new Set(n.map(xu).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const wP=/^-?\d+$/;function TP(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 EP(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!wP.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 DP(e,t,n){return r=>r?wP.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 OP(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=>!wP.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 kP(e){return e===`config`?`set-config`:`set-state`}function AP(e,t,n){return t.kind===`int`?EP(`menu page "${e}"`):t.kind===`range`?DP(t.min,t.max,`${n} stepper "${e}"`):TP(t.allowed,`${n} "${e}"`,kP(n))}function jP(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:OP(e,n,t)}))}function MP(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 jP(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,AP(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 NP(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};MP(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=MP(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const PP=NP({},`config`,VP);function FP(e,t){return PP.register(e,t)}function IP(e){return PP.gateFor(e)}function LP(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:xw(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:[xP({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[xP({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:xw(e.insertSegmentFrom,t).members.map(t=>xP({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function RP(e,t){let n=Pf(e).get(t);return n===void 0?null:String(n)}function zP(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?Rw(n.persist):null;e?.scope===`preset-root`&&t.add(Pw(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function BP(e){let t=AD(e);return[...zP(e),...Object.values(e.actions).flatMap(e=>LP(e,t))]}function VP(e){return jP(BP(e),`config`)}const HP={},UP=DT(`commands.`),WP=VT(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),GP=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,KP=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${GP}) (basename .project_dir) (ne (${GP}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,qP=`{{ ${Qw} }}`,JP={min:0,max:100,step:5},YP={warnAt:{label:`warning at %`,domain:JP,default:50},errorAt:{label:`error at %`,domain:{...JP,atLeast:`warnAt`},default:80}};function XP(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:JP,default:80}}}const ZP={globals:{palette:`tokyo-night`},variables:{...UP.variables,...JC,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``},"activity.ticket.id":{kind:`input`,path:`activity.ticket.id`,type:`string`,default:``},"activity.ticket.phase":{kind:`input`,path:`activity.ticket.phase`,type:`string`,default:``},"activity.ticket.epic.done":{kind:`input`,path:`activity.ticket.epic.done`,type:`number`,default:0},"activity.ticket.epic.total":{kind:`input`,path:`activity.ticket.epic.total`,type:`number`,default:0},"activity.ticket.unread":{kind:`input`,path:`activity.ticket.unread`,type:`string`,default:``},"ticket.detail":{kind:`state`,key:`ticket-detail`,default:`collapsed`}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:KP},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:qP,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:gT(``).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:UP.template,when:UP.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:XP(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:XP(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:YP,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:YP,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) ${tc} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:WP.template,bg:WP.bg,when:WP.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) }}`},ticket:{group:`activity`,description:`The lit ticket this session started; expands to its workflow phase and its epic's done/total.`,template:`🎫 {{ action "copyTicket" .activity.ticket.id }}{{ if eq .ticket.detail "expanded" }} · {{ .activity.ticket.phase }}{{ if .activity.ticket.epic.total }} · epic {{ .activity.ticket.epic.done }}/{{ .activity.ticket.epic.total }}{{ end }}{{ if .activity.ticket.unread }} · ⚠ unreadable {{ abbrev 40 .activity.ticket.unread }}{{ end }}{{ end }} {{ action "ticketDetail" "▸" "◂" }}`,when:`{{ ne .activity.ticket.id "" }}`},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`},{kind:`segment`,name:`ticket`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...gT(``).actions,...UP.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},ticketDetail:{set:`ticket-detail`,cycle:[`collapsed`,`expanded`]},copyTicket:{copy:`{{ .activity.ticket.id }}`},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...WP.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:HP,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${tc}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:HT(`.`),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 .)) }}`}},QP=new Set([ZP.globals.palette,...Object.keys(ZP.themeDefaults),...Object.values(ZP.segments).map(e=>e.palette)].filter(e=>e!==void 0)),$P=Id(bA(`<default>`,JSON.stringify(ZP),QP),ZP),eF=Mb($P.presets);function tF(e){return eF.includes(e)}const nF=Object.freeze({});function rF(e,t){return e.kind===`decided`?t[e.name]??nF:nF}function iF(e,t){return{...e,...Object.fromEntries(ku.map(n=>[n,e[n]??t[n]]))}}function aF(e){if(!e)return 0;try{return s(e).mtimeMs}catch{return 0}}const oF=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function sF(e){return((...t)=>oF.run(()=>e(...t)))}const cF=sF(ee),lF=sF(C),uF=sF(w);async function dF(e,t){return oF.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function fF(e,t){return oF.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const pF=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function mF(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function hF(e){let t=await gF(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function gF(e){for(let t of[65536,1048576]){let n=await fF(e,t);if(n.kind!==`ok`)return n;let r=_F(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function _F(e,t){let n=e.toString(`utf8`).split(`
184
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!pF.test(t))continue;let r=mF(t);if(r!=null)return r}return null}function vF(e,t){return{...e,claudeConfigDir:kT(t.claudeConfigDir),env:t.mementoEnv}}const yF=l.join(`lib`,`ceiling_config.py`),bF=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function xF(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function SF(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function CF(e,t){if(!r.existsSync(e))return Y;let n;try{n=xF(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=SF([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[yF,bF].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function wF(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:$e]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function TF(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function EF(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function DF(e,t){let n=await je({bin:`python3`,args:[`-c`,`
177
+ Tip: every bar carries a settings menu — click it (${Vd} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/shade/endcaps/wrap/padding controls.\n`}async function QM(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...kM],i=WM();process.platform===`darwin`?KM(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
178
+ `),$M(i.binPath,r,t),process.stdout.write(ZM());let a=DM(wM,EM(JA,await TM(wM,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function $M(e,t,n,i){let a=i??jT(AT(kT(process.env,process.cwd())));r.mkdirSync(l.dirname(a),{recursive:!0});let o=PT(a).statusLine,s=FT(o)?o.command:void 0,c=[e,yM(e),vM(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||c.some(e=>s===e||s.startsWith(`${e} `)));if(s&&!u&&!n){process.stderr.write(`Skipping settings.json update: existing statusLine.command appears customized.\n Current: ${s}\n To overwrite, re-run with --force.\n`);return}let d=jM(e,t);Pe(a,(FT(o)?[[[`statusLine`,`type`],`command`],[[`statusLine`,`command`],d]]:[[[`statusLine`],{type:`command`,command:d}]]).reduce((e,[t,n])=>$l(e,t,JSON.stringify(n,null,2),Rl),NT(a))),process.stdout.write(`Updated ${a}\n`)}function eN(e,t){return e.kind===`owned`?t(e.pid,e.startTime)?{kind:`attach-and-exit`,reason:`live owner pid=${e.pid} holds the socket`}:{kind:`reclaim`,reason:`owner pid=${e.pid} is gone or recycled`}:e.kind===`absent`?{kind:`reclaim`,reason:`no lease — stale socket, no live owner`}:{kind:`reclaim`,reason:`unreadable lease (${e.detail}) — cannot prove a live owner`}}function tN(e){let t;try{t=r.readFileSync(e,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:`read failed: ${e.message}`}}let n;try{n=JSON.parse(t)}catch(e){return{kind:`unreadable`,detail:`bad JSON: ${e.message}`}}let i=n,a=i?.pid;if(typeof a!=`number`||!Number.isInteger(a)||a<=0)return{kind:`unreadable`,detail:`no valid pid (got ${JSON.stringify(a)})`};let o=i?.startTime;return o!=null&&typeof o!=`string`?{kind:`unreadable`,detail:`invalid startTime (got ${JSON.stringify(o)})`}:{kind:`owned`,pid:a,startTime:o??null}}function nN(e,n){let i=`${e}.${t.pid}.tmp`;try{return r.writeFileSync(i,JSON.stringify(n),{mode:384}),r.renameSync(i,e),null}catch(e){let t=e.message;try{r.unlinkSync(i)}catch(e){if(e.code!==`ENOENT`)return`${t}; also failed to remove temp ${i}: ${e.message}`}return t}}function rN(e,t){let n=tN(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function iN(e){try{let t=r.statSync(e);return{kind:`present`,identity:{dev:t.dev,ino:t.ino}}}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:e.message}}}function aN(e,t,n,r){let i=oN(e,t);return i===null?r.kind===`owned`?r.pid===n?{kind:`owned`}:{kind:`displaced`,reason:`lease reassigned (names pid=${r.pid}, we are pid=${n}) — a reclaimer overwrote it`}:{kind:`displaced`,reason:`lease not held (${r.kind}) — no longer the socket owner`}:{kind:`displaced`,reason:i}}function oN(e,t){return t.kind===`present`?t.identity.dev===e.dev&&t.identity.ino===e.ino?null:`socket replaced (bound dev=${e.dev} ino=${e.ino}, now dev=${t.identity.dev} ino=${t.identity.ino})`:t.kind===`absent`?`socket path gone (ENOENT) — unlinked by a reclaimer`:`socket path unreadable (${t.detail}) — cannot prove ownership`}function sN(e){let t=!1;function n(){let n=aN(e.bound,e.readIdentity(),e.myPid,e.readLease());return n.kind===`displaced`&&!t&&(t=!0,e.log(`warn`,`ownership self-check: ${n.reason}; shutting down`),e.shutdown(0)),n}function r(t=e.intervalMs??5e3){let r=setInterval(()=>{n().kind===`displaced`&&clearInterval(r)},t);return r.unref(),{disarm:()=>clearInterval(r)}}return{check:n,arm:r}}function cN(e,t=O){let n=t({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:2e3,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});if(n.ok){let e=n.stdout.trim();return e.length>0?{kind:`start`,token:e}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:n.reason===`spawn-error`?n.error??`ps spawn failed`:`ps ${n.reason} (exit ${n.exitCode})`}}function lN(e,t,n){if(t===null)return n.pidAlive(e);let r=n.readStartTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.pidAlive(e)}}function uN(e,t=cN){let n=t(e);return n.kind===`start`?n.token:null}const dN=`CC_CANDYBAR_PARENT_PID`;function fN(e){let t=e[dN];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${dN} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function pN(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??250);return n.unref(),{disarm:()=>clearInterval(n)}}function mN(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function hN(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function gN(e,t,n){return e?t>=n?{allow:!1,reason:`${t} live isolated daemons registered >= ceiling ${n}`}:{allow:!0,reason:`${t} live isolated daemons registered < ceiling ${n}`}:{allow:!0,reason:`canonical production socket — exempt (bind() already caps it to one)`}}function _N(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>l.join(e,t))}catch{return[]}}function vN(e){let t;try{t=r.readFileSync(e,`utf8`)}catch{return null}try{let e=JSON.parse(t),n=e?.pid;return typeof n!=`number`||!Number.isInteger(n)||n<=0?null:{pid:n,startTime:typeof e?.startTime==`string`?e.startTime:null}}catch{return null}}function yN(e,t,n){let r=0;for(let i of e)t(i.identity.pid,i.identity.startTime)?r++:n(i.path);return r}function bN(e){if(!e.isolated)return{decision:gN(!1,0,e.ceiling),registryPath:null};e.ensureDirSafe(e.registryDir);let t=[];for(let n of e.listFiles(e.registryDir)){let r=e.readEntry(n);r!==null&&r.pid!==e.pid&&t.push({path:n,identity:r})}let n=gN(!0,yN(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=l.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function xN(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function SN(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:qe(),ceiling:hN(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>lN(e,t,{readStartTime:cN,pidAlive:mN}),listFiles:_N,readEntry:vN,removeFile:e=>{try{r.unlinkSync(e)}catch{}},writeEntry:(e,t)=>{let n=`${e}.${t.pid}.tmp`;try{r.writeFileSync(n,JSON.stringify(t),{mode:384}),r.renameSync(n,e)}catch(e){try{r.unlinkSync(n)}catch(e){e.code}throw e}},ensureDirSafe:process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR?Ve:e=>{Ve(l.dirname(e)),Ve(e)},...t}}function CN(e){return e<32||e===127||e>=128&&e<=159}function wN(e){let t=``;for(let n of e)t+=CN(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function TN(e,t){let n=wN(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const EN=`\x1B[38;2;255;255;255m`,DN=`\x1B[48;2;200;40;40m`;function ON(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const kN={fg:ON(EN),bg:ON(DN)},AN={fg:ON(`\x1B[38;2;0;0;0m`),bg:ON(`\x1B[48;2;220;160;40m`)},jN=new Ai({"strip.separator":`default`,"strip.rail":`default`});function MN(e){return jN.resolve(e)}const NN=RegExp(`\\x1b\\[[0-9;]*m|${la.source}`,`g`),PN={kind:`still`},FN=Symbol(`bar`);function IN(e){return e.name!==Wc}function LN(e){return(t,n)=>{let r=e.map(({t:e,effect:t})=>t(e,n));return(e,t)=>r.reduce((e,n)=>n(e,t),e)}}const RN=oi;function zN(e,t){let n=new Wn(t,RN.foregroundColor,RN.ansiColors,RN.palette);return(t,r)=>e(t,{...r,theme:n})}function BN(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 VN=4096;var HN=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Wc,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(({passage:e})=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:FN,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision&&u.source.width===n.source.width?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h=[],g={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m,leaves:h},_=(e,n,{ground:r})=>{let i=ds.transitions[e]({span:0,z:BN(`${this.key}@${n}`)*VN});return{name:e,since:t,transition:{effect:zN(i.effect,r),done:e=>i.done(e)}}},v=({since:e,transition:n})=>n.done(t-e),y=(e,t,n)=>({drawing:t,passage:f===null?null:n===void 0||n.passage?.name===`dissolve`?_(`fade`,e,t):n.passage!==null&&!v(n.passage)?n.passage:null}),b=(e,t)=>{if(t===void 0||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return v(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:_(`dissolve`,e,r)}},x=(e,r)=>{if(p.has(e))throw Error(`placement "${e}" was reached twice in one frame`);let i=f?.get(e),{drawing:a,deeper:o}=n.returned(e,r),s=a===null?b(e,i):y(e,a,i);return s===void 0?r:(p.set(e,s),s.passage!==null&&(s.passage.name===`fade`?m:h).push({placement:e,t:t-s.passage.since}),a===null?[...s.drawing.own,...o]:r)},S=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},C=(e,t,n)=>{let r=c.get(e)??new Map;c.set(e,r);let i=r.get(t.scope);if(i!==void 0)return i.effect;let a=s.get(e)?.get(t.scope),o=a?.name===t.name&&a.span===n,l=BN(t.scope===FN?e:`${e}@${t.scope}`),u=o?a.effect:ds.loops[t.name]({span:n,z:l*VN});return g[o?`reused`:`made`]++,r.set(t.scope,{name:t.name,span:n,effect:u}),u},ee=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:S(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},w=e=>{let n=new Map;for(let{owner:t,placement:r}of e){let e=n.get(r.id);e===void 0?n.set(r.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=p.get(e)?.passage??null;return r===null?[]:[{t:t-r.since,effect:bo(r.transition.effect,...n)}]})};return{placed:d===`off`?(e,t)=>t:x,row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?ee(t):[{...i,owners:void 0}]).filter(IN),r=w(t);if(n.length===0&&r.length===0)return PN;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:(e,t)=>new go(e,LN([...n.map(e=>{let n=C(a,e,t);return{t:e.t,effect:e.owners===void 0?n:bo(n,...e.owners)}}),...r]),{t:i.t,key:a,theme:RN})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=g}}}},UN=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new HN(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function WN(e){return Math.max(0,...e.split(`
179
+ `).map(e=>A(e.replace(NN,``))))}function GN(e,t){return ho(e,{...t,theme:jN,onStyleError:e=>{throw e}})}const KN=new Map;function qN(e){let t=KN.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>({...t,glyph:e}));return{...t,seam:n,divider:n}},{shape:r,ascii:i}=fo.plain,a=new Ya(n(r),nl(e)?n(i):i);return KN.set(e,a),a}function JN(e,t){return e===`plain`&&t!==void 0?qN(t):fo[e]}const YN=e=>({asciiOnly:e===`ascii`}),XN=new Map;function ZN(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=XN.get(t);if(n!==void 0)return n;let r=JN(e.endcaps,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=t=>new W(GN(new ka(t,r),{colorSystem:null,...YN(e.charset)}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return XN.set(t,s),s}function QN(e){return ZN(e).chrome}function $N(e){return ZN(e).seam}function eP(e,t,n=PN){if(e.length===0)return``;let r=JN(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...YN(t.charset),...i?{width:t.width}:{}},o=i?new _s([...e],{joiner:r}):new ka([...e],r),s=n.kind===`still`?GN(o,a):GN(n.wrap(o,WN(GN(o,a))),a);if(!s.endsWith(`
180
+ `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return s.slice(0,-1)}function tP(e){return Math.min(20,e??20)}const nP={heading:`ERROR`,glyph:`⚠`,colors:kN},rP={heading:`WARNING`,glyph:`⚠`,colors:AN},iP={heading:`UPDATE`,glyph:`⬆`,colors:AN};function aP(e,t){return{text:wN(e),link:t}}function oP(e,t,n){let[r,...i]=[sP(e,nP,Uj),t,sP(n,rP,Wj)].flat();return r===void 0?null:{channels:[r,...i]}}function sP(e,t,n){let r=dM([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>aP(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function cP(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
181
+ `)}function lP(e,t,n,r){if(t===null)return e;let i=uP(r),a=t.channels.flatMap(e=>dP(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[fP(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
182
+ `);return e?`${l}\n${e}`:l}function uP(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function dP(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Kt(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>eP([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Zt(e,r)).map(e=>i(e,t))})],t).split(`
183
+ `))}function fP(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ae(a.path).href)):c(`full text unavailable: ${wN(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(wN(o),s.withLink(ae(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,eP([m],r)}const pP=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function mP(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function hP(e,t){return r.readdirSync(t).filter(pP).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?hP(e,i):[[l.relative(e,i).split(l.sep).join(`/`),mP(i,a)]]})}function gP(e){let t=oe.createHash(`sha256`);for(let[n,r]of hP(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const _P=e=>e.slice(0,7);function vP(e){return l.dirname(l.dirname(e))}function yP(){return{version:JA,digest:`d13aa7096f19ba199b1857ad8bde06eb7b6808d063af2fb48127a51ab663b1a2`}}function bP(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function xP(e,t){try{let n=vP(E(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=gP(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:bP(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function SP(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function CP(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 wP(e,t,n){let r=Su(e,new Set(n.map(xu).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const TP=/^-?\d+$/;function EP(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 DP(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!TP.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 OP(e,t,n){return r=>r?TP.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 kP(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=>!TP.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 AP(e){return e===`config`?`set-config`:`set-state`}function jP(e,t,n){return t.kind===`int`?DP(`menu page "${e}"`):t.kind===`range`?OP(t.min,t.max,`${n} stepper "${e}"`):EP(t.allowed,`${n} "${e}"`,AP(n))}function MP(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:kP(e,n,t)}))}function NP(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 MP(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,jP(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 PP(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};NP(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=NP(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const FP=PP({},`config`,HP);function IP(e,t){return FP.register(e,t)}function LP(e){return FP.gateFor(e)}function RP(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:Sw(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:[SP({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[SP({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Sw(e.insertSegmentFrom,t).members.map(t=>SP({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function zP(e,t){let n=Pf(e).get(t);return n===void 0?null:String(n)}function BP(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?zw(n.persist):null;e?.scope===`preset-root`&&t.add(Fw(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function VP(e){let t=jD(e);return[...BP(e),...Object.values(e.actions).flatMap(e=>RP(e,t))]}function HP(e){return MP(VP(e),`config`)}const UP={},WP=OT(`commands.`),GP=HT(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),KP=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,qP=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${KP}) (basename .project_dir) (ne (${KP}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,JP=`{{ ${$w} }}`,YP={min:0,max:100,step:5},XP={warnAt:{label:`warning at %`,domain:YP,default:50},errorAt:{label:`error at %`,domain:{...YP,atLeast:`warnAt`},default:80}};function ZP(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:YP,default:80}}}const QP={globals:{palette:`tokyo-night`},variables:{...WP.variables,...YC,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``},"activity.ticket.id":{kind:`input`,path:`activity.ticket.id`,type:`string`,default:``},"activity.ticket.phase":{kind:`input`,path:`activity.ticket.phase`,type:`string`,default:``},"activity.ticket.epic.done":{kind:`input`,path:`activity.ticket.epic.done`,type:`number`,default:0},"activity.ticket.epic.total":{kind:`input`,path:`activity.ticket.epic.total`,type:`number`,default:0},"activity.ticket.unread":{kind:`input`,path:`activity.ticket.unread`,type:`string`,default:``},"ticket.detail":{kind:`state`,key:`ticket-detail`,default:`collapsed`}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:qP},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:JP,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:_T(``).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:WP.template,when:WP.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:ZP(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:ZP(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:XP,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:XP,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) ${tc} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:GP.template,bg:GP.bg,when:GP.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) }}`},ticket:{group:`activity`,description:`The lit ticket this session started; expands to its workflow phase and its epic's done/total.`,template:`🎫 {{ action "copyTicket" .activity.ticket.id }}{{ if eq .ticket.detail "expanded" }} · {{ .activity.ticket.phase }}{{ if .activity.ticket.epic.total }} · epic {{ .activity.ticket.epic.done }}/{{ .activity.ticket.epic.total }}{{ end }}{{ if .activity.ticket.unread }} · ⚠ unreadable {{ abbrev 40 .activity.ticket.unread }}{{ end }}{{ end }} {{ action "ticketDetail" "▸" "◂" }}`,when:`{{ ne .activity.ticket.id "" }}`},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`},{kind:`segment`,name:`ticket`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{..._T(``).actions,...WP.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},ticketDetail:{set:`ticket-detail`,cycle:[`collapsed`,`expanded`]},copyTicket:{copy:`{{ .activity.ticket.id }}`},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...GP.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:UP,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${tc}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:UT(`.`),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 .)) }}`}},$P=new Set([QP.globals.palette,...Object.keys(QP.themeDefaults),...Object.values(QP.segments).map(e=>e.palette)].filter(e=>e!==void 0)),eF=Id(xA(`<default>`,JSON.stringify(QP),$P),QP),tF=Nb(eF.presets);function nF(e){return tF.includes(e)}const rF=Object.freeze({});function iF(e,t){return e.kind===`decided`?t[e.name]??rF:rF}function aF(e,t){return{...e,...Object.fromEntries(ku.map(n=>[n,e[n]??t[n]]))}}function oF(e){if(!e)return 0;try{return s(e).mtimeMs}catch{return 0}}const sF=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function cF(e){return((...t)=>sF.run(()=>e(...t)))}const lF=cF(ee),uF=cF(C),dF=cF(w);async function fF(e,t){return sF.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function pF(e,t){return sF.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const mF=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function hF(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function gF(e){let t=await _F(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function _F(e){for(let t of[65536,1048576]){let n=await pF(e,t);if(n.kind!==`ok`)return n;let r=vF(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function vF(e,t){let n=e.toString(`utf8`).split(`
184
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!mF.test(t))continue;let r=hF(t);if(r!=null)return r}return null}function yF(e,t){return{...e,claudeConfigDir:AT(t.claudeConfigDir),env:t.mementoEnv}}const bF=l.join(`lib`,`ceiling_config.py`),xF=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function SF(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function CF(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function wF(e,t){if(!r.existsSync(e))return Y;let n;try{n=SF(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=CF([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[bF,xF].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function TF(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:$e]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function EF(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function DF(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function OF(e,t){let n=await je({bin:`python3`,args:[`-c`,`
185
185
  import json, math, sys
186
186
  sys.path.insert(0, sys.argv[1])
187
187
  from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
@@ -190,41 +190,41 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
190
190
  layer = ceiling_in(directory / CONFIG_NAME)
191
191
  print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
192
192
  "session": layer.text if layer else None}))
193
- `,l.join(e,`lib`),t.sessionId,t.cwd],env:wF(t),timeoutMs:3e3,category:`memento.read`});return n.ok?EF(n.stdout):X(TF(n))}function OF(e,t,n){let r=O({bin:l.join(e,bF),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:wF(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(TF(r))}function kF(){return{locate:e=>CF(jT(e.claudeConfigDir),e.projectDir),read:DF,move:OF}}function AF(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${vM(n)} `,i=e.added_dirs.map(e=>` --add-dir ${vM(e)}`).join(``);return`cd ${vM(e.project_dir)} && ${r}claude --resume ${vM(t)}${i}`}function jF(e,t,n){let r=Nb(t(`preset`),e.globals.preset,e.presets),i=Ib(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=mw(a.palette,t(`theme`),i.palette),s=iF(i,rF(o,e.themeDefaults));return{preset:r,presetCustomized:n(r),theme:o,style:Uc(a.style,t(`style`),s.style,e.styles),effect:Yc(a.effect,t(`effect`),s.effect),endcaps:el(a.endcaps,t(`endcaps`),s.endcaps),variation:cl(a.variation,t(`variation`),s.variation),shade:dl(a.shade,t(`shade`),s.shade),separator:a.default_separator??s.default_separator,autoWrap:yl(a.autoWrap,t(`autoWrap`),s.autoWrap),padding:Sl(a.padding,t(`padding`),s.padding),charset:a.charset??s.charset??`unicode`,updateNotice:bl(a.updateNotice,t(`updateNotice`),s.updateNotice),transitions:xl(a.transitions,t(`transitions`),s.transitions),colorCompatibility:a.colorCompatibility??s.colorCompatibility??`truecolor`}}function MF(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function NF(e){return{theme:e.theme,style:e.style,effect:e.effect,preset:e.preset,variation:e.variation,shade:e.shade,transitions:e.transitions}}function PF(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:tF(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},shade:{effective:e.shade},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice},transitions:{effective:e.transitions}}}const FF=10*1e3;function IF(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function LF(e,t){if(!(t<60))return e*3600/t}function RF(e,t,n,r){let i=r-t;if(i<50||i>FF)return;let a=n-e;if(!(a<=0))return a*1e3/i}function zF(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=RF(t.input,t.atMs,n.input,n.atMs),i=RF(t.output,t.atMs,n.output,n.atMs),a=RF(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 BF(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>FF)continue;let o=RF(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function VF(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function HF(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>VF(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function UF(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>Sx(t,e.helpers).keys(),o=Ib(e,t);for(let e of Ic){let t=o[e];if(Lc(t))for(let e of a(t))r.push(e)}for(let n of wu(Fb(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of GF(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function WF(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=UF(e,n);return t.set(n,i),i}}function GF(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function KF(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function qF(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function JF(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>KF(i,e),u=wC(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[p,m,h,g,_,v,y,b,x,S,C]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,qF(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(Y):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>hF(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(vF({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(AT(kT(o.claudeConfigDir)))))]),ee=[],w=e=>{if(e.kind===`failed`){ee.push(e.reason);return}return e.kind===`ok`?e.value:void 0},te=nI(p,u);ee.push(...te.failures);let ne=HF(o);ee.push(...ne.failures);let re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=w(b),ce=ZF(S);S.kind===`failed`&&ee.push(`memento: ${S.reason}`);let le=YF(C,T?.maxTokens);C.kind===`failed`&&ee.push(`autocompact: ${C.reason}`);for(let e of ee)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?IF(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?IF(de.used_percentage,de.resets_at,6048e5,u):void 0,me=re?.session.cost,he=E?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?LF(me,he):void 0,_e=w(x),ve=_e===void 0?void 0:zF(_e),ye=_e===void 0?void 0:BF(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,D=tI(process.env.HOME??process.env.USERPROFILE),xe=e.workspace?{...e.workspace,current_dir:tI(e.workspace.current_dir)??``,project_dir:tI(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>tI(e)??e)}:e.workspace,Se=re===void 0?void 0:eI({cost:re.session.cost,tokens:re.session.tokens}),Ce=ie===void 0?void 0:{cost:ie.cost,tokens:ie.tokens},we=E===void 0?void 0:eI({lastResponseTime:E.lastResponseTime,responseTime:E.responseTime,sessionDuration:E.sessionDuration,messageCount:E.messageCount,linesAdded:E.linesAdded,linesRemoved:E.linesRemoved}),Te=ae===void 0?void 0:QF(ae);return{...e,...xe!==void 0&&{workspace:xe},...D!==void 0&&{home:D},...te.git!==void 0&&{git:te.git},...d!==null&&{tmux:{pane:d.pane,...oe!==void 0&&{session:oe}}},host:ne.host,...PF(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},...c,...s!==null&&{configPath:s},resumeCommand:AF(xe,e.session_id,o.claudeConfigDir),...Se!==void 0&&{session:Se},...Ce!==void 0&&{today:Ce},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...T!==void 0&&{context:{totalTokens:T.totalTokens,contextLeft:T.contextLeftPercentage}},...we!==void 0&&{metrics:we},...Te!==void 0&&{activity:Te},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function YF(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return BT(e.value,t)}}const XF=e=>e.trim().split(`
194
- `).at(-1).trim();function ZF(e){switch(e.kind){case`absent`:return;case`failed`:return{error:XF(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function QF(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=$F(e.running),i=$F(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}},o=e.ticket===null?void 0:{id:e.ticket.id,phase:e.ticket.phase,...e.ticket.epic!==null&&{epic:e.ticket.epic},...e.ticket.unread!==null&&{unread:e.ticket.unread}};if(!(o===void 0&&e.command===null&&n===void 0&&a===void 0))return{...o!==void 0&&{ticket:o},...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function $F(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function eI(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 tI(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function nI(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=i(`repoName`,n.repoName),p=i(`repoUrl`,n.repoUrl),m=n.pullRequest,h={};return m?.kind===`ok`?(h.prNumber=m.value.number,h.prState=m.value.state,h.prUrl=m.value.url):m?.kind===`failed`&&(r.push(`git.pr: ${m.reason}`),h.prError=m.reason),{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{repoName:f},...p!==void 0&&{repoUrl:p},...h},failures:r}}const rI={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,effect:e=>e.effect.kind===`decided`?e.effect.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,shade:e=>e.shade,transitions:e=>e.transitions?fl:pl,autoWrap:e=>e.autoWrap?fl:pl,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?fl:pl},iI=Object.entries(XC),aI=new Set(ZC.map(e=>e.sessionKey)),oI=()=>!1;function sI(e,t){return jF(e,e=>aI.has(e)?t(e):null,oI)}const cI=[`preset`,`theme`];function lI(e,t,n){let r=new Set(cI.slice(0,n).map(e=>XC[e].sessionKey));return jF(e,e=>r.has(e)?t(e):null,oI)}function uI(e,t){let n=Array.from({length:cI.length+1},(n,r)=>lI(e,t,r));return e=>{let t=cI.indexOf(e);return n[t===-1?cI.length:t]}}function dI(e,t,n,r){return e.flatMap(([e,i])=>{let a=rI[e](t);return a===null||a===rI[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function fI(e,t,n){return rI[n](sI(e,t))}function pI(e,t){let n=sI(e,t);return dI(iI,n,uI(e,t),t=>mI(e,n.preset,t.configKey))}function mI(e,t,n){return n in(Pb(e.presets,t).globals??{})?Lw(t,n):n}function hI(e,t,n){let r=Nb(t(XC.preset.sessionKey),e.globals.preset,e.presets),i=Rw(n);return{key:i?.scope===`globals`?mI(e,r,i.field):n,globals:Ib(e,r)}}function gI(e,t){let{preset:n}=sI(e,t);return yI(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Hu(a,s);return c===void 0||Vu(c)===Vu(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function _I(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Mb(e.presets).flatMap(n=>{let i=yI(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 zu(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:Hu(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const vI=new WeakMap;function yI(e,t){let n=vI.get(e)??new Map;vI.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...wu(Fb(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Lu(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 bI(e,t){let n=sI(e,t);return{from:n.preset,globals:Pb(e.presets,n.preset).globals??{},picks:dI(iI.filter(([e])=>e!==`preset`),n,uI(e,t),e=>e.configKey),placements:gI(e,t)}}function xI(e,t){return jF({...e,globals:{palette:t},presets:{}},()=>null,oI)}function SI(e,t){let n=sI(e,t),r=rI.theme(n);if(r===null)return{kind:`rule`};let i=xI(e,r),a=Ib(e,n.preset),o=Object.fromEntries(ku.map(e=>[e,rI[e](a[e]===void 0?n:i)]));return{kind:`look`,theme:r,look:o,differs:ku.some(e=>o[e]!==rI[e](i))}}function CI(e){return{sessionKeys:ZC.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...xf(e)?eF.map(t=>Lw(t,e)):[],...Iw(e)?jc().map(t=>Fw(t,e)):[]]}}function wI(e){return new Set(ZC.map(e=>e.configKey).filter(t=>CI(t).fileKeys.some(t=>DI(e,EI(t)))))}function TI(e,t,n){let r=pI(e,n),i=new Set(r.map(e=>e.configKey)),a=nw(e=>i.has(XC[e].configKey)||t.has(XC[e].configKey)),o=SI(e,n);return{unsaved:r.length+gI(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function EI(e){let t=Rw(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return zw(t)}function DI(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&DI(e[n],r)}const OI=jc(),kI=new Set(OI),AI=new Set(Xc),jI=e=>e?kI.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${OI.join(`, `)})`}:{ok:!1,reason:`theme name is required`},MI=e=>e?AI.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Xc.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},NI=new Set([`1`,`true`]),PI=new Set([`0`,`false`]),FI={endcaps:MI,theme:jI,"toolbar-expanded":e=>NI.has(e)?{ok:!0,value:`1`}:PI.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},II=NP(FI,`state`,UI);function LI(e,t){return II.register(e,t)}function RI(e){return II.gateFor(e)}function zI(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:xw(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 BI(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(FI,e.key))}function VI(e,t,n){let r=rw.get(n);if(r!==void 0)return fI(e,t,r);let i=Object.values(e.variables).find(e=>e.kind===`state`&&e.key===n);return i?.kind===`state`?i.default??null:null}function HI(e){let t=AD(e);return BI(Object.values(e.actions).flatMap(e=>zI(e,t)))}function UI(e){return jP(HI(e))}const WI=`update.dismissed`,GI=`updateNotice`,KI=XC.updateNotice.sessionKey;function qI(e){return e.kind===`source`?e.newer.digest:xM(e.newer)}const JI=e=>`${e.version} [${gP(e.digest)}]`;function YI(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:JI(e.newer),running:JI(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:xM(e.newer),running:xM(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${CM}@${xM(e.newer)}`,`install`]}}}}const XI={kind:`idle`},ZI={kind:`running`};function QI(e,t,n){if(e===null)return[];let r=qI(e);if(!n.enabled||n.dismissed===r)return[];let i=YI(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(`
195
- `),c=uM([{verb:Uj,args:[s]}]),l=t.kind===`running`?iP(`[${i.busy}]`,c):iP(`[${i.act}]`,uM([{verb:nM,args:[n.sessionId]}]));return[{severity:rP,message:s,lines:[[iP(a,c),l,iP(`[dismiss]`,uM([{verb:Lj,args:[n.sessionId,WI,r]}])),iP(`[disable]`,uM([{verb:Wj,args:[n.sessionId,GI,`false`]},{verb:Lj,args:[n.sessionId,KI,`false`]}]))],...o.map(e=>[iP(e,c)])]}]}function $I(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function eL(e){switch(e.kind){case`current`:return[`info`,`build: current ${JI(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${JI(e.source)}, running ${JI(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function tL(e){switch(e.kind){case`current`:return[`info`,`release: current ${xM(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${xM(e.latest)}, running ${xM(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${xM(e.installed)}, latest ${xM(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function nL(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const rL=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function iL(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=rL(e.stderr)??e.error??rL(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function aL(){let e=[FP(GI,[`false`]),LI(KI,[`false`]),LI(WI,[])];return()=>e.forEach(e=>e())}function oL(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=XI,d=null,f=nL(s),p=nL(s),m=()=>$I(c,l);function h(){let e=m(),t=e===null?null:qI(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:LI(WI,[t])})}function g(){c=bP(t,vP),f(eL(c)),h()}async function _(){l=TM(qA,await wM(CM,a,i)),p(tL(l)),h()}return{arm(){aL(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>QI(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=YI(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=ZI,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),je({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=XI,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=iL(n);u={kind:`failed`,identity:qI(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var sL=class{static CACHE_DIR=Le();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return D(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ue(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return se(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){D(`Cache for ${e} is locked, waiting...`),await ue(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ue(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const cL={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var lL=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await sL.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await sL.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ie(this.GITHUB_PRICING_URL),n=le({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(cL).length} models`),this.executionCache=cL,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(cL).length} models`),cL)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const uL=String.raw`(?:^|[\s;&|(])`,dL=e=>RegExp(`(?:^|:)(?:${e})$`),fL=[{phase:`impl`,tool:`Edit`,match:/^/},{phase:`impl`,tool:`MultiEdit`,match:/^/},{phase:`impl`,tool:`Write`,match:/^/},{phase:`impl`,tool:`NotebookEdit`,match:/^/},{phase:`review`,tool:`Bash`,match:RegExp(`${uL}gh\\s+pr\\s+create\\b`)},{phase:`review`,tool:`Skill`,match:dL(`code-review|simplify`)},{phase:`groom`,tool:`Bash`,match:RegExp(`${uL}lit\\s+(done|close)\\b`)},{phase:`groom`,tool:`Skill`,match:dL(`groom-backlog`)},{phase:`handoff`,tool:`Skill`,match:dL(`message-in-a-bottle`)}],pL=e=>RegExp(`${uL}lit\\s+(?:${e})(?:\\s+(?:--?[\\w-]+(?:=\\S*)?|''))*\\s+([A-Za-z0-9][\\w.-]*)`),mL=[{verb:pL(`start`),to:`in_progress`},{verb:pL(`done|close`),to:`closed`}];function hL(e){return fL.find(t=>t.tool===e.tool&&t.match.test(e.subject))?.phase}function gL(e,t){if(t.tool===`Bash`)for(let{verb:n,to:r}of mL){let i=n.exec(t.subject)?.[1];if(i!==void 0)return{call:e,id:i,to:r}}}const _L=/^lit:state (.*)$/gm;function vL(e){return[...e.matchAll(_L)].map(([e,t])=>yL(t)??{kind:`unreadable`,line:e.trim()})}function yL(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{id:n,status:r,epic:i}=t;if(typeof n!=`string`||typeof r!=`string`)return;if(i===null)return{kind:`state`,id:n,status:r,epic:null};if(typeof i!=`object`||i===void 0)return;let a=i;if(!(typeof a.id!=`string`||typeof a.done!=`number`||typeof a.total!=`number`))return{kind:`state`,id:n,status:r,epic:{id:a.id,done:a.done,total:a.total}}}function bL(e,t){let n=t??{};return{tool:e,subject:e===`Bash`&&typeof n.command==`string`?CL(n.command):e===`Skill`&&typeof n.skill==`string`?n.skill:e}}const xL=/(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)[\s\S]*?\n\s*\3(?=\n|$)/g,SL=/'[^']*'|"(?:[^"\\]|\\.)*"/g;function CL(e){return e.replace(xL,`$1`).replace(SL,`''`)}function wL(e){return typeof e==`string`?[e]:Array.isArray(e)?e.flatMap(e=>typeof e==`object`&&e&&typeof e.text==`string`?[e.text]:[]):[]}const TL=/^(\S+) \[(open|in_progress|closed)\//gm,EL=/^Ticket (\S+) has been closed\./gm,DL={sentinels:[],said:[]};function OL(e){let t;for(let n of wL(e)){let e=n.includes(`lit:state `),r=n.includes(` [`),i=n.includes(`has been closed.`);if(!(!e&&!r&&!i)){if(t??={sentinels:[],said:[]},e&&t.sentinels.push(...vL(n)),r)for(let[,e,r]of n.matchAll(TL))t.said.push({id:e,status:r});if(i)for(let[,e]of n.matchAll(EL))t.said.push({id:e,status:`closed`})}}if(t===void 0)return DL;for(let e of t.sentinels)e.kind===`state`&&t.said.push({id:e.id,status:e.status});return t}const kL=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function AL(e){if(typeof e==`string`)return kL.exec(e)?.[1]}function jL(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 ML(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o,s=[],c=[],l,u=[];if(typeof t==`string`)o=t;else if(Array.isArray(t))for(let e of t){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});let i=bL(n,t.input),o=gL(e,i);o!==void 0&&s.push(o),l=hL(i)??l,n===`TodoWrite`&&(a=jL(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id,n=OL(t.content);if(u.push(...n.sentinels),typeof e==`string`){i.push(e);for(let t of n.said)c.push({call:e,...t})}break}case`text`:o??=t.text;break;default:break}}let d=n?AL(o):void 0,f=s.length===0&&l===void 0&&u.length===0&&c.length===0?void 0:{...s.length>0&&{claims:s},...l!==void 0&&{phase:l},...u.length>0&&{sentinels:u},...c.length>0&&{said:c}};if(!(r.length===0&&i.length===0&&a===void 0&&d===void 0&&f===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...d!==void 0&&{command:d},...f!==void 0&&{lit:f}}}function NL(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function PL(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await cF(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function FL(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await cF(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await lF(t,`utf-8`)).split(`
196
- `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function IL(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}const LL=new Map;async function RL(e){try{let t=await uF(e),n=t.size,r=LL.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),LL.delete(e),LL.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await UL(e)):i=await VL(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(LL.delete(e),LL.size>=16&&LL.delete(LL.keys().next().value),LL.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function zL(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;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,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,activity:ML(e),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 BL(e){let t=[];for(let n of e.split(`
197
- `))if(n.trim())try{let e=zL(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function VL(e){return BL(await lF(e,`utf-8`))}async function HL(e,t){let n=await dF(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return J(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:BL(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function UL(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=de({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=zL(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var WL=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 GL(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 KL=new Map,qL={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},JL={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function YL(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function XL(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function ZL(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function QL(e,t,n,r){let i=YL(new Date(XL())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:ZL(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await lL.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=YL(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...qL};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function $L(e){let t=0,n=0,r=ZL(),i=new Map;for(let 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)??{...qL};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:JL,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function eR(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var tR=class{entries=new Map;flight=new WL;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new WL;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??lC,this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:JL,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=YL(wC(n)),i=NL(t);try{await this.ensureSeeded(r,i)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path);if(a.kind===`failed`)return a;let o=i.map(e=>p(e,`projects`)+m),s={...qL},c=!1;for(let[t,n]of this.entries){let i=n.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n.days:KL;c||=a.has(r);let l=a.get(r)??qL;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?J({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):Y}async observeSpeed(e,t,n){let r=aF(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=GL(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),J({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Y;let r=n??aF(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,J(i);if(!t)return i?J(i):Y;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return X(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),J(o)}async refold(e,t,n){let r=await FL(e,d(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await HL(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await QL(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...$L(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=XL(),n=await PL(e),r=[];for(let e of n){let n;try{n=await cF(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=p(e,i),a;try{a=(await uF(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await eR(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},nR=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await RL(e);if(n.length===0)return D(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},rR=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=aF(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await HL(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const iR={messageCount:0,recent:[]};function aR(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!IL(t),recent:n.length>20?n.slice(-20):n}}function oR(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(IL(r))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 sR=class{fold=new rR(iR,aR);async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:oR(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};function cR(e,t,n){return n.some(e=>e.call===t.call&&e.id===t.id&&e.status===t.to)?t.to===`closed`?e?.id===t.id?null:e:{id:t.id,phase:`prep`,epic:e?.id===t.id?e.epic:null,unread:null}:e}function lR(e,t,n){let r=[...e.claims,...t?.claims??[]],i=e=>n.includes(e.call),a=r.filter(i).reduce((e,n)=>cR(e,n,t?.said??[]),e.ticket),o=r.filter(e=>!i(e));if(a===null||t===void 0)return{claims:o,ticket:a};let s=t.sentinels??[],c=s.findLast(e=>e.kind===`state`&&e.id===a.id),l=s.findLast(e=>e.kind===`unreadable`);return{claims:o,ticket:{id:a.id,phase:t.phase??a.phase,epic:c?.kind===`state`?c.epic:a.epic,unread:l?.kind===`unreadable`?l.line:a.unread}}}const uR={ticket:null,claims:[],command:null,todos:[],pending:[],done:[]};function dR(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 fR(e,t){if(t.isSidechain)return e;let n=IL(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,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=dR(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos,...lR(n,r.lit,r.finished??[])}}function pR(e){return{ticket:e.ticket,command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>dR(e,t.name),[]),done:e.done}}var mR=class{fold=new rR(uR,fR);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(pR(n.value))}};function hR(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function gR(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function _R(e,t,n,r){return gR(O(hR(e,t,n,r)),n)}async function vR(e,t,n){return gR(await je(hR(e,t,n)),n)}const yR=e=>`${e.socket}\n${e.pane}`;var bR=class{names=new Map;asking=new WL;constructor(e=Date.now){this.now=e}getSessionName(e){let t=yR(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await vR(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const xR=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:$e.map(t=>e.env?.[t]??null)]);var SR=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=xR(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=xR(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function CR(e){return{gitProvider:new vC({watchers:e.watchers,logger:e.logger}),usageStore:new tR({logger:e.logger}),contextProvider:new nR,metricsProvider:new sR,activityProvider:new mR,tmuxService:new bR,mementoProvider:new SR(kF()),autoCompact:zT,log:e.logger}}function wR(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function TR(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function ER(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function DR({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function OR(e){let t=DR(e);if(t.length===1)return e.text;let n=TR(t);return n.style=e.text.style,n}function kR(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=TR(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:TR([d,...c],a)},...l.length>0&&{trail:TR([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(ER(u,n,p),[{text:u,...f}])}function AR(e,t){let n=()=>e.map(e=>({owner:OR(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=$N(e.map(OR),t).split(`
198
- `);if(i.length>1)return n();let a=Math.max(0,t.width-UN(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];ER(c,c.cellLength+a,n)}),n()}function jR(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=MR(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:jN(a.style)};if(e.style.link){i();let r=MR([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function MR(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>NR(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function NR(e,t){let n=e.copy();return n.style=t,n}function PR(e,t){if(e.look===void 0)throw Error(`${t} read the render's look before any render resolved one`);return e.look}function FR(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,IR(e,t,o,n,r,i));return i}function IR(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=xw(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=ew.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=xw(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=xw(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:zR(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:zR(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:XD(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:zR(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 LR(e){return e.kind===`do`?LR(e.head):e}function RR(e){switch(LR(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`ceiling`:case`slash`:case`do`:return!1}}function zR(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function BR(e,t){return e.has(t)?zx(e.read(t)):``}function VR(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function HR(e,t,n,r){let i=new W(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function UR(e,t){return Math.max(e.members.indexOf(BR(t,e.stateVar)),0)}function WR(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=BR(r,e.stateVar);return{effects:[{verb:Lj,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=BR(r,e.stateVar);return{effects:[{verb:Lj,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=BR(r,e.stateVar);return{effects:[{verb:Lj,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(UR(e,r)+1)%e.members.length];return{effects:[{verb:Lj,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Rj,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:zj,args:[VR(e.text,MS(r))]}],active:!1};case`open`:return{effects:[{verb:Bj,args:[VR(e.target,MS(r))]}],active:!1};case`persist-literal`:{let t=BR(r,e.stateVar);return{effects:[{verb:Wj,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=BR(r,e.stateVar);return{effects:[{verb:Wj,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(UR(e,r)+1)%e.members.length];return{effects:[{verb:Wj,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Gj,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Xj,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Qj,args:[i]}],active:!1};case`redo`:return{effects:[{verb:$j,args:[i]}],active:!1};case`back`:return{effects:[{verb:eM,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:tM,args:[i]}],active:!1};case`save`:return{effects:[{verb:Kj,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:qj,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Jj,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Yj,args:[i,VR(e.name,MS(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:rM,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:iM,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:oM,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:sM,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Zj,args:[i,e.key,xP(e.op)]}],active:!1};case`do`:{let a=WR(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>WR(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Zj,args:[i,e.key,xP(r)]}],active:!1}}}}function GR(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:Ud(`action "${e}"`,n,t.members.length,UR(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]}}function KR(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=GR(e,LR(r),t,i),{effects:s,active:c}=WR(r,a,o,i,BR(i,`session.id`));return HR(a,uM(s),c)}function qR(e){return{action:{fn:(t,...n)=>KR(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function JR(e,t){return HR(`✕`,uM([{verb:Lj,args:[BR(e,`session.id`),t,Bd]}]),!1)}function YR(e,t,n){return new H({bgcolor:L.fromRgba(t),color:L.fromRgba(nc(e,t,n))})}function XR({tint:e,text:t}){return new H({bgcolor:L.fromRgba(e),color:L.fromRgba(t)})}function ZR(e,t,n){return new H({color:L.fromRgba(Or(Ks(e,`warning`),t,tc,n))})}function QR(e,t,n){return H.combine([YR(e,t,n),ZR(e,t,n)])}function $R(e,t,n){return YR(e.palette,Sc(e.palette,e.disclosure,[t],n),n)}function ez(e,t,n,r,i,a){return r===void 0?n=>$R(e,{...n,distribution:t},i):(e,t)=>tz(r(t,n),a,i)}function tz(e,t,n){return new H({bgcolor:L.fromRgba(t),color:L.fromRgba(Or(Ks(e,`primary`),t,4.5,n))})}function nz(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=>rz(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function rz(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function iz(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function az(e){return{current:null,drawnAt:e}}function oz(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 sz(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 cz(e){return new W(e).cellLength}function lz(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function uz(e){return Math.max(1,lz(e)-(cz(`✕`)+2*e.padding+e.seamCols))}function dz(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 fz(e,t,n){let r=cz(`←`)+1+cz(`→`)+1,i=dz(e,t,n);return(i.length>1?dz(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function pz(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function mz(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function hz(e,t,n){let r=e.compiled.get(t),i=r&&LR(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 gz(e,t,n,r,i,a,o){let s=hz(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=BR(l,`session.id`),d=`stateVar`in s?BR(l,s.stateVar):void 0,f=r?n.kind===`led`?uz(i):lz(i):1/0,p=n.kind===`led`?0:cz(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?fz(s.options.map(cz),f,p):nz(m.entries,m.groups,r),g=parseInt(BR(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>uM([{verb:Lj,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:Lj,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>uM([...WR(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return HR(t,S(n),n===d,a({index:e,count:s.options.length},n))},ee=n.kind===`led`?[]:[HR(`✕`,uM(b),!1,o)];_>0&&ee.push(HR(`←`,y(_-1),!1));let w=_<h.length-1?[HR(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[pz([...ee,...e.map(e=>C(e,s.options[e])),...w],r)]}let te=new H({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[pz([...ee,...re,...w],r)];for(let e of v){v.length>1&&ie.push(pz([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>cz(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:CN(i),o=` `.repeat(t-cz(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(pz([C(n,iz(c,f))],r))}}return ie}function _z(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ES(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=mz(e,r,`set-int`,`an int action ({ set, int: true })`);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=hz(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=sz(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]=gz(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,ez(u,Ps(void 0),PR(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),ZR(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function vz(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+cz(e(-(s+1)))+1+cz(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function yz(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=n.store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=BR(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return pz([],!0);let d=BR(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=uM(WR(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>HR(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):HR(m(0),uM(WR(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=vz(m,u,cz(`◀`)+1+v.cellLength+1+cz(`▶`),uz(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return pz([...b(-1).reverse(),HR(`◀`,g(-1),!1),v,HR(`▶`,g(1),!1),...b(1)],!0)}function bz(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ES(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&RR(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=hz(e,n,`carousel`),l=sz(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return yz(n,c,e,ez(l,Ps(void 0),PR(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const xz=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function Sz(e,t,n,r){let i=mc(e,n,r),a=(t,n)=>({text:t,colour:n,ink:nc(e,n,r)});return[ks(t).map((n,i)=>{let a=qs(e,n);return{text:xz[i%xz.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}}),[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Ks(e,`warning`)),a(`error`,Ks(e,`error`))]]}function Cz(e,t,n,r,i){let a=Sz(e,t,n,r).flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:XR({tint:n,text:r})})}))),o=[],s=0;for(let{gap:e,cell:t}of a){if(s+=e.length+t.cellLength,s>i)break;e!==``&&o.push(new W(e)),o.push(t)}let c=W.fromFragments(o);return c.overflow=`ignore`,c.end=``,c}function wz(e,t){return{themePreview:{fn:()=>{let{palette:n,decor:r}=PR(e,`{{ themePreview }}`);return Cz(n,r,{...sz(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),uz(e))},argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const Tz=e=>e.slice(e.lastIndexOf(`.`)+1),Ez=(e,t)=>{let n=new W(Tz(e));return n.truncate(t,{marker:`…`}),n.plain};function Dz(e,t){let n=e.map(e=>e.map(({name:e})=>cz(Tz(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 Oz(e,t,n,r){let i=Dz(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${Ez(s,i)} `,{style:XR(Ec(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
199
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function kz(e,t){return{layoutPreview:{fn:()=>Oz(e.layout(),PR(e,`{{ layoutPreview }}`).decor,t.drawnAt(),uz(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function Az(e,t,n,r){let i=sz(r.activeSegment,`{{ menu }}`),a=r.action,o=Sb(i.placementId,e,n.key),s=Tb(o),c=xb(e),l=BR(a.store,o)===c,u=BR(a.store,`session.id`),d=l?Bd:c,f=HR(Ud(`{{ menu "${e}" }}`,t,2,+!!l),uM([{verb:Lj,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=mc(i.palette,i.disclosure,t).plane;return gz(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Bd],[s,`0`]],onPick:n.closeOnPick},n.paged,a,ez(i,n.distribution,PR(a,`{{ menu }}`),hz(a,e,`menu`).paletteOf,t,c),ZR(i.palette,c,t))})():[]),f}const jz=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Mz(e,t){let n=t[t.length-1],r=jz(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:kb(r??{})}}function Nz(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=Mz(t,n);return Az(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function Pz(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=Fz(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 W(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function Fz(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 Iz(e){let t={fn:(()=>{let t=sz(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:(()=>sz(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=sz(e,`{{ keptOn }}`),i=yr(r,t),a=yr(r,n),o=P(Ar(i,F.TRUECOLOR),Ar(a,F.TRUECOLOR)),s=Math.min(tc,Math.max(o,3));return(kr(i,e.drawnAt(),(e,t)=>P(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=fS(()=>sz(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...Lz(s)];return Pz({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function Lz(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function Rz(e){let t=[],n=[];for(let r of e){if(!r.contains(`
193
+ `,l.join(e,`lib`),t.sessionId,t.cwd],env:TF(t),timeoutMs:3e3,category:`memento.read`});return n.ok?DF(n.stdout):X(EF(n))}function kF(e,t,n){let r=O({bin:l.join(e,xF),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:TF(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(EF(r))}function AF(){return{locate:e=>wF(MT(e.claudeConfigDir),e.projectDir),read:OF,move:kF}}function jF(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${yM(n)} `,i=e.added_dirs.map(e=>` --add-dir ${yM(e)}`).join(``);return`cd ${yM(e.project_dir)} && ${r}claude --resume ${yM(t)}${i}`}function MF(e,t,n){let r=Pb(t(`preset`),e.globals.preset,e.presets),i=Lb(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=hw(a.palette,t(`theme`),i.palette),s=aF(i,iF(o,e.themeDefaults));return{preset:r,presetCustomized:n(r),theme:o,style:Uc(a.style,t(`style`),s.style,e.styles),effect:Yc(a.effect,t(`effect`),s.effect),endcaps:el(a.endcaps,t(`endcaps`),s.endcaps),variation:cl(a.variation,t(`variation`),s.variation),shade:dl(a.shade,t(`shade`),s.shade),separator:a.default_separator??s.default_separator,autoWrap:yl(a.autoWrap,t(`autoWrap`),s.autoWrap),padding:Sl(a.padding,t(`padding`),s.padding),charset:a.charset??s.charset??`unicode`,updateNotice:bl(a.updateNotice,t(`updateNotice`),s.updateNotice),transitions:xl(a.transitions,t(`transitions`),s.transitions),colorCompatibility:a.colorCompatibility??s.colorCompatibility??`truecolor`}}function NF(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function PF(e){return{theme:e.theme,style:e.style,effect:e.effect,preset:e.preset,variation:e.variation,shade:e.shade,transitions:e.transitions}}function FF(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:nF(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},shade:{effective:e.shade},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice},transitions:{effective:e.transitions}}}const IF=10*1e3;function LF(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function RF(e,t){if(!(t<60))return e*3600/t}function zF(e,t,n,r){let i=r-t;if(i<50||i>IF)return;let a=n-e;if(!(a<=0))return a*1e3/i}function BF(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=zF(t.input,t.atMs,n.input,n.atMs),i=zF(t.output,t.atMs,n.output,n.atMs),a=zF(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 VF(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>IF)continue;let o=zF(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function HF(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function UF(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>HF(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function WF(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>Cx(t,e.helpers).keys(),o=Lb(e,t);for(let e of Ic){let t=o[e];if(Lc(t))for(let e of a(t))r.push(e)}for(let n of wu(Ib(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of KF(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function GF(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=WF(e,n);return t.set(n,i),i}}function KF(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function qF(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function JF(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function YF(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>qF(i,e),u=TC(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[p,m,h,g,_,v,y,b,x,S,C]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,JF(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(Y):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>gF(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(yF({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(jT(AT(o.claudeConfigDir)))))]),ee=[],w=e=>{if(e.kind===`failed`){ee.push(e.reason);return}return e.kind===`ok`?e.value:void 0},te=rI(p,u);ee.push(...te.failures);let ne=UF(o);ee.push(...ne.failures);let re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=w(b),ce=QF(S);S.kind===`failed`&&ee.push(`memento: ${S.reason}`);let le=XF(C,T?.maxTokens);C.kind===`failed`&&ee.push(`autocompact: ${C.reason}`);for(let e of ee)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?LF(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?LF(de.used_percentage,de.resets_at,6048e5,u):void 0,me=re?.session.cost,he=E?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?RF(me,he):void 0,_e=w(x),ve=_e===void 0?void 0:BF(_e),ye=_e===void 0?void 0:VF(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,D=nI(process.env.HOME??process.env.USERPROFILE),xe=e.workspace?{...e.workspace,current_dir:nI(e.workspace.current_dir)??``,project_dir:nI(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>nI(e)??e)}:e.workspace,Se=re===void 0?void 0:tI({cost:re.session.cost,tokens:re.session.tokens}),Ce=ie===void 0?void 0:{cost:ie.cost,tokens:ie.tokens},we=E===void 0?void 0:tI({lastResponseTime:E.lastResponseTime,responseTime:E.responseTime,sessionDuration:E.sessionDuration,messageCount:E.messageCount,linesAdded:E.linesAdded,linesRemoved:E.linesRemoved}),Te=ae===void 0?void 0:$F(ae);return{...e,...xe!==void 0&&{workspace:xe},...D!==void 0&&{home:D},...te.git!==void 0&&{git:te.git},...d!==null&&{tmux:{pane:d.pane,...oe!==void 0&&{session:oe}}},host:ne.host,...FF(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},...c,...s!==null&&{configPath:s},resumeCommand:jF(xe,e.session_id,o.claudeConfigDir),...Se!==void 0&&{session:Se},...Ce!==void 0&&{today:Ce},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...T!==void 0&&{context:{totalTokens:T.totalTokens,contextLeft:T.contextLeftPercentage}},...we!==void 0&&{metrics:we},...Te!==void 0&&{activity:Te},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function XF(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return VT(e.value,t)}}const ZF=e=>e.trim().split(`
194
+ `).at(-1).trim();function QF(e){switch(e.kind){case`absent`:return;case`failed`:return{error:ZF(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function $F(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=eI(e.running),i=eI(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}},o=e.ticket===null?void 0:{id:e.ticket.id,phase:e.ticket.phase,...e.ticket.epic!==null&&{epic:e.ticket.epic},...e.ticket.unread!==null&&{unread:e.ticket.unread}};if(!(o===void 0&&e.command===null&&n===void 0&&a===void 0))return{...o!==void 0&&{ticket:o},...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function eI(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function tI(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 nI(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function rI(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=i(`repoName`,n.repoName),p=i(`repoUrl`,n.repoUrl),m=n.pullRequest,h={};return m?.kind===`ok`?(h.prNumber=m.value.number,h.prState=m.value.state,h.prUrl=m.value.url):m?.kind===`failed`&&(r.push(`git.pr: ${m.reason}`),h.prError=m.reason),{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{repoName:f},...p!==void 0&&{repoUrl:p},...h},failures:r}}const iI={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,effect:e=>e.effect.kind===`decided`?e.effect.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,shade:e=>e.shade,transitions:e=>e.transitions?fl:pl,autoWrap:e=>e.autoWrap?fl:pl,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?fl:pl},aI=Object.entries(ZC),oI=new Set(QC.map(e=>e.sessionKey)),sI=()=>!1;function cI(e,t){return MF(e,e=>oI.has(e)?t(e):null,sI)}const lI=[`preset`,`theme`];function uI(e,t,n){let r=new Set(lI.slice(0,n).map(e=>ZC[e].sessionKey));return MF(e,e=>r.has(e)?t(e):null,sI)}function dI(e,t){let n=Array.from({length:lI.length+1},(n,r)=>uI(e,t,r));return e=>{let t=lI.indexOf(e);return n[t===-1?lI.length:t]}}function fI(e,t,n,r){return e.flatMap(([e,i])=>{let a=iI[e](t);return a===null||a===iI[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function pI(e,t,n){return iI[n](cI(e,t))}function mI(e,t){let n=cI(e,t);return fI(aI,n,dI(e,t),t=>hI(e,n.preset,t.configKey))}function hI(e,t,n){return n in(Fb(e.presets,t).globals??{})?Rw(t,n):n}function gI(e,t,n){let r=Pb(t(ZC.preset.sessionKey),e.globals.preset,e.presets),i=zw(n);return{key:i?.scope===`globals`?hI(e,r,i.field):n,globals:Lb(e,r)}}function _I(e,t){let{preset:n}=cI(e,t);return bI(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Hu(a,s);return c===void 0||Vu(c)===Vu(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function vI(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Nb(e.presets).flatMap(n=>{let i=bI(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 zu(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:Hu(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const yI=new WeakMap;function bI(e,t){let n=yI.get(e)??new Map;yI.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...wu(Ib(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Lu(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 xI(e,t){let n=cI(e,t);return{from:n.preset,globals:Fb(e.presets,n.preset).globals??{},picks:fI(aI.filter(([e])=>e!==`preset`),n,dI(e,t),e=>e.configKey),placements:_I(e,t)}}function SI(e,t){return MF({...e,globals:{palette:t},presets:{}},()=>null,sI)}function CI(e,t){let n=cI(e,t),r=iI.theme(n);if(r===null)return{kind:`rule`};let i=SI(e,r),a=Lb(e,n.preset),o=Object.fromEntries(ku.map(e=>[e,iI[e](a[e]===void 0?n:i)]));return{kind:`look`,theme:r,look:o,differs:ku.some(e=>o[e]!==iI[e](i))}}function wI(e){return{sessionKeys:QC.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...xf(e)?tF.map(t=>Rw(t,e)):[],...Lw(e)?jc().map(t=>Iw(t,e)):[]]}}function TI(e){return new Set(QC.map(e=>e.configKey).filter(t=>wI(t).fileKeys.some(t=>OI(e,DI(t)))))}function EI(e,t,n){let r=mI(e,n),i=new Set(r.map(e=>e.configKey)),a=rw(e=>i.has(ZC[e].configKey)||t.has(ZC[e].configKey)),o=CI(e,n);return{unsaved:r.length+_I(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function DI(e){let t=zw(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return Bw(t)}function OI(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&OI(e[n],r)}const kI=jc(),AI=new Set(kI),jI=new Set(Xc),MI=e=>e?AI.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${kI.join(`, `)})`}:{ok:!1,reason:`theme name is required`},NI=e=>e?jI.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Xc.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},PI=new Set([`1`,`true`]),FI=new Set([`0`,`false`]),II={endcaps:NI,theme:MI,"toolbar-expanded":e=>PI.has(e)?{ok:!0,value:`1`}:FI.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},LI=PP(II,`state`,WI);function RI(e,t){return LI.register(e,t)}function zI(e){return LI.gateFor(e)}function BI(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:Sw(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 VI(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(II,e.key))}function HI(e,t,n){let r=iw.get(n);if(r!==void 0)return pI(e,t,r);let i=Object.values(e.variables).find(e=>e.kind===`state`&&e.key===n);return i?.kind===`state`?i.default??null:null}function UI(e){let t=jD(e);return VI(Object.values(e.actions).flatMap(e=>BI(e,t)))}function WI(e){return MP(UI(e))}const GI=`update.dismissed`,KI=`updateNotice`,qI=ZC.updateNotice.sessionKey;function JI(e){return e.kind===`source`?e.newer.digest:SM(e.newer)}const YI=e=>`${e.version} [${_P(e.digest)}]`;function XI(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:YI(e.newer),running:YI(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:SM(e.newer),running:SM(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${wM}@${SM(e.newer)}`,`install`]}}}}const ZI={kind:`idle`},QI={kind:`running`};function $I(e,t,n){if(e===null)return[];let r=JI(e);if(!n.enabled||n.dismissed===r)return[];let i=XI(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(`
195
+ `),c=dM([{verb:Wj,args:[s]}]),l=t.kind===`running`?aP(`[${i.busy}]`,c):aP(`[${i.act}]`,dM([{verb:rM,args:[n.sessionId]}]));return[{severity:iP,message:s,lines:[[aP(a,c),l,aP(`[dismiss]`,dM([{verb:Rj,args:[n.sessionId,GI,r]}])),aP(`[disable]`,dM([{verb:Gj,args:[n.sessionId,KI,`false`]},{verb:Rj,args:[n.sessionId,qI,`false`]}]))],...o.map(e=>[aP(e,c)])]}]}function eL(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function tL(e){switch(e.kind){case`current`:return[`info`,`build: current ${YI(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${YI(e.source)}, running ${YI(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function nL(e){switch(e.kind){case`current`:return[`info`,`release: current ${SM(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${SM(e.latest)}, running ${SM(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${SM(e.installed)}, latest ${SM(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function rL(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const iL=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function aL(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=iL(e.stderr)??e.error??iL(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function oL(){let e=[IP(KI,[`false`]),RI(qI,[`false`]),RI(GI,[])];return()=>e.forEach(e=>e())}function sL(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=ZI,d=null,f=rL(s),p=rL(s),m=()=>eL(c,l);function h(){let e=m(),t=e===null?null:JI(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:RI(GI,[t])})}function g(){c=xP(t,yP),f(tL(c)),h()}async function _(){l=EM(JA,await TM(wM,a,i)),p(nL(l)),h()}return{arm(){oL(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>$I(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=XI(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=QI,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),je({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=ZI,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=aL(n);u={kind:`failed`,identity:JI(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var cL=class{static CACHE_DIR=Le();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return D(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ue(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return se(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){D(`Cache for ${e} is locked, waiting...`),await ue(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ue(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const lL={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var uL=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await cL.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await cL.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ie(this.GITHUB_PRICING_URL),n=le({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(lL).length} models`),this.executionCache=lL,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(lL).length} models`),lL)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const dL=String.raw`(?:^|[\s;&|(])`,fL=e=>RegExp(`(?:^|:)(?:${e})$`),pL=[{phase:`impl`,tool:`Edit`,match:/^/},{phase:`impl`,tool:`MultiEdit`,match:/^/},{phase:`impl`,tool:`Write`,match:/^/},{phase:`impl`,tool:`NotebookEdit`,match:/^/},{phase:`review`,tool:`Bash`,match:RegExp(`${dL}gh\\s+pr\\s+create\\b`)},{phase:`review`,tool:`Skill`,match:fL(`code-review|simplify`)},{phase:`groom`,tool:`Bash`,match:RegExp(`${dL}lit\\s+(done|close)\\b`)},{phase:`groom`,tool:`Skill`,match:fL(`groom-backlog`)},{phase:`handoff`,tool:`Skill`,match:fL(`message-in-a-bottle`)}],mL=e=>RegExp(`${dL}lit\\s+(?:${e})(?:\\s+(?:--?[\\w-]+(?:=\\S*)?|''))*\\s+([A-Za-z0-9][\\w.-]*)`),hL=[{verb:mL(`start`),to:`in_progress`},{verb:mL(`done|close`),to:`closed`}];function gL(e){return pL.find(t=>t.tool===e.tool&&t.match.test(e.subject))?.phase}function _L(e,t){if(t.tool===`Bash`)for(let{verb:n,to:r}of hL){let i=n.exec(t.subject)?.[1];if(i!==void 0)return{call:e,id:i,to:r}}}const vL=/^lit:state (.*)$/gm;function yL(e){return[...e.matchAll(vL)].map(([e,t])=>bL(t)??{kind:`unreadable`,line:e.trim()})}function bL(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{id:n,status:r,epic:i}=t;if(typeof n!=`string`||typeof r!=`string`)return;if(i===null)return{kind:`state`,id:n,status:r,epic:null};if(typeof i!=`object`||i===void 0)return;let a=i;if(!(typeof a.id!=`string`||typeof a.done!=`number`||typeof a.total!=`number`))return{kind:`state`,id:n,status:r,epic:{id:a.id,done:a.done,total:a.total}}}function xL(e,t){let n=t??{};return{tool:e,subject:e===`Bash`&&typeof n.command==`string`?wL(n.command):e===`Skill`&&typeof n.skill==`string`?n.skill:e}}const SL=/(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)[\s\S]*?\n\s*\3(?=\n|$)/g,CL=/'[^']*'|"(?:[^"\\]|\\.)*"/g;function wL(e){return e.replace(SL,`$1`).replace(CL,`''`)}function TL(e){return typeof e==`string`?[e]:Array.isArray(e)?e.flatMap(e=>typeof e==`object`&&e&&typeof e.text==`string`?[e.text]:[]):[]}const EL=/^(\S+) \[(open|in_progress|closed)\//gm,DL=/^Ticket (\S+) has been closed\./gm,OL={sentinels:[],said:[]};function kL(e){let t;for(let n of TL(e)){let e=n.includes(`lit:state `),r=n.includes(` [`),i=n.includes(`has been closed.`);if(!(!e&&!r&&!i)){if(t??={sentinels:[],said:[]},e&&t.sentinels.push(...yL(n)),r)for(let[,e,r]of n.matchAll(EL))t.said.push({id:e,status:r});if(i)for(let[,e]of n.matchAll(DL))t.said.push({id:e,status:`closed`})}}if(t===void 0)return OL;for(let e of t.sentinels)e.kind===`state`&&t.said.push({id:e.id,status:e.status});return t}const AL=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function jL(e){if(typeof e==`string`)return AL.exec(e)?.[1]}function ML(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 NL(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o,s=[],c=[],l,u=[];if(typeof t==`string`)o=t;else if(Array.isArray(t))for(let e of t){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});let i=xL(n,t.input),o=_L(e,i);o!==void 0&&s.push(o),l=gL(i)??l,n===`TodoWrite`&&(a=ML(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id,n=kL(t.content);if(u.push(...n.sentinels),typeof e==`string`){i.push(e);for(let t of n.said)c.push({call:e,...t})}break}case`text`:o??=t.text;break;default:break}}let d=n?jL(o):void 0,f=s.length===0&&l===void 0&&u.length===0&&c.length===0?void 0:{...s.length>0&&{claims:s},...l!==void 0&&{phase:l},...u.length>0&&{sentinels:u},...c.length>0&&{said:c}};if(!(r.length===0&&i.length===0&&a===void 0&&d===void 0&&f===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...d!==void 0&&{command:d},...f!==void 0&&{lit:f}}}function PL(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function FL(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await lF(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function IL(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await lF(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await uF(t,`utf-8`)).split(`
196
+ `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function LL(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}const RL=new Map;async function zL(e){try{let t=await dF(e),n=t.size,r=RL.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),RL.delete(e),RL.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await WL(e)):i=await HL(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(RL.delete(e),RL.size>=16&&RL.delete(RL.keys().next().value),RL.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function BL(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;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,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,activity:NL(e),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 VL(e){let t=[];for(let n of e.split(`
197
+ `))if(n.trim())try{let e=BL(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function HL(e){return VL(await uF(e,`utf-8`))}async function UL(e,t){let n=await fF(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return J(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:VL(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function WL(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=de({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=BL(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var GL=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 KL(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 qL=new Map,JL={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},YL={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function XL(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function ZL(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function QL(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function $L(e,t,n,r){let i=XL(new Date(ZL())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:QL(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await uL.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=XL(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...JL};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function eR(e){let t=0,n=0,r=QL(),i=new Map;for(let 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)??{...JL};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:YL,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function tR(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var nR=class{entries=new Map;flight=new GL;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new GL;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??uC,this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:YL,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=XL(TC(n)),i=PL(t);try{await this.ensureSeeded(r,i)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path);if(a.kind===`failed`)return a;let o=i.map(e=>p(e,`projects`)+m),s={...JL},c=!1;for(let[t,n]of this.entries){let i=n.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n.days:qL;c||=a.has(r);let l=a.get(r)??JL;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?J({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):Y}async observeSpeed(e,t,n){let r=oF(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=KL(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),J({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Y;let r=n??oF(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,J(i);if(!t)return i?J(i):Y;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return X(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),J(o)}async refold(e,t,n){let r=await IL(e,d(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await UL(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await $L(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...eR(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=ZL(),n=await FL(e),r=[];for(let e of n){let n;try{n=await lF(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=p(e,i),a;try{a=(await dF(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await tR(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},rR=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await zL(e);if(n.length===0)return D(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},iR=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=oF(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await UL(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const aR={messageCount:0,recent:[]};function oR(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!LL(t),recent:n.length>20?n.slice(-20):n}}function sR(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(LL(r))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 cR=class{fold=new iR(aR,oR);async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:sR(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};function lR(e,t,n){return n.some(e=>e.call===t.call&&e.id===t.id&&e.status===t.to)?t.to===`closed`?e?.id===t.id?null:e:{id:t.id,phase:`prep`,epic:e?.id===t.id?e.epic:null,unread:null}:e}function uR(e,t,n){let r=[...e.claims,...t?.claims??[]],i=e=>n.includes(e.call),a=r.filter(i).reduce((e,n)=>lR(e,n,t?.said??[]),e.ticket),o=r.filter(e=>!i(e));if(a===null||t===void 0)return{claims:o,ticket:a};let s=t.sentinels??[],c=s.findLast(e=>e.kind===`state`&&e.id===a.id),l=s.findLast(e=>e.kind===`unreadable`);return{claims:o,ticket:{id:a.id,phase:t.phase??a.phase,epic:c?.kind===`state`?c.epic:a.epic,unread:l?.kind===`unreadable`?l.line:a.unread}}}const dR={ticket:null,claims:[],command:null,todos:[],pending:[],done:[]};function fR(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 pR(e,t){if(t.isSidechain)return e;let n=LL(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,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=fR(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos,...uR(n,r.lit,r.finished??[])}}function mR(e){return{ticket:e.ticket,command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>fR(e,t.name),[]),done:e.done}}var hR=class{fold=new iR(dR,pR);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(mR(n.value))}};function gR(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function _R(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function vR(e,t,n,r){return _R(O(gR(e,t,n,r)),n)}async function yR(e,t,n){return _R(await je(gR(e,t,n)),n)}const bR=e=>`${e.socket}\n${e.pane}`;var xR=class{names=new Map;asking=new GL;constructor(e=Date.now){this.now=e}getSessionName(e){let t=bR(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await yR(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const SR=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:$e.map(t=>e.env?.[t]??null)]);var CR=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=SR(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=SR(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function wR(e){return{gitProvider:new yC({watchers:e.watchers,logger:e.logger}),usageStore:new nR({logger:e.logger}),contextProvider:new rR,metricsProvider:new cR,activityProvider:new hR,tmuxService:new xR,mementoProvider:new CR(AF()),autoCompact:BT,log:e.logger}}function TR(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function ER(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function DR(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function OR({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function kR({text:e,placement:t,lead:n,trail:r}){return{text:AR(e),placement:t,...n!==void 0&&{lead:AR(n)},...r!==void 0&&{trail:AR(r)}}}function AR(e){let t=e.blankCopy(e.plain);t.style=MN(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(MN(i).clearMetaAndLinks(),n,r);return t}function jR(e){let t=OR(e);if(t.length===1)return e.text;let n=ER(t);return n.style=e.text.style,n}function MR(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=ER(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:ER([d,...c],a)},...l.length>0&&{trail:ER([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(DR(u,n,p),[{text:u,...f}])}function NR(e,t){let n=()=>e.map(e=>({owner:jR(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=eP(e.map(jR),t).split(`
198
+ `);if(i.length>1)return n();let a=Math.max(0,t.width-WN(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];DR(c,c.cellLength+a,n)}),n()}function PR(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=FR(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:MN(a.style)};if(e.style.link){i();let r=FR([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function FR(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>IR(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function IR(e,t){let n=e.copy();return n.style=t,n}function LR(e,t){if(e.look===void 0)throw Error(`${t} read the render's look before any render resolved one`);return e.look}function RR(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,zR(e,t,o,n,r,i));return i}function zR(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=Sw(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=tw.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=Sw(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Sw(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:HR(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:HR(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:ZD(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:HR(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 BR(e){return e.kind===`do`?BR(e.head):e}function VR(e){switch(BR(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`ceiling`:case`slash`:case`do`:return!1}}function HR(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function UR(e,t){return e.has(t)?Bx(e.read(t)):``}function WR(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function GR(e,t,n,r){let i=new W(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function KR(e,t){return Math.max(e.members.indexOf(UR(t,e.stateVar)),0)}function qR(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=UR(r,e.stateVar);return{effects:[{verb:Rj,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=UR(r,e.stateVar);return{effects:[{verb:Rj,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=UR(r,e.stateVar);return{effects:[{verb:Rj,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(KR(e,r)+1)%e.members.length];return{effects:[{verb:Rj,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zj,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Bj,args:[WR(e.text,NS(r))]}],active:!1};case`open`:return{effects:[{verb:Vj,args:[WR(e.target,NS(r))]}],active:!1};case`persist-literal`:{let t=UR(r,e.stateVar);return{effects:[{verb:Gj,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=UR(r,e.stateVar);return{effects:[{verb:Gj,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(KR(e,r)+1)%e.members.length];return{effects:[{verb:Gj,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Kj,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Zj,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:$j,args:[i]}],active:!1};case`redo`:return{effects:[{verb:eM,args:[i]}],active:!1};case`back`:return{effects:[{verb:tM,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:nM,args:[i]}],active:!1};case`save`:return{effects:[{verb:qj,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Jj,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Yj,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Xj,args:[i,WR(e.name,NS(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:iM,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:aM,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:sM,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:cM,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Qj,args:[i,e.key,SP(e.op)]}],active:!1};case`do`:{let a=qR(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>qR(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Qj,args:[i,e.key,SP(r)]}],active:!1}}}}function JR(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:Ud(`action "${e}"`,n,t.members.length,KR(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]}}function YR(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=JR(e,BR(r),t,i),{effects:s,active:c}=qR(r,a,o,i,UR(i,`session.id`));return GR(a,dM(s),c)}function XR(e){return{action:{fn:(t,...n)=>YR(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function ZR(e,t){return GR(`✕`,dM([{verb:Rj,args:[UR(e,`session.id`),t,Bd]}]),!1)}function QR(e,t,n){return new H({bgcolor:L.fromRgba(t),color:L.fromRgba(nc(e,t,n))})}function $R({tint:e,text:t}){return new H({bgcolor:L.fromRgba(e),color:L.fromRgba(t)})}function ez(e,t,n){return new H({color:L.fromRgba(Or(Ks(e,`warning`),t,tc,n))})}function tz(e,t,n){return H.combine([QR(e,t,n),ez(e,t,n)])}function nz(e,t,n){return QR(e.palette,Sc(e.palette,e.disclosure,[t],n),n)}function rz(e,t,n,r,i,a){return r===void 0?n=>nz(e,{...n,distribution:t},i):(e,t)=>iz(r(t,n),a,i)}function iz(e,t,n){return new H({bgcolor:L.fromRgba(t),color:L.fromRgba(Or(Ks(e,`primary`),t,4.5,n))})}function az(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=>oz(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function oz(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function sz(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function cz(e){return{current:null,drawnAt:e}}function lz(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 uz(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 dz(e){return new W(e).cellLength}function fz(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function pz(e){return Math.max(1,fz(e)-(dz(`✕`)+2*e.padding+e.seamCols))}function mz(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 hz(e,t,n){let r=dz(`←`)+1+dz(`→`)+1,i=mz(e,t,n);return(i.length>1?mz(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function gz(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function _z(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function vz(e,t,n){let r=e.compiled.get(t),i=r&&BR(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 yz(e,t,n,r,i,a,o){let s=vz(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=UR(l,`session.id`),d=`stateVar`in s?UR(l,s.stateVar):void 0,f=r?n.kind===`led`?pz(i):fz(i):1/0,p=n.kind===`led`?0:dz(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?hz(s.options.map(dz),f,p):az(m.entries,m.groups,r),g=parseInt(UR(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>dM([{verb:Rj,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:Rj,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>dM([...qR(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return GR(t,S(n),n===d,a({index:e,count:s.options.length},n))},ee=n.kind===`led`?[]:[GR(`✕`,dM(b),!1,o)];_>0&&ee.push(GR(`←`,y(_-1),!1));let w=_<h.length-1?[GR(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[gz([...ee,...e.map(e=>C(e,s.options[e])),...w],r)]}let te=new H({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[gz([...ee,...re,...w],r)];for(let e of v){v.length>1&&ie.push(gz([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>dz(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:wN(i),o=` `.repeat(t-dz(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(gz([C(n,sz(c,f))],r))}}return ie}function bz(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{DS(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=_z(e,r,`set-int`,`an int action ({ set, int: true })`);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=vz(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=uz(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]=yz(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,rz(u,Ps(void 0),LR(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),ez(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function xz(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+dz(e(-(s+1)))+1+dz(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function Sz(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=n.store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=UR(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return gz([],!0);let d=UR(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=dM(qR(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>GR(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):GR(m(0),dM(qR(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=xz(m,u,dz(`◀`)+1+v.cellLength+1+dz(`▶`),pz(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return gz([...b(-1).reverse(),GR(`◀`,g(-1),!1),v,GR(`▶`,g(1),!1),...b(1)],!0)}function Cz(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(DS(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&VR(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=vz(e,n,`carousel`),l=uz(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return Sz(n,c,e,rz(l,Ps(void 0),LR(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const wz=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function Tz(e,t,n,r){let i=mc(e,n,r),a=(t,n)=>({text:t,colour:n,ink:nc(e,n,r)});return[ks(t).map((n,i)=>{let a=qs(e,n);return{text:wz[i%wz.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}}),[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Ks(e,`warning`)),a(`error`,Ks(e,`error`))]]}function Ez(e,t,n,r,i){let a=Tz(e,t,n,r).flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:$R({tint:n,text:r})})}))),o=[],s=0;for(let{gap:e,cell:t}of a){if(s+=e.length+t.cellLength,s>i)break;e!==``&&o.push(new W(e)),o.push(t)}let c=W.fromFragments(o);return c.overflow=`ignore`,c.end=``,c}function Dz(e,t){return{themePreview:{fn:()=>{let{palette:n,decor:r}=LR(e,`{{ themePreview }}`);return Ez(n,r,{...uz(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),pz(e))},argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const Oz=e=>e.slice(e.lastIndexOf(`.`)+1),kz=(e,t)=>{let n=new W(Oz(e));return n.truncate(t,{marker:`…`}),n.plain};function Az(e,t){let n=e.map(e=>e.map(({name:e})=>dz(Oz(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 jz(e,t,n,r){let i=Az(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${kz(s,i)} `,{style:$R(Ec(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
199
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function Mz(e,t){return{layoutPreview:{fn:()=>jz(e.layout(),LR(e,`{{ layoutPreview }}`).decor,t.drawnAt(),pz(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function Nz(e,t,n,r){let i=uz(r.activeSegment,`{{ menu }}`),a=r.action,o=Cb(i.placementId,e,n.key),s=Eb(o),c=Sb(e),l=UR(a.store,o)===c,u=UR(a.store,`session.id`),d=l?Bd:c,f=GR(Ud(`{{ menu "${e}" }}`,t,2,+!!l),dM([{verb:Rj,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=mc(i.palette,i.disclosure,t).plane;return yz(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Bd],[s,`0`]],onPick:n.closeOnPick},n.paged,a,rz(i,n.distribution,LR(a,`{{ menu }}`),vz(a,e,`menu`).paletteOf,t,c),ez(i.palette,c,t))})():[]),f}const Pz=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fz(e,t){let n=t[t.length-1],r=Pz(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:Ab(r??{})}}function Iz(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=Fz(t,n);return Nz(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function Lz(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=Rz(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 W(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function Rz(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 zz(e){let t={fn:(()=>{let t=uz(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:(()=>uz(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=uz(e,`{{ keptOn }}`),i=yr(r,t),a=yr(r,n),o=P(Ar(i,F.TRUECOLOR),Ar(a,F.TRUECOLOR)),s=Math.min(tc,Math.max(o,3));return(kr(i,e.drawnAt(),(e,t)=>P(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=pS(()=>uz(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...Bz(s)];return Lz({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function Bz(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function Vz(e){let t=[],n=[];for(let r of e){if(!r.contains(`
200
200
  `)){n.push(r);continue}let e=r.split(`
201
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function zz(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function Bz(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,...Vz(e,r)]}function Vz(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 Hz(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:Bz(e.direction,e.children.map((t,i)=>n(t,[...r,Uz(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function Uz(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:yu[e.direction]}}const Wz={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ps(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,Tu(t.path,n)))}},render(e,t){return Bz(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,Uz(e,r))))}},Gz={drop:e=>e.place,above:()=>`above`},Kz={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},qz={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:bu(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Kd(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Eu(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=PS(t.scope,e.settings);try{if(!wR(i.when,a))return[];let n=cw(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:Ww(n)},s=e.opens!==void 0&&wR(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:Gz[g.placement](e)})),v=Rz(jR(l,m)).map((e,t)=>({cells:kR(e,{...h,lead:t===0?jR(u,m):[],trail:t===0?jR(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:kR(jR([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>kR(jR([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),x=_.findIndex(e=>e.band===`own`),{lead:S,stays:C}=g!==void 0&&x!==-1?Kz[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},ee=S.flatMap(e=>b(new W(` `.repeat(DR(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=_.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),..._.flatMap(w)].flatMap(DR)),[...ne,...te]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:kR([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Ww(t.palette)},lead:Jz(e.lead,e,a,t),trail:Jz(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}};function Jz(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const Yz={container:Wz,segment:qz};function Xz(e){return Yz[e]}function Zz(e){if(`ttl`in e)return{kind:`ttl`,durationMs:EC(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 Qz(e,t){switch(Au(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 $z(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:Zz(n.cache),parse:Qz(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:Zz(n.cache),parse:Qz(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function eB(e,t){let n=$m.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}const tB=(e,t,n,r,i)=>{let a=iF(t,rF(n,e.themeDefaults));return{variation:Os[r??cl(void 0,null,a.variation)],shade:Es[i??dl(void 0,null,a.shade)]}};function nB(e,t,n){let r=n.cwd,i={store:t.variableStore,compiled:new Map,chromeCols:ZN({endcaps:`powerline`,charset:rl}),width:80,padding:1,seamCols:QN({endcaps:`powerline`,charset:rl}),layout:()=>[],look:void 0},a=az(t.drawnAt),o={action:i,activeSegment:a},s=Object.keys(e.styles),c=Mb(e.presets),l=AD(e),u=jS({extraFuncs:{...qR(i),..._z(i,a),...bz(i,a),...wz(i,a),...kz(i,a),...Nz(o),...Iz(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:t.now,drawnAt:t.drawnAt}),d=eB(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map;for(let[t,n]of tw)n in e.variables&&h.set(t,n);for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!h.has(n.key)&&h.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!h.has(r.key)&&h.set(r.key,`${t}.${e}`);i.compiled=FR(f,e.actions,h,l);let g=[];for(let[n,i]of Object.entries(e.variables))try{$z(t,n,i,r)}catch(e){g.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{$z(t,`${n}.${e}`,a,r)}catch(t){g.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let _=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};_[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let v=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},y=t.variableStore,b=t=>{let n=Lu(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Uu(t,e,i,e=>String(y.read(e.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:v(e.when,t,`when`),parse:(e,n)=>v(e,t,n),compileChild:x,placementSettings:b};return Xz(e.kind).compile(e,n)},S=new Map;for(let t of c){let{node:n,path:r}=Fb(e,t);S.set(t,x(n,r))}let C=new Map(Ic.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of Ic){let r=t[n];if(!Lc(r))continue;let i=`${e}.${n}`,a=C.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:rB(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:_,roots:S,activeSegment:a,menuRuntime:o,globalExpressions:C,loadWarnings:g}}function rB(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function iB(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function aB(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function oB(e,t){return e.kind===`decided`?e.name:t}function sB(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u,onRenderWarning:d}=s??{},f=new Set;r.renderAt(a),r.drawAt(al(o.colorCompatibility));let{preset:p=Ab}=c??{},m=Ib(e,p),h=c?.style??Hc(`none`,e.styles),g=c?.theme??mw(void 0,null,m.palette),_=tB(e,m,g,c?.variation,c?.shade),v=c?.effect??Yc(void 0,null,m.effect),y=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(y(oB(g,kc),oB(h,Bc),oB(v,Wc))),t.menuRuntime.action.chromeCols=ZN(o),t.menuRuntime.action.padding=o.padding,t.menuRuntime.action.width=o.width,t.menuRuntime.action.seamCols=QN(o);let b=MS(n),x=zc(g,e=>{let n=iB(t,`palette`,e);return pw(aB(n,b),n.where,e=>d?.({kind:`theme-rule`,message:e}))}),S=zc(h,n=>Hc(aB(iB(t,`style`,n),b),e.styles)),C=zc(v,e=>Jc(aB(iB(t,`effect`,e),b)));(x!==g||S!==h||C!==v)&&r.applyInput(y(x.name,S.name,C.name));let ee=x.value,w=uw(ee,S.value);t.menuRuntime.action.look={basePalette:ee,palette:w,decor:_};let te=(c?.effects??new VN(``)).motion(C.value,a,{transitions:c?.transitions??xl(void 0,null,m.transitions),source:{config:t,preset:p,revision:r.stateRevision()}});l?.clear();let ne=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},re=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Ec(i,a,c),p=oz(t.activeSegment,e.name,e.id,i,d,l,u),m=Kw(p,c,o.bg,o.fg,n),h=()=>mc(i,d,c);s&&(p.bg=h().state);let g=o.body.evaluate(n),_=p.drops.length>0||s;if(_){let e=h();p.bg=e.state;for(let t of e.shortfalls)f.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:m,get trigger(){return YR(i,h().state,c)},get band(){return YR(i,h().plane,c)},get close(){return QR(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:p.drops,open:_}}finally{t.activeSegment.current=null}},ie=(e,t,r)=>{let i=t&&wR(e.when,b),a={scope:b,palette:w,visible:i,padding:o.padding,region:r,perSegmentSink:l,onSegmentError:u,evaluateSegment:re,lookupSegment:ne,renderChild:(e,t,n)=>ie(e,t,wc(r,n)),renderBody:(e,t,n)=>ie(e,i&&t,Tc(n)),closeDisclosure:e=>JR(n,e)};return Xz(e.kind).render(e,a)},T=t.roots.get(p);if(T===void 0)throw Error(`Preset "${p}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Ab}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let E=e=>{if(!wR(e.when,b))return!1;if(e.kind===`container`)return!0;if(VD(e.name)===void 0)return!1;try{return wR(t.segments[e.name].when,PS(b,e.settings))}catch{return!0}};t.menuRuntime.action.layout=()=>Hz(T,E).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=VD(e);return r===void 0?[]:[{name:r,address:t,palette:cw(n.theme,w)}]}));let ae=zz(ie(T,!0,Cc(_))).map(({line:e,row:t})=>{let n=AR(e.cells,o);return $N(n.map(e=>e.owner),o,te.row(t,n))}).join(`
202
- `);te.drawn();for(let e of f)d?.({kind:`band-floor`,message:e});return ae}function*cB(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*lB(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of Mb(e.presets)){for(let n of wu(Fb(e,t).node))n.when!==void 0&&(yield n.when);let n=Ib(e,t);for(let e of Ic){let t=n[e];Lc(t)&&(yield t)}}for(let[,t]of cB(e))t.kind===`template`&&(yield t.template),Mu(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function uB(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function dB(e,t){let n=new Set,r=new Set,i=new Set;for(let e of lB(t)){for(let r of Sx(e,t.helpers).keys())n.add(r);for(let{name:n}of Ex(e,t.helpers))r.add(n);for(let n of Dx(e,t.helpers))i.add(n)}for(let[,e]of cB(t))if(Mu(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Mb(t.presets))for(let n of wu(Fb(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>uB(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!Ep(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(cB(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var fB=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,vB(e,t,n,`initial value`),this.cell=Ix.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){vB(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},pB=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Ix.computed)(()=>{let e=n();return vB(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},mB=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Ix.observable.box(_B(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=_B(e);gB(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function hB(e){return JSON.stringify(e)}function gB(e,t){return hB(e)===hB(t)}function _B(e){return e.kind===`ok`?{kind:`ok`,value:Lx(e.value)}:e}function vB(e,t,n,r){let i=Rx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var yB=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new fB(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new mB(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new pB(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Ix.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Ix.runInAction)(()=>n.set(t))}runInAction(e){(0,Ix.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return hB(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function bB(e,{loaded:t,dropped:n,unreached:r}){Z(`info`,`config load ${e.join(` < `)||`<default>`}: plugins loaded=${t.length} dropped=${n.length} unplaced=${r.length}`+t.map(e=>` +${e}`).join(``)+n.map(e=>` -${e.path} (${e.reason})`).join(``)+r.map(e=>` ~${e.path} (${e.reason})`).join(``))}function xB(e,t,n){return e+`\0`+t+`\0`+(n??``)}function SB(e,t){return new Set(Mb(e.presets).filter(n=>Fb(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function CB(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...Dk(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=Mx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Mx(l.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function wB(e){return e.filter(Boolean).join(`
203
- `)||null}function TB(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=hA(t.layers,$P,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??$P,l=a.find(e=>e.path===t.home)?.raw??{},u=new yB,d=new qC(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=nB(o,d,{cwd:e}),n.push(...f.loadWarnings),RI(o),IP(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:WF(o),lastRenderCellsBySegment:new Map,authoredRoots:SB(c,l),fileHeldSettings:wI(l),unused:[...new Map(a.flatMap(e=>dB(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function EB(e,t,n,r){let i=kk(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[Pk(e,t),Mk(i)],s,c=null;try{s=TB(t,a,o,r,e=>{c=e})}catch(e){return e instanceof pu&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:wB(o),state:null,error:e instanceof pu||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:wB(o),state:s,error:null}}function DB(e,t,n){return TB(e,{layers:[],home:``,projectDir:t},[],n)}var OB=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=xB(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=EB(e,t,n,this.deps);a.state!==null&&bB(a.layers,a.state.plugins);let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??DB(t,e,this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=EB(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(bB(t.layers,t.state.plugins),e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=CB(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const kB=16384;var AB=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<kB){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%kB}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qA,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},effectCache:e.effectCache,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function jB(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const MB={load:()=>({}),save:()=>{},flush:()=>{}};var NB=class{sessions;storage;head=0;atom=(0,Ix.createAtom)(`SessionState`);constructor(e=MB,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Ix.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Ix.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Ix.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function PB(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 FB=class{timer=null;pending=null;constructor(e,t=500,n=lC){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.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 PB(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(l.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const IB={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,effect:`string`,preset:`string`,endcaps:`string`,variation:`string`,shade:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,transitions:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},LB=new Set([`1`,`true`]),RB=new Set([`0`,`false`,``]);function zB(e,t){let n=uV(e),r=n.scope===`segment-palette`?`string`:IB[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(LB.has(t))return`true`;if(RB.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function BB(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function VB(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Pe(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function HB(e){return/^\s*$/.test(e)?null:kl(e)}function UB(e,t){return e!==null&&jl(e,t)!==void 0}function WB(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(WB),...i}}return e}function GB(e){if(!Od(e))return WB(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,WB(t)])),...n}}const KB=ZP,qB=KB.segments,JB=KB.presets,YB=KB.root;function XB(e,t,n,r){if(!UB(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function ZB(e,t){let n=zw(t);return t.scope===`segment-palette`&&XB(e,[`segments`,t.segment],qB[t.segment],n.join(`.`)),n}function QB(e){return kl(zl(e))}function $B(){return Object.entries(YB.rows).map(([e,t])=>{let n=WB(t);return{path:[`root`],fragment:QB({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function eV(e,t){let n=e===null?void 0:jl(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function tV(e,t){if(t===void 0)return null;let n=GB(t);return{path:e,fragment:QB(n),unit:{path:e,value:n}}}function nV(e,t){let n=[`presets`,t],r=[...n,`root`],i=JB[t];XB(e,n,i,r.join(`.`));let a=eV(e,r)??tV(r,i?.root);return a!==null&&ou(a.fragment)?a:null}function rV(e,t){let n=au(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 iV(e,t){return[...$B(),eV(e,[`root`]),nV(e,t)].filter(e=>e!==null).reduce(rV,new Map)}function aV(e,t,n){for(let{node:r,...i}of iV(e,t).values())if(cu(r,n))return i;throw new $(`${oV(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 oV(e,t){return nV(e,t)?.path??[`root`]}function sV(e,t){return t.scope===`preset-root`?oV(e,t.preset):zw(t)}function cV(e,{unit:t}){return t===null?e:$l(e,t.path,zl(t.value),Ll)}function lV(e){let t=Rw(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function uV(e){let t=lV(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function dV(e,t,n,r,i){i(t,n,SV(t,r)),VB(t.path,r,e.logger),e.record(t.path,n,r)}function fV(e,t,n){let r=hV(e,t,n);if(r.length>0)throw new $(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const pV=()=>{};function mV(e,t){try{return t()}catch(t){throw!(t instanceof $)||e.above.length===0?t:new $(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function hV(e,t,n){let r=gV(e,t);if(r===null)return[];let i=new Set(bV(yV(r),yV(n)));return bV(vV(e,r),vV(e,n)).filter(e=>!i.has(e))}function gV(e,t){try{return _V(e,t)}catch(e){if(e instanceof pu)return null;throw e}}function _V(e,t){return hA(t===null?e.above:[e.path,...e.above],$P,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function vV(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function yV(e){return e.layers.at(-1)?.config??e.base}function bV(e,t,n=``){return!xV(e)||!xV(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>bV(e[r],t[r],n===``?r:`${n}.${r}`))}function xV(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function SV(e,t){try{return _V(e,t)}catch(e){throw e instanceof pu?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function CV(e,t){let n=uV(t),r=HB(BB(e)??``),i=r===null?void 0:jl(r,zw(n));return i!==void 0&&`value`in i?i.value:void 0}function wV(e,t,n){TV(e,t,n,[])}function TV(e,t,n,r){let i=BB(t.path),a=n.reduce((e,[t,n])=>$l(e,ZB(HB(e),uV(t)),zB(t,n),Ll),i??``);dV(e,t,i,mV(t,()=>EV(a,t.path,r,e=>e)),fV)}function EV(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=aV(HB(s),n,i),l=fu(cV(s,c),c.path,i,a,zl(o));if(l===null)throw new $(`${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 DV(e,t,n){let r=HB(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of iV(r,t)){if(!cu(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Nl(e,c):zl(s.value);if(a!==`#`)return $l(e,[...i,`rows`,a],l,Ll);if(nV(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return $l(e,i,l,Ll)}return e}function OV(e,t){return tu(e,t,t[0]===`presets`&&t.length>2&&!tF(t[1])?2:0)}function kV(e,t,n){let r=n.map(lV),i=BB(t.path);if(i===null)return;let a=r.reduce((e,t)=>OV(e,sV(HB(e),t)),i);a!==i&&dV(e,t,i,a,pV)}function AV(e){let t=e===null?void 0:jl(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function jV(e,t){let n=new Set([...eF,...AV(e),...t.above.flatMap(e=>Object.keys(at.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map(bp));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(bp(e)))}function MV(e,t,n,r,i,a){let o=BB(t.path),s=HB(o??``),c=jV(s,t),l=[`presets`,c],u=mV(t,()=>nV(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Nl(o??``,u.fragment):zl(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],zl(r)]]],f=i.map(([e,t])=>{let n=Lw(c,e);return[ZB(s,uV(n)),zB(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>$l(e,t,n,Ll),$l(o??``,l,`{}`,Ll));return dV(e,t,o,mV(t,()=>EV(p,t.path,a.map(e=>({...e,preset:c})),DV)),fV),c}function NV(e,t,n,r){let i=BB(t.path);dV(e,t,i,$l(i??``,[`themeDefaults`,n],zl(r),Ll),fV)}function PV(e,t,n){if(tF(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=BB(t.path),a=HB(i??``);if(i===null||a===null||jl(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=jl(a,[`globals`,`preset`]);dV(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>OV(e,t),i),pV)}function FV(e,t,n,r){let i=lV(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=BB(t.path),o=r.op===`remove`?r.target:r.anchor,s=mV(t,()=>aV(HB(a??``),i.preset,o)),c=cV(a??``,s),{after:l,placed:u}=IV(c,s.path,r,()=>{let e=SV(t,c).config;return Mb(e.presets).map(t=>Fb(e,t).node)});if(l===null)throw new $(`${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 dV(e,t,a,l,fV),u}function IV(e,t,n,r){switch(n.op){case`remove`:return{after:uu(e,t,n.target),placed:null};case`insert`:{let i=CP(n.segment,n.anchor,r());return{after:du(e,t,i,n.anchor,n.relation),placed:i}}}}const LV={load:()=>({}),save:()=>{}},RV=new Set(ZC.map(e=>e.sessionKey)),zV=e=>RV.has(e)||e.startsWith(nx),BV=8*1024*1024,VV={past:[],future:[]},HV=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var UV=class{state=new Map;constructor(e,t,n=LV){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??VV;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??VV}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(HV(n));r.set(HV(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:jB(this.sessionState,e=>zV(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:ZV(i,n),o=r.get(e),s=o===void 0?a:tH(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 $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,$V(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`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(HV)),a=n.net.filter(e=>!i.has(HV(e))),o=KV(nH(eH(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(iH).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 $(`redo: nothing to redo`);let a=[...n,i],o=KV(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...JV(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(HV)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:nH(n,t),future:nH(i,t),...a!==void 0&&{savepoint:{at:nH([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(HV(e))),below:nH(a.below,t)}}}),new $(`${r}: ${o.map(iH).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):BB(t.file)}write(e,t,n){t.kind===`file`?VB(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||WV(n)>BV;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,GV(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${BV} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function WV(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 GV({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...JV(n,1,[])}:{past:e,future:t.slice(1),...JV(n,0,[])}}function KV(e){return e.slice(-50)}const qV=e=>e===ix.member;function JV(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:YV(e.net,n),below:e.below}}}function YV(e,t){let n=new Map(e.map(e=>[HV(e),e]));for(let e of t){let t=n.get(HV(e));n.set(HV(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const XV=e=>e.map(e=>({...e,before:e.after,after:e.before}));function ZV(e,t){let n=[...e.past,t],r=KV(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...JV(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...QV(e.future,a),...i.below]},n.length-r.length,t)}}function QV(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function $V(e,t){return{past:e.past.slice(0,-1),future:KV([...e.future,t]),...JV(e.savepoint,0,XV(t))}}function eH(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...QV(r,t.at-i.length),...t.below]}function tH(e,t){if(qV(t.after)&&!qV(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!qV(t.after)&&qV(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function nH(e,t){return e.map(e=>e.filter(e=>!t.has(HV(e)))).filter(e=>e.length>0)}function rH(e){return e.map(iH).join(`, `)}function iH(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function aH(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function oH(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(aH))}function sH(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(aH)&&oH(t.below)}function cH(e){if(typeof e!=`object`||!e)return!1;let t=e;return oH(t.past)&&oH(t.future)&&(t.savepoint===void 0||sH(t.savepoint))}function lH(e,t){let n=e=>e.kind===`file`||zV(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 uH(e,t){return{load:()=>{let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(cH)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,lH(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(l.dirname(e),{recursive:!0}),Pe(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const dH=e=>!zV(e)&&!bT(e)&&e!==`update.dismissed`;var fH=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:jB(e,dH,(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 $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Ix.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function pH(e){let t=_R(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function mH(e){return{probeTmux:pH,loadConfig:e}}function hH(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
204
- `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}function gH(e){let{env:t,statusLine:n}=NT(e);if(t!==void 0&&!PT(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t??{},statusLine:n===void 0?{kind:`absent`}:PT(n)?{kind:`present`,refreshInterval:n.refreshInterval}:{kind:`not-an-object`,value:n}}}function _H(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function vH(e){return{kind:`arrived`,handler:e,bar:qA}}function yH(e,t,n){let r=new Map;for(let i of wu(Fb(e,t).node)){if(i.kind!==`segment`)continue;let t=Lu(e.segments[i.name])[Fu],a=Uu(i,Fu,t,e=>n(e.key));a===`bar`||a===`none`||r.set(i.drafts?.effect?.id??bu(i),a)}return[...r].map(([e,t])=>({placement:e,effect:t}))}function bH(e,t,n,r){let i=e.loadConfig(n),a=jF(i.config,r,()=>!1);return{tmux:_H(e,t.tmux),config:hH(i),effect:a.effect,placementEffects:yH(i.config,a.preset,r),transitions:a.transitions,claudeSettings:gH(AT(kT(t.claudeConfigDir)))}}function xH(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings`:{let i=$l(MT(n),e.path,JSON.stringify(e.value),Rl);return r.mkdirSync(l.dirname(n),{recursive:!0}),Pe(n,i),{...t,claudeSettings:gH(n)}}default:return e.kind}}const SH={connectMs:200,budgetMs:500};async function CH(e){let n=e.includes(`--json`),r=await wH();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${KA(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
205
- `);return}t.stdout.write(OH(r.value))}function wH(){return BA({kind:`stats`},SH,e=>`stats`in e?e.stats:void 0)}function TH(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function EH(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function DH(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 OH(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${DH(e.uptimeSec)}`),t.push(` rss ${TH(e.rssBytes)}`),t.push(` heapUsed ${TH(e.heapUsedBytes)}`),t.push(` heapTotal ${TH(e.heapTotalBytes)}`),t.push(` external ${TH(e.externalBytes)}`),t.push(` arrayBuffers ${TH(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${EH(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${EH(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(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),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(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
201
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function Hz(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function Uz(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function Wz(e){return{...e,cells:e.cells.map(kR)}}function Gz(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,...Kz(e,r)]}function Kz(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 qz(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:Gz(e.direction,e.children.map((t,i)=>n(t,[...r,Jz(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function Jz(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:yu[e.direction]}}const Yz={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ps(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,Tu(t.path,n)))}},render(e,t){return Gz(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,Jz(e,r))))}},Xz={drop:e=>e.place,above:()=>`above`},Zz={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},Qz={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:bu(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Kd(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Eu(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,$z(e,t))};function $z(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=FS(t.scope,e.settings);try{if(!TR(i.when,a))return[];let n=lw(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:Gw(n)},s=e.opens!==void 0&&TR(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:Xz[g.placement](e)})),v=Vz(PR(l,m)).map((e,t)=>({cells:MR(e,{...h,lead:t===0?PR(u,m):[],trail:t===0?PR(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:MR(PR([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>MR(PR([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),x=_.findIndex(e=>e.band===`own`),{lead:S,stays:C}=g!==void 0&&x!==-1?Zz[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},ee=S.flatMap(e=>b(new W(` `.repeat(OR(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=_.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),..._.flatMap(w)].flatMap(OR)),[...ne,...te]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:MR([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Gw(t.palette)},lead:eB(e.lead,e,a,t),trail:eB(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}function eB(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const tB={container:Yz,segment:Qz};function nB(e){return tB[e]}function rB(e){if(`ttl`in e)return{kind:`ttl`,durationMs:DC(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 iB(e,t){switch(Au(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 aB(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:rB(n.cache),parse:iB(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:rB(n.cache),parse:iB(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function oB(e,t){let n=eh.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}const sB=(e,t,n,r,i)=>{let a=aF(t,iF(n,e.themeDefaults));return{variation:Os[r??cl(void 0,null,a.variation)],shade:Es[i??dl(void 0,null,a.shade)]}};function cB(e,t,n){let r=n.cwd,i={store:t.variableStore,compiled:new Map,chromeCols:QN({endcaps:`powerline`,charset:rl}),width:80,padding:1,seamCols:$N({endcaps:`powerline`,charset:rl}),layout:()=>[],look:void 0},a=cz(t.drawnAt),o={action:i,activeSegment:a},s=Object.keys(e.styles),c=Nb(e.presets),l=jD(e),u=MS({extraFuncs:{...XR(i),...bz(i,a),...Cz(i,a),...Dz(i,a),...Mz(i,a),...Iz(o),...zz(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:t.now,drawnAt:t.drawnAt}),d=oB(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map;for(let[t,n]of nw)n in e.variables&&h.set(t,n);for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!h.has(n.key)&&h.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!h.has(r.key)&&h.set(r.key,`${t}.${e}`);i.compiled=RR(f,e.actions,h,l);let g=[];for(let[n,i]of Object.entries(e.variables))try{aB(t,n,i,r)}catch(e){g.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{aB(t,`${n}.${e}`,a,r)}catch(t){g.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let _=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};_[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let v=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},y=t.variableStore,b=t=>{let n=Lu(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Uu(t,e,i,e=>String(y.read(e.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:v(e.when,t,`when`),parse:(e,n)=>v(e,t,n),compileChild:x,placementSettings:b};return nB(e.kind).compile(e,n)},S=new Map;for(let t of c){let{node:n,path:r}=Ib(e,t);S.set(t,x(n,r))}let C=new Map(Ic.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of Ic){let r=t[n];if(!Lc(r))continue;let i=`${e}.${n}`,a=C.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:lB(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:_,roots:S,activeSegment:a,menuRuntime:o,globalExpressions:C,loadWarnings:g}}function lB(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function uB(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function dB(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function fB(e,t){return e.kind===`decided`?e.name:t}function pB(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u,onRenderWarning:d}=s??{},f=new Set;r.renderAt(a),r.drawAt(al(o.colorCompatibility));let{preset:p=jb}=c??{},m=Lb(e,p),h=c?.style??Hc(`none`,e.styles),g=c?.theme??hw(void 0,null,m.palette),_=sB(e,m,g,c?.variation,c?.shade),v=c?.effect??Yc(void 0,null,m.effect),y=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(y(fB(g,kc),fB(h,Bc),fB(v,Wc))),t.menuRuntime.action.chromeCols=QN(o),t.menuRuntime.action.padding=o.padding,t.menuRuntime.action.width=o.width,t.menuRuntime.action.seamCols=$N(o);let b=NS(n),x=zc(g,e=>{let n=uB(t,`palette`,e);return mw(dB(n,b),n.where,e=>d?.({kind:`theme-rule`,message:e}))}),S=zc(h,n=>Hc(dB(uB(t,`style`,n),b),e.styles)),C=zc(v,e=>Jc(dB(uB(t,`effect`,e),b)));(x!==g||S!==h||C!==v)&&r.applyInput(y(x.name,S.name,C.name));let ee=x.value,w=dw(ee,S.value);t.menuRuntime.action.look={basePalette:ee,palette:w,decor:_};let te=(c?.effects??new HN(``)).motion(C.value,a,{transitions:c?.transitions??xl(void 0,null,m.transitions),source:{config:t,preset:p,revision:r.stateRevision(),width:o.width},returned:Uz,hold:Wz});l?.clear();let ne=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},re=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Ec(i,a,c),p=lz(t.activeSegment,e.name,e.id,i,d,l,u),m=qw(p,c,o.bg,o.fg,n),h=()=>mc(i,d,c);s&&(p.bg=h().state);let g=o.body.evaluate(n),_=p.drops.length>0||s;if(_){let e=h();p.bg=e.state;for(let t of e.shortfalls)f.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:m,get trigger(){return QR(i,h().state,c)},get band(){return QR(i,h().plane,c)},get close(){return tz(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:p.drops,open:_}}finally{t.activeSegment.current=null}},ie=(e,t,r)=>{let i=t&&TR(e.when,b),a={scope:b,palette:w,visible:i,padding:o.padding,region:r,perSegmentSink:l,onSegmentError:u,evaluateSegment:re,lookupSegment:ne,renderChild:(e,t,n)=>ie(e,t,wc(r,n)),renderBody:(e,t,n)=>ie(e,i&&t,Tc(n)),closeDisclosure:e=>ZR(n,e),placed:te.placed};return nB(e.kind).render(e,a)},T=t.roots.get(p);if(T===void 0)throw Error(`Preset "${p}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${jb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let E=e=>{if(!TR(e.when,b))return!1;if(e.kind===`container`)return!0;if(HD(e.name)===void 0)return!1;try{return TR(t.segments[e.name].when,FS(b,e.settings))}catch{return!0}};t.menuRuntime.action.layout=()=>qz(T,E).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=HD(e);return r===void 0?[]:[{name:r,address:t,palette:lw(n.theme,w)}]}));let ae=Hz(ie(T,!0,Cc(_))).map(({line:e,row:t})=>{let n=NR(e.cells,o);return eP(n.map(e=>e.owner),o,te.row(t,n))}).join(`
202
+ `);te.drawn();for(let e of f)d?.({kind:`band-floor`,message:e});return ae}function*mB(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*hB(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of Nb(e.presets)){for(let n of wu(Ib(e,t).node))n.when!==void 0&&(yield n.when);let n=Lb(e,t);for(let e of Ic){let t=n[e];Lc(t)&&(yield t)}}for(let[,t]of mB(e))t.kind===`template`&&(yield t.template),Mu(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function gB(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function _B(e,t){let n=new Set,r=new Set,i=new Set;for(let e of hB(t)){for(let r of Cx(e,t.helpers).keys())n.add(r);for(let{name:n}of Dx(e,t.helpers))r.add(n);for(let n of Ox(e,t.helpers))i.add(n)}for(let[,e]of mB(t))if(Mu(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Nb(t.presets))for(let n of wu(Ib(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>gB(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!Ep(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(mB(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var vB=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,wB(e,t,n,`initial value`),this.cell=Lx.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){wB(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},yB=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Lx.computed)(()=>{let e=n();return wB(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},bB=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Lx.observable.box(CB(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=CB(e);SB(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function xB(e){return JSON.stringify(e)}function SB(e,t){return xB(e)===xB(t)}function CB(e){return e.kind===`ok`?{kind:`ok`,value:Rx(e.value)}:e}function wB(e,t,n,r){let i=zx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var TB=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new vB(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new bB(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new yB(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Lx.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Lx.runInAction)(()=>n.set(t))}runInAction(e){(0,Lx.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return xB(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function EB(e,{loaded:t,dropped:n,unreached:r}){Z(`info`,`config load ${e.join(` < `)||`<default>`}: plugins loaded=${t.length} dropped=${n.length} unplaced=${r.length}`+t.map(e=>` +${e}`).join(``)+n.map(e=>` -${e.path} (${e.reason})`).join(``)+r.map(e=>` ~${e.path} (${e.reason})`).join(``))}function DB(e,t,n){return e+`\0`+t+`\0`+(n??``)}function OB(e,t){return new Set(Nb(e.presets).filter(n=>Ib(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function kB(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...Ok(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=Nx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Nx(l.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function AB(e){return e.filter(Boolean).join(`
203
+ `)||null}function jB(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=gA(t.layers,eF,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??eF,l=a.find(e=>e.path===t.home)?.raw??{},u=new TB,d=new JC(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=cB(o,d,{cwd:e}),n.push(...f.loadWarnings),zI(o),LP(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:GF(o),lastRenderCellsBySegment:new Map,authoredRoots:OB(c,l),fileHeldSettings:TI(l),unused:[...new Map(a.flatMap(e=>_B(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function MB(e,t,n,r){let i=Ak(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[Fk(e,t),Nk(i)],s,c=null;try{s=jB(t,a,o,r,e=>{c=e})}catch(e){return e instanceof pu&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:AB(o),state:null,error:e instanceof pu||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:AB(o),state:s,error:null}}function NB(e,t,n){return jB(e,{layers:[],home:``,projectDir:t},[],n)}var PB=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=DB(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=MB(e,t,n,this.deps);a.state!==null&&EB(a.layers,a.state.plugins);let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??NB(t,e,this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=MB(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(EB(t.layers,t.state.plugins),e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=kB(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const FB=16384;var IB=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<FB){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%FB}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:JA,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},effectCache:e.effectCache,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function LB(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const RB={load:()=>({}),save:()=>{},flush:()=>{}};var zB=class{sessions;storage;head=0;atom=(0,Lx.createAtom)(`SessionState`);constructor(e=RB,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Lx.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Lx.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Lx.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function BB(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 VB=class{timer=null;pending=null;constructor(e,t=500,n=uC){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.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 BB(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(l.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const HB={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,effect:`string`,preset:`string`,endcaps:`string`,variation:`string`,shade:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,transitions:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},UB=new Set([`1`,`true`]),WB=new Set([`0`,`false`,``]);function GB(e,t){let n=gV(e),r=n.scope===`segment-palette`?`string`:HB[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(UB.has(t))return`true`;if(WB.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function KB(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function qB(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Pe(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function JB(e){return/^\s*$/.test(e)?null:kl(e)}function YB(e,t){return e!==null&&jl(e,t)!==void 0}function XB(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(XB),...i}}return e}function ZB(e){if(!Od(e))return XB(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,XB(t)])),...n}}const QB=QP,$B=QB.segments,eV=QB.presets,tV=QB.root;function nV(e,t,n,r){if(!YB(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function rV(e,t){let n=Bw(t);return t.scope===`segment-palette`&&nV(e,[`segments`,t.segment],$B[t.segment],n.join(`.`)),n}function iV(e){return kl(zl(e))}function aV(){return Object.entries(tV.rows).map(([e,t])=>{let n=XB(t);return{path:[`root`],fragment:iV({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function oV(e,t){let n=e===null?void 0:jl(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function sV(e,t){if(t===void 0)return null;let n=ZB(t);return{path:e,fragment:iV(n),unit:{path:e,value:n}}}function cV(e,t){let n=[`presets`,t],r=[...n,`root`],i=eV[t];nV(e,n,i,r.join(`.`));let a=oV(e,r)??sV(r,i?.root);return a!==null&&ou(a.fragment)?a:null}function lV(e,t){let n=au(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 uV(e,t){return[...aV(),oV(e,[`root`]),cV(e,t)].filter(e=>e!==null).reduce(lV,new Map)}function dV(e,t,n){for(let{node:r,...i}of uV(e,t).values())if(cu(r,n))return i;throw new $(`${fV(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 fV(e,t){return cV(e,t)?.path??[`root`]}function pV(e,t){return t.scope===`preset-root`?fV(e,t.preset):Bw(t)}function mV(e,{unit:t}){return t===null?e:$l(e,t.path,zl(t.value),Ll)}function hV(e){let t=zw(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function gV(e){let t=hV(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function _V(e,t,n,r,i){i(t,n,OV(t,r)),qB(t.path,r,e.logger),e.record(t.path,n,r)}function vV(e,t,n){let r=xV(e,t,n);if(r.length>0)throw new $(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const yV=()=>{};function bV(e,t){try{return t()}catch(t){throw!(t instanceof $)||e.above.length===0?t:new $(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function xV(e,t,n){let r=SV(e,t);if(r===null)return[];let i=new Set(EV(TV(r),TV(n)));return EV(wV(e,r),wV(e,n)).filter(e=>!i.has(e))}function SV(e,t){try{return CV(e,t)}catch(e){if(e instanceof pu)return null;throw e}}function CV(e,t){return gA(t===null?e.above:[e.path,...e.above],eF,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function wV(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function TV(e){return e.layers.at(-1)?.config??e.base}function EV(e,t,n=``){return!DV(e)||!DV(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>EV(e[r],t[r],n===``?r:`${n}.${r}`))}function DV(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function OV(e,t){try{return CV(e,t)}catch(e){throw e instanceof pu?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function kV(e,t){let n=gV(t),r=JB(KB(e)??``),i=r===null?void 0:jl(r,Bw(n));return i!==void 0&&`value`in i?i.value:void 0}function AV(e,t,n){jV(e,t,n,[])}function jV(e,t,n,r){let i=KB(t.path),a=n.reduce((e,[t,n])=>$l(e,rV(JB(e),gV(t)),GB(t,n),Ll),i??``);_V(e,t,i,bV(t,()=>MV(a,t.path,r,e=>e)),vV)}function MV(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=dV(JB(s),n,i),l=fu(mV(s,c),c.path,i,a,zl(o));if(l===null)throw new $(`${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 NV(e,t,n){let r=JB(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of uV(r,t)){if(!cu(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Nl(e,c):zl(s.value);if(a!==`#`)return $l(e,[...i,`rows`,a],l,Ll);if(cV(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return $l(e,i,l,Ll)}return e}function PV(e,t){return tu(e,t,t[0]===`presets`&&t.length>2&&!nF(t[1])?2:0)}function FV(e,t,n){let r=n.map(hV),i=KB(t.path);if(i===null)return;let a=r.reduce((e,t)=>PV(e,pV(JB(e),t)),i);a!==i&&_V(e,t,i,a,yV)}function IV(e){let t=e===null?void 0:jl(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function LV(e,t){let n=new Set([...tF,...IV(e),...t.above.flatMap(e=>Object.keys(at.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map(bp));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(bp(e)))}function RV(e,t,n,r,i,a){let o=KB(t.path),s=JB(o??``),c=LV(s,t),l=[`presets`,c],u=bV(t,()=>cV(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Nl(o??``,u.fragment):zl(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],zl(r)]]],f=i.map(([e,t])=>{let n=Rw(c,e);return[rV(s,gV(n)),GB(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>$l(e,t,n,Ll),$l(o??``,l,`{}`,Ll));return _V(e,t,o,bV(t,()=>MV(p,t.path,a.map(e=>({...e,preset:c})),NV)),vV),c}function zV(e,t,n,r){let i=KB(t.path);_V(e,t,i,$l(i??``,[`themeDefaults`,n],zl(r),Ll),vV)}function BV(e,t,n){if(nF(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=KB(t.path),a=JB(i??``);if(i===null||a===null||jl(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=jl(a,[`globals`,`preset`]);_V(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>PV(e,t),i),yV)}function VV(e,t,n,r){let i=hV(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=KB(t.path),o=r.op===`remove`?r.target:r.anchor,s=bV(t,()=>dV(JB(a??``),i.preset,o)),c=mV(a??``,s),{after:l,placed:u}=HV(c,s.path,r,()=>{let e=OV(t,c).config;return Nb(e.presets).map(t=>Ib(e,t).node)});if(l===null)throw new $(`${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 _V(e,t,a,l,vV),u}function HV(e,t,n,r){switch(n.op){case`remove`:return{after:uu(e,t,n.target),placed:null};case`insert`:{let i=wP(n.segment,n.anchor,r());return{after:du(e,t,i,n.anchor,n.relation),placed:i}}}}const UV={load:()=>({}),save:()=>{}},WV=new Set(QC.map(e=>e.sessionKey)),GV=e=>WV.has(e)||e.startsWith(rx),KV=8*1024*1024,qV={past:[],future:[]},JV=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var YV=class{state=new Map;constructor(e,t,n=UV){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??qV;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??qV}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(JV(n));r.set(JV(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:LB(this.sessionState,e=>GV(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:rH(i,n),o=r.get(e),s=o===void 0?a:sH(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 $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,aH(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`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(JV)),a=n.net.filter(e=>!i.has(JV(e))),o=QV(cH(oH(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(uH).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 $(`redo: nothing to redo`);let a=[...n,i],o=QV(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...eH(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(JV)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:cH(n,t),future:cH(i,t),...a!==void 0&&{savepoint:{at:cH([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(JV(e))),below:cH(a.below,t)}}}),new $(`${r}: ${o.map(uH).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):KB(t.file)}write(e,t,n){t.kind===`file`?qB(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||XV(n)>KV;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,ZV(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${KV} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function XV(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 ZV({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...eH(n,1,[])}:{past:e,future:t.slice(1),...eH(n,0,[])}}function QV(e){return e.slice(-50)}const $V=e=>e===ax.member;function eH(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:tH(e.net,n),below:e.below}}}function tH(e,t){let n=new Map(e.map(e=>[JV(e),e]));for(let e of t){let t=n.get(JV(e));n.set(JV(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const nH=e=>e.map(e=>({...e,before:e.after,after:e.before}));function rH(e,t){let n=[...e.past,t],r=QV(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...eH(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...iH(e.future,a),...i.below]},n.length-r.length,t)}}function iH(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function aH(e,t){return{past:e.past.slice(0,-1),future:QV([...e.future,t]),...eH(e.savepoint,0,nH(t))}}function oH(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...iH(r,t.at-i.length),...t.below]}function sH(e,t){if($V(t.after)&&!$V(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!$V(t.after)&&$V(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function cH(e,t){return e.map(e=>e.filter(e=>!t.has(JV(e)))).filter(e=>e.length>0)}function lH(e){return e.map(uH).join(`, `)}function uH(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function dH(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function fH(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(dH))}function pH(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(dH)&&fH(t.below)}function mH(e){if(typeof e!=`object`||!e)return!1;let t=e;return fH(t.past)&&fH(t.future)&&(t.savepoint===void 0||pH(t.savepoint))}function hH(e,t){let n=e=>e.kind===`file`||GV(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 gH(e,t){return{load:()=>{let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(mH)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,hH(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(l.dirname(e),{recursive:!0}),Pe(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const _H=e=>!GV(e)&&!xT(e)&&e!==`update.dismissed`;var vH=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:LB(e,_H,(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 $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Lx.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function yH(e){let t=vR(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function bH(e){return{probeTmux:yH,loadConfig:e}}function xH(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
204
+ `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}function SH(e){let{env:t,statusLine:n}=PT(e);if(t!==void 0&&!FT(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t??{},statusLine:n===void 0?{kind:`absent`}:FT(n)?{kind:`present`,refreshInterval:n.refreshInterval}:{kind:`not-an-object`,value:n}}}function CH(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function wH(e){return{kind:`arrived`,handler:e,bar:JA}}function TH(e,t,n){let r=new Map;for(let i of wu(Ib(e,t).node)){if(i.kind!==`segment`)continue;let t=Lu(e.segments[i.name])[Fu],a=Uu(i,Fu,t,e=>n(e.key));a===`bar`||a===`none`||r.set(i.drafts?.effect?.id??bu(i),a)}return[...r].map(([e,t])=>({placement:e,effect:t}))}function EH(e,t,n,r){let i=e.loadConfig(n),a=MF(i.config,r,()=>!1);return{tmux:CH(e,t.tmux),config:xH(i),effect:a.effect,placementEffects:TH(i.config,a.preset,r),transitions:a.transitions,claudeSettings:SH(jT(AT(t.claudeConfigDir)))}}function DH(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings`:{let i=$l(NT(n),e.path,JSON.stringify(e.value),Rl);return r.mkdirSync(l.dirname(n),{recursive:!0}),Pe(n,i),{...t,claudeSettings:SH(n)}}default:return e.kind}}const OH={connectMs:200,budgetMs:500};async function kH(e){let n=e.includes(`--json`),r=await AH();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${qA(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
205
+ `);return}t.stdout.write(PH(r.value))}function AH(){return VA({kind:`stats`},OH,e=>`stats`in e?e.stats:void 0)}function jH(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function MH(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function NH(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 PH(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${NH(e.uptimeSec)}`),t.push(` rss ${jH(e.rssBytes)}`),t.push(` heapUsed ${jH(e.heapUsedBytes)}`),t.push(` heapTotal ${jH(e.heapTotalBytes)}`),t.push(` external ${jH(e.externalBytes)}`),t.push(` arrayBuffers ${jH(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${MH(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${MH(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(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),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(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
206
206
  `)+`
207
- `}const kH=e=>({kind:`ok`,value:e}),AH=e=>({kind:`failed`,reason:e});var jH=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const MH=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function NH(e){return MH.test(e)?e:null}function PH(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return kH(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return kH({app:n,missing:AH(`its script could not be read (${r.reason})`)});let i=LM(r.value);return kH({app:n,missing:i===null?AH("its script is not one `cc-candybar install` wrote"):kH([i.node,i.script].filter(t=>!e.exists(t)))})}async function FH(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function IH(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Fj}://${aM}/${n}`);return(r===null?await FH(e,n):null)??{kind:`lost`,unopened:r,opener:PH(e)}}function LH(e,t,n){let r=O({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?kH(r.stdout):AH(r.stderr.trim()||r.error||r.reason)}const RH=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Fj}://probe"));u.isNil() ? "" : u.path.js`;async function zH(){let e=await wH();if(e.kind!==`ok`)return AH(KA(e).split(`
208
- `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?kH({version:t,arrivals:n}):AH(`the running daemon (${t}) predates this check`)}function BH(){return{platform:process.platform,sockets:{own:ze(),handler:Be()},now:Date.now,nonce:ce,daemon:zH,open:e=>{let t=LH(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=LH(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,RH]);if(e.kind===`failed`)return e;let t=e.value.trim();return kH(t===``?null:t)},script:e=>LH(`doctor.osadecompile`,`/usr/bin/osadecompile`,[RM(e)]),exists:r.existsSync}}const VH=/^─{20,}/,HH=/^❯(\s|$)/,UH=/›\s*stashed$/;function WH(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>VH.test(e)?[t]:[]).at(-2);return n===void 0||!HH.test(t[n+1]??``)?{kind:`no-prompt`}:UH.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const GH={"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 KH(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=WH(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:GH[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const qH=`cc-candybar-slash`;function JH(e,t,n,r){let i=_R(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function YH(e){let t=JH(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
209
- `);return{inMode:n!==`0`,screen:r}}function XH(e,t){let n=JH(e,`claude-input.type`,[`load-buffer`,`-b`,qH,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,qH,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function ZH(){return{read:YH,type:XH}}function QH(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function $H(e){return eU(()=>decodeURIComponent(e))}function eU(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function tU(e,t){let n=O({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const nU=(e,t)=>tU($H(e),t),rU=(e,t)=>{let n=O({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,$H(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},iU=(e,t)=>tU($H(e),t),aU=(e,t)=>tU($H(e),t),oU=(e,t)=>{let n=QH($H(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},sU=(e,t)=>{let[n=``,...r]=eU(()=>lM(e)),i=QH(n),a=RI(yU(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}dU(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},cU=/^-?\d+$/;function lU(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const uU=(e,t)=>{let[n=``,r=``,i=``]=eU(()=>lM(e)),a=QH(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!cU.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=yU(t,a),c=RI(s),l=c.rangeParamsFor(r);if(!l)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&cU.test(u)?fU(l,parseInt(u,10)):pU(`step-state`,r,l,VI(s,e=>t.sessionState.get(a,e),r)),f=lU(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);dU(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function dU(e,t,n,r){let i=r.filter(e=>e.key.startsWith(nx));if(i.length===0)return;let a=_I(yU(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function fU(e,t){return Math.max(e.min,Math.min(e.max,t))}function pU(e,t,n,r){if(r===null)return n.min;if(!cU.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return fU(n,parseInt(r,10))}const mU=`render-origin`;function hU(e){return JSON.stringify(e)}function gU(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function _U(e,t){let n=e.sessionState.get(t,mU);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return gU(n)}function vU(e,t,n){let r=e.sessionState.get(t,mU);if(r===null)return;let i=gU(r),{path:a}=bU(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function yU(e,t){return e.configFor(_U(e,t))}function bU(e){return jk(e.projectDir,e.cwd,e.configFile??void 0)}function xU(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const SU=(e,t)=>{let[n=``,r=``,i=``]=eU(()=>lM(e)),a=QH(n),o=_U(t,a),s=t.configFor(o),c=IP(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=bU(o),d=hI(s,e=>t.sessionState.get(a,e),r);wV(xU(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},CU=(e,t)=>{let[n=``,r=``,i=``]=eU(()=>lM(e)),a=QH(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!cU.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=_U(t,a),c=t.configFor(s),l=IP(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=bU(s),f=hI(c,e=>t.sessionState.get(a,e),r),p=CV(d.path,f.key),m=typeof p==`number`?fU(u,p):pU(`step-config`,r,u,RP(f.globals,r)),h=lU(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);wV(xU(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},wU=(e,t)=>{let[n=``]=eU(()=>lM(e)),r=QH(n),i=_U(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=pI(a,o),c=gI(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=RI(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});EU(`save`,l,c);let d=bU(i);TV(xU(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(TU)].join(` `)} → ${d.path} (session=${r})`)},TU=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Vu(e.value)}`;function EU(e,t,n){for(let r of n){let n=t.validate(r.key,Vu(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const DU=(e,t)=>{let[n=``]=eU(()=>lM(e)),r=QH(n),i=_U(t,r),a=t.configFor(i),o=bI(a,e=>t.sessionState.get(r,e)),s=RI(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});EU(`save-preset`,s,o.placements);let l=bU(i),u=MV(xU(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...ZC.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,XC.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(TU)].join(` `)} → ${l.path} (session=${r})`)},OU=(e,t)=>{let[n=``]=eU(()=>lM(e)),r=QH(n),i=_U(t,r),a=SI(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new $(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=bU(i);NV(xU(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(pI(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ku.map(e=>XC[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${ku.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},kU=(e,t)=>{let[n=``,r=``]=eU(()=>lM(e)),i=QH(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=_U(t,i),o=bU(a);PV(xU(t,i),o,r),t.reloadConfig(a);let s=XC.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},AU=(e,t)=>{let[n=``,...r]=eU(()=>lM(e)),i=QH(n),a=_U(t,i),o=IP(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=bU(a),l=r.map(CI),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);kV(xU(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function jU(e,t){let n=(e,t)=>[...wu(Fb(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Mb(t.presets).flatMap(e=>n(t,e).map(t=>rx(bp(e),bu(t)))));return Mb(e.presets).flatMap(t=>n(e,t).map(e=>({member:rx(bp(t),bu(e)),node:e})).filter(({member:e})=>!r.has(e)))}function MU(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Zb]:[]])}const NU=(e,t)=>{let[n=``,r=``,i=``]=eU(()=>lM(e)),a=QH(n),o=_U(t,a),s=t.configFor(o),c=IP(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=SP(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=bU(o),f=FV(xU(t,a),d,r,u);t.reloadConfig(o);let p=MU(jU(s,t.configFor(o)),t.sessionState.get(a,Zb)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},PU=(e,t)=>{let[n=``]=eU(()=>lM(e)),r=QH(n);t.journal.commit();let i=t.history.undo(r);vU(t,r,i),t.dlog(`info`,`undo: restored ${rH(i)} (session=${r})`)},FU=(e,t)=>{let n=QH($H(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,RI(yU(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},IU=(e,t)=>{let n=QH($H(e));t.journal.commit();let r=t.history.rewind(n);vU(t,n,r),t.dlog(`info`,`rewind: put back ${rH(r)||`nothing`} as edit mode found it (session=${n})`)},LU=(e,t)=>{let[n=``]=eU(()=>lM(e)),r=QH(n);t.journal.commit();let i=t.history.redo(r);vU(t,r,i),t.dlog(`info`,`redo: re-applied ${rH(i)} (session=${r})`)},RU=(e,t)=>{QH($H(e)),t.applyUpdate()},zU=`client-hints`;function BU(e,t){let n=e.sessionState.get(t,zU);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return DA(r)}function VU(e,t,n){let r=lT(n);e.sessionState.setBatch(t,mT(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function HU(e,t){return{...bH(e.doctor,BU(e,t),_U(e,t),n=>e.sessionState.get(t,n)),urlHandler:vH(e.clientVersion)}}const UU=(e,t)=>{let n=QH($H(e));VU(t,n,HU(t,n))},WU=(e,t)=>{let n=NH($H(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},GU=(e,t)=>{let[n=``,r=``]=eU(()=>lM(e)),i=QH(n),a=uT(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=HU(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=xH(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.path.join(`.`)}=${JSON.stringify(s.fix.value)} (session=${i})`),VU(t,i,c)},KU=(e,t)=>{let[n=``,...r]=eU(()=>lM(e)),i=QH(n),a=_U(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=XD(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=vF({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},BU(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},qU=(e,t)=>{let[n=``,r=``]=eU(()=>lM(e)),i=QH(n),a=Object.values(t.configFor(_U(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=KH(t.claudeInput,BU(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},JU=`config-override`,YU=new Map([[zj,nU],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=QH(eU(()=>decodeURIComponent(e.slice(0,n)))),i=eU(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,JU),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,JU,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Bj,rU],[Lj,sU],[Rj,uU],[Wj,SU],[Gj,CU],[Xj,AU],[Kj,wU],[qj,DU],[Jj,OU],[Yj,kU],[Zj,NU],[Qj,PU],[$j,LU],[eM,FU],[tM,IU],[Hj,iU],[Uj,aU],[Vj,oU],[nM,RU],[rM,UU],[iM,GU],[aM,WU],[oM,KU],[sM,qU]]),XU=new Set([Lj,Rj,Wj,Gj,Xj,Kj,qj,Jj,Yj,Zj,Qj,$j,eM,tM,Vj,nM,rM,iM,oM,sM]),ZU=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of pM(dM(e))){if(!i&&XU.has(a)){let e=lM(o);e.length>0&&e[0]&&(i=e[0])}let e=YU.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
210
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function QU(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const $U=new Map([...YU,[Ij,ZU]].map(([e,t])=>[e,QU(t)]));Object.freeze([...$U.keys()]);const eW=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`]),tW=[[`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`]],nW=[[`workspace.added_dirs`,`string-list`]];function rW(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of tW){let i=oW(n,e);if(i==null)t.missingRequired.push(e);else{let n=iW(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of nW){let i=oW(n,e),a=i===void 0?r:aW(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))eW.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function iW(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function aW(e){return Array.isArray(e)&&e.every(e=>iW(e)===`string`)?`string-list`:iW(e)}function oW(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 sW(e,t){switch(e){case`vars`:return{what:e,vars:cW(t)};case`segments`:return{what:e,segments:pW(t)};case`config`:return{what:e,config:_W(t)}}}function cW(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=dW(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=lW(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:uW(r.lastUpdatedMs())})}return o}function lW(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function uW(e){return e===null?null:Math.max(0,Date.now()-e)}function dW(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,fW(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}`,fW(i));return t}function fW(e){return e.kind}function pW(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=hW(n),o=mW(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:gW(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function mW(e){let t=new Map;for(let n of Mb(e.presets))for(let r of wu(Fb(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=bu(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function hW(e){let t=[],n=new Set;for(let r of wu(jd(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 gW(e,t,n){let r=new Set;for(let i of Sx(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function _W(e){return e===null?null:e.config}const vW=[`vars`,`segments`,`config`];function yW(e){return typeof e==`string`&&vW.includes(e)}function bW(e){return Math.max(1,e-2)}var xW=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const SW=new AB,CW=new jH;ke(SW.launchStats);const wW=new dC({counters:SW,logger:Z}),TW=CR({watchers:wW,logger:Z}),{gitProvider:EW,usageStore:DW,mementoProvider:OW}=TW,kW=new NB,AW=new UV(kW,Z),jW=new fH,MW=new HN,NW=new xW(Ze()),PW=new OB({gitService:EW,sessionState:kW,watchers:wW},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),FW=60*1e3;function IW(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(E(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),QW(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,FW),a.unref())},checkNow:o}}const LW=IW(),RW=oL({entryUrl:import.meta.url,intervalMs:FW,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>LW.checkNow(),log:Z});let zW=null,BW=null,VW=0;function HW(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),QW(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),QW(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),QW(0)});try{VW=cj(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),QW(1);return}zW=lN(t.pid);let e=yN(xN(zW));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),QW(1);return}BW=e.registryPath,r.mkdirSync(Re(),{recursive:!0}),He(ze()),kW.useStorage(new FB(Ge(),500,Z)),AW.useStorage(uH(Ke(),Z)),fN({anchor:dN(t.env),isAlive:pN,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),QW(0)}}),UW(x.createServer({allowHalfOpen:!1},e=>{$W(e)}),ze(),!1)}function UW(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),QW(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}WW(e,n)}),e.listen(n,()=>GW(n))}function WW(e,n){let i=$M(eN(Ue(n)),(e,t)=>cN(e,t,{readStartTime:sN,pidAlive:pN}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),QW(1);return}}UW(e,n,!0)}function GW(e){let n=rN(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),QW(0);return}YW(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(re.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(VW/1048576)}MB`),Tj();let i=NW.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),LW.arm(),RW.arm(),JW(),KW(e,n.identity)}function KW(e,n){oN({bound:n,myPid:t.pid,readIdentity:()=>rN(e),readLease:()=>eN(Ue(e)),shutdown:e=>QW(e),log:Z}).arm()}let qW=null;function JW(){qW=fj(gj(SW.startedAt.getTime(),e=>QW(e),{rssLimitBytes:VW})),qW.arm()}function YW(e){let n=tN(Ue(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:zW});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let XW=0,ZW=!1;function QW(e){if(!ZW){ZW=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{EW.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{DW.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{wW.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{kW.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}nN(We(),t.pid),BW!==null&&bN(BW,t.pid,_N,e=>r.unlinkSync(e)),t.exit(e)}}function $W(e){XW++,SW.inFlight=XW;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>QW(r);try{e.end(LA(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{SW.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=RA(e=>{tG(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),XW=Math.max(0,XW-1),SW.inFlight=XW})}const eG=e=>({resp:e,exitAfterFlush:null});async function tG(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return eG({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return eG({ok:!0,stats:SW.snapshot({gitCache:EW.getStats(),usageCache:DW.getStats(),renderCacheSize:PW.size,effectCache:MW.getStats(),watchersActive:wW.size(),nextRestartReason:qW?.describeNextRestart()??null,handlerProbes:CW.list()})});if(e.kind===`render`){SW.requestsTotal++;let t=new Date,n=CC(t),r=t.getTime();try{let{report:t}=rW(e.hookData);for(let e of t.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let i=[];for(let e of t.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:n,got:r}of t.typeMismatches)i.push(`field '${e}' expected ${n}, got ${r}`);if(e.cwd===``&&i.push(`request 'cwd' is empty`),i.length>0)return SW.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${i.join(`; `)}`),eG({ok:!1,error:`malformed hookData: ${i.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let a=e.hookData.workspace.project_dir,{configFile:o,unknownFlagsError:s}=nG(e.args),c=e.hookData.session_id,l=DA(e),u=JSON.stringify(l);kW.get(c,`client-hints`)!==u&&kW.set(c,zU,u);let d=kW.get(c,`config-override`)??o??l.configEnv,f=PW.getOrCreate(a,e.cwd,d),p=hU({projectDir:a,cwd:e.cwd,configFile:d??null});kW.get(c,`render-origin`)!==p&&kW.set(c,mU,p);let m=l.termCols,h=bW(m??120),g=eP(l.termRows),{authoredRoots:_}=f.state,v=t=>kW.get(e.hookData.session_id,t),y=jF(f.state.config,v,e=>_.has(e)),b=await JF(e.hookData,n,{...sG,navigation:e=>jW.depth(e,kW,RI(f.state.config))},e.cwd,f.state.neededInputPaths(y.preset),y,l,{...TI(f.state.config,f.state.fileHeldSettings,v),configPath:f.configLayers.includes(f.configHome)?f.configHome:null}),x=[],S=MF(y,h),C=MW.of(c),ee=sB(f.state.config,f.state.compiled,f.state.store,f.state.registry,b,n,S,{perSegmentSink:f.state.lastRenderCellsBySegment,onRenderWarning:({message:e})=>x.push(e)},{...NF(y),effects:C}),w=kW.get(e.hookData.session_id,`click.error`);w&&kW.clear(e.hookData.session_id,`click.error`);let te=[s,f.lastError,w].filter(Boolean).join(`
211
- `),ne=RW.notice({sessionId:c,dismissed:kW.get(c,WI),enabled:y.updateNotice}),re=f.lastError===null?null:f.failedFile,ie=aP(te,ne,[f.lastWarning??``,...x].filter(Boolean).join(`
212
- `)),T=NW.sync(c,ie===null?null:sP(ie));T!==null&&Z(`warn`,`diagnostic dump failed: ${T}`);let E=cP(ee,ie,{fullText:T===null?{kind:`file`,path:NW.pathFor(c)}:{kind:`unavailable`,reason:T},failedConfigFile:re},{width:h,rowCap:g,colorCompatibility:y.colorCompatibility}),ae=Date.now()-r,oe=EW.getStats(),se=DW.getStats(),ce=C.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=ce.fades.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`;return Z(`info`,`render sid=${e.hookData.session_id??`?`} at=${n.toFixed(3)} took=${ae}ms termCols=${m??`?`} termRows=${l.termRows??`?`} width=${h} git=${oe.size}/${oe.hits}h/${oe.misses}m usage=${se.size}/${se.hits}h/${se.misses}m effect=${ce.effect} effectT=${ce.t.toFixed(3)} effectRows=${ce.made}made/${ce.reused}reused effectOwn=${le} fadeBasis=${ce.basis} stateRev=${ce.revision} fades=${ue} err=${te?`Y`:`N`} upd=${ne.length} warn=${f.lastWarning?`Y`:`N`}`),eG({ok:!0,output:E+`
213
- `})}catch(e){throw SW.requestsErrored++,e}}if(e.kind===`click`)return eG(cG(e.verb,e.value,FA(e.clientVersion)));if(e.kind===`debug`){if(!yW(e.what))return eG({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${vW.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=PW.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?oG(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):aG};return eG({ok:!0,debug:sW(e.what,n)})}return eG({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function nG(e){let{values:t,tokens:n}=y({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:AA(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const rG={sessionState:kW,dlog:Z,applyUpdate:()=>RW.act(),doctor:mH(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];PW.reload(...t);let n=PW.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),probes:CW,memento:OW,claudeInput:ZH(),history:AW,navigation:jW,configFor:e=>PW.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>PW.reload(e.projectDir,e.cwd,e.configFile??void 0)};rG.reloadConfig;const iG={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:rl,width:1/0},aG=new Map;function oG(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,$N(a,{...iG,charset:t,colorCompatibility:n}));return r}const sG={...TW,history:e=>AW.depth(e)};function cG(e,t,n){let r=$U.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...rG,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const lG={connectMs:200,budgetMs:500};async function uG(e,n){let r=n.includes(`--json`),i=await dG(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${KA(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
214
- `);return}t.stdout.write(fG(i.value))}function dG(e){return BA({kind:`debug`,what:e},lG,e=>`debug`in e?e.debug:void 0)}function fG(e){switch(e.what){case`vars`:return pG(e.vars);case`segments`:return mG(e.segments);case`config`:return hG(e.config);default:return e}}function pG(e){if(e.length===0)return`no variables (DSL not active)
215
- `;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?``:` ${_G(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${gG(a.value)}${e}${o}`)}return t.join(`
207
+ `}const FH=e=>({kind:`ok`,value:e}),IH=e=>({kind:`failed`,reason:e});var LH=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const RH=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function zH(e){return RH.test(e)?e:null}function BH(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return FH(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return FH({app:n,missing:IH(`its script could not be read (${r.reason})`)});let i=RM(r.value);return FH({app:n,missing:i===null?IH("its script is not one `cc-candybar install` wrote"):FH([i.node,i.script].filter(t=>!e.exists(t)))})}async function VH(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function HH(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Ij}://${oM}/${n}`);return(r===null?await VH(e,n):null)??{kind:`lost`,unopened:r,opener:BH(e)}}function UH(e,t,n){let r=O({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?FH(r.stdout):IH(r.stderr.trim()||r.error||r.reason)}const WH=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ij}://probe"));u.isNil() ? "" : u.path.js`;async function GH(){let e=await AH();if(e.kind!==`ok`)return IH(qA(e).split(`
208
+ `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?FH({version:t,arrivals:n}):IH(`the running daemon (${t}) predates this check`)}function KH(){return{platform:process.platform,sockets:{own:ze(),handler:Be()},now:Date.now,nonce:ce,daemon:GH,open:e=>{let t=UH(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=UH(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,WH]);if(e.kind===`failed`)return e;let t=e.value.trim();return FH(t===``?null:t)},script:e=>UH(`doctor.osadecompile`,`/usr/bin/osadecompile`,[zM(e)]),exists:r.existsSync}}const qH=/^─{20,}/,JH=/^❯(\s|$)/,YH=/›\s*stashed$/;function XH(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>qH.test(e)?[t]:[]).at(-2);return n===void 0||!JH.test(t[n+1]??``)?{kind:`no-prompt`}:YH.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const ZH={"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 QH(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=XH(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:ZH[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const $H=`cc-candybar-slash`;function eU(e,t,n,r){let i=vR(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function tU(e){let t=eU(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
209
+ `);return{inMode:n!==`0`,screen:r}}function nU(e,t){let n=eU(e,`claude-input.type`,[`load-buffer`,`-b`,$H,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,$H,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function rU(){return{read:tU,type:nU}}function iU(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function aU(e){return oU(()=>decodeURIComponent(e))}function oU(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function sU(e,t){let n=O({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const cU=(e,t)=>sU(aU(e),t),lU=(e,t)=>{let n=O({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,aU(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},uU=(e,t)=>sU(aU(e),t),dU=(e,t)=>sU(aU(e),t),fU=(e,t)=>{let n=iU(aU(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},pU=(e,t)=>{let[n=``,...r]=oU(()=>uM(e)),i=iU(n),a=zI(TU(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}_U(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},mU=/^-?\d+$/;function hU(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const gU=(e,t)=>{let[n=``,r=``,i=``]=oU(()=>uM(e)),a=iU(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!mU.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=TU(t,a),c=zI(s),l=c.rangeParamsFor(r);if(!l)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&mU.test(u)?vU(l,parseInt(u,10)):yU(`step-state`,r,l,HI(s,e=>t.sessionState.get(a,e),r)),f=hU(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);_U(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function _U(e,t,n,r){let i=r.filter(e=>e.key.startsWith(rx));if(i.length===0)return;let a=vI(TU(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function vU(e,t){return Math.max(e.min,Math.min(e.max,t))}function yU(e,t,n,r){if(r===null)return n.min;if(!mU.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return vU(n,parseInt(r,10))}const bU=`render-origin`;function xU(e){return JSON.stringify(e)}function SU(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function CU(e,t){let n=e.sessionState.get(t,bU);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return SU(n)}function wU(e,t,n){let r=e.sessionState.get(t,bU);if(r===null)return;let i=SU(r),{path:a}=EU(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function TU(e,t){return e.configFor(CU(e,t))}function EU(e){return Mk(e.projectDir,e.cwd,e.configFile??void 0)}function DU(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const OU=(e,t)=>{let[n=``,r=``,i=``]=oU(()=>uM(e)),a=iU(n),o=CU(t,a),s=t.configFor(o),c=LP(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=EU(o),d=gI(s,e=>t.sessionState.get(a,e),r);AV(DU(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},kU=(e,t)=>{let[n=``,r=``,i=``]=oU(()=>uM(e)),a=iU(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!mU.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=CU(t,a),c=t.configFor(s),l=LP(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=EU(s),f=gI(c,e=>t.sessionState.get(a,e),r),p=kV(d.path,f.key),m=typeof p==`number`?vU(u,p):yU(`step-config`,r,u,zP(f.globals,r)),h=hU(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);AV(DU(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},AU=(e,t)=>{let[n=``]=oU(()=>uM(e)),r=iU(n),i=CU(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=mI(a,o),c=_I(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=zI(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});MU(`save`,l,c);let d=EU(i);jV(DU(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(jU)].join(` `)} → ${d.path} (session=${r})`)},jU=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Vu(e.value)}`;function MU(e,t,n){for(let r of n){let n=t.validate(r.key,Vu(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const NU=(e,t)=>{let[n=``]=oU(()=>uM(e)),r=iU(n),i=CU(t,r),a=t.configFor(i),o=xI(a,e=>t.sessionState.get(r,e)),s=zI(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});MU(`save-preset`,s,o.placements);let l=EU(i),u=RV(DU(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...QC.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,ZC.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(jU)].join(` `)} → ${l.path} (session=${r})`)},PU=(e,t)=>{let[n=``]=oU(()=>uM(e)),r=iU(n),i=CU(t,r),a=CI(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new $(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=EU(i);zV(DU(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(mI(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ku.map(e=>ZC[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${ku.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},FU=(e,t)=>{let[n=``,r=``]=oU(()=>uM(e)),i=iU(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=CU(t,i),o=EU(a);BV(DU(t,i),o,r),t.reloadConfig(a);let s=ZC.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},IU=(e,t)=>{let[n=``,...r]=oU(()=>uM(e)),i=iU(n),a=CU(t,i),o=LP(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=EU(a),l=r.map(wI),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);FV(DU(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function LU(e,t){let n=(e,t)=>[...wu(Ib(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Nb(t.presets).flatMap(e=>n(t,e).map(t=>ix(bp(e),bu(t)))));return Nb(e.presets).flatMap(t=>n(e,t).map(e=>({member:ix(bp(t),bu(e)),node:e})).filter(({member:e})=>!r.has(e)))}function RU(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Qb]:[]])}const zU=(e,t)=>{let[n=``,r=``,i=``]=oU(()=>uM(e)),a=iU(n),o=CU(t,a),s=t.configFor(o),c=LP(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=CP(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=EU(o),f=VV(DU(t,a),d,r,u);t.reloadConfig(o);let p=RU(LU(s,t.configFor(o)),t.sessionState.get(a,Qb)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},BU=(e,t)=>{let[n=``]=oU(()=>uM(e)),r=iU(n);t.journal.commit();let i=t.history.undo(r);wU(t,r,i),t.dlog(`info`,`undo: restored ${lH(i)} (session=${r})`)},VU=(e,t)=>{let n=iU(aU(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,zI(TU(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},HU=(e,t)=>{let n=iU(aU(e));t.journal.commit();let r=t.history.rewind(n);wU(t,n,r),t.dlog(`info`,`rewind: put back ${lH(r)||`nothing`} as edit mode found it (session=${n})`)},UU=(e,t)=>{let[n=``]=oU(()=>uM(e)),r=iU(n);t.journal.commit();let i=t.history.redo(r);wU(t,r,i),t.dlog(`info`,`redo: re-applied ${lH(i)} (session=${r})`)},WU=(e,t)=>{iU(aU(e)),t.applyUpdate()},GU=`client-hints`;function KU(e,t){let n=e.sessionState.get(t,GU);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return OA(r)}function qU(e,t,n){let r=uT(n);e.sessionState.setBatch(t,hT(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function JU(e,t){return{...EH(e.doctor,KU(e,t),CU(e,t),n=>e.sessionState.get(t,n)),urlHandler:wH(e.clientVersion)}}const YU=(e,t)=>{let n=iU(aU(e));qU(t,n,JU(t,n))},XU=(e,t)=>{let n=zH(aU(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},ZU=(e,t)=>{let[n=``,r=``]=oU(()=>uM(e)),i=iU(n),a=dT(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=JU(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=DH(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.path.join(`.`)}=${JSON.stringify(s.fix.value)} (session=${i})`),qU(t,i,c)},QU=(e,t)=>{let[n=``,...r]=oU(()=>uM(e)),i=iU(n),a=CU(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=ZD(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=yF({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},KU(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},$U=(e,t)=>{let[n=``,r=``]=oU(()=>uM(e)),i=iU(n),a=Object.values(t.configFor(CU(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=QH(t.claudeInput,KU(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},eW=`config-override`,tW=new Map([[Bj,cU],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=iU(oU(()=>decodeURIComponent(e.slice(0,n)))),i=oU(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,eW),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,eW,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vj,lU],[Rj,pU],[zj,gU],[Gj,OU],[Kj,kU],[Zj,IU],[qj,AU],[Jj,NU],[Yj,PU],[Xj,FU],[Qj,zU],[$j,BU],[eM,UU],[tM,VU],[nM,HU],[Uj,uU],[Wj,dU],[Hj,fU],[rM,WU],[iM,YU],[aM,ZU],[oM,XU],[sM,QU],[cM,$U]]),nW=new Set([Rj,zj,Gj,Kj,Zj,qj,Jj,Yj,Xj,Qj,$j,eM,tM,nM,Hj,rM,iM,aM,sM,cM]),rW=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of mM(fM(e))){if(!i&&nW.has(a)){let e=uM(o);e.length>0&&e[0]&&(i=e[0])}let e=tW.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
210
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function iW(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const aW=new Map([...tW,[Lj,rW]].map(([e,t])=>[e,iW(t)]));Object.freeze([...aW.keys()]);const oW=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`]),sW=[[`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`]],cW=[[`workspace.added_dirs`,`string-list`]];function lW(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of sW){let i=fW(n,e);if(i==null)t.missingRequired.push(e);else{let n=uW(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of cW){let i=fW(n,e),a=i===void 0?r:dW(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))oW.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function uW(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function dW(e){return Array.isArray(e)&&e.every(e=>uW(e)===`string`)?`string-list`:uW(e)}function fW(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 pW(e,t){switch(e){case`vars`:return{what:e,vars:mW(t)};case`segments`:return{what:e,segments:yW(t)};case`config`:return{what:e,config:CW(t)}}}function mW(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=_W(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=hW(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:gW(r.lastUpdatedMs())})}return o}function hW(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function gW(e){return e===null?null:Math.max(0,Date.now()-e)}function _W(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,vW(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}`,vW(i));return t}function vW(e){return e.kind}function yW(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=xW(n),o=bW(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:SW(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function bW(e){let t=new Map;for(let n of Nb(e.presets))for(let r of wu(Ib(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=bu(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function xW(e){let t=[],n=new Set;for(let r of wu(jd(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 SW(e,t,n){let r=new Set;for(let i of Cx(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function CW(e){return e===null?null:e.config}const wW=[`vars`,`segments`,`config`];function TW(e){return typeof e==`string`&&wW.includes(e)}function EW(e){return Math.max(1,e-2)}var DW=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const OW=new IB,kW=new LH;ke(OW.launchStats);const AW=new fC({counters:OW,logger:Z}),jW=wR({watchers:AW,logger:Z}),{gitProvider:MW,usageStore:NW,mementoProvider:PW}=jW,FW=new zB,IW=new YV(FW,Z),LW=new vH,RW=new UN,zW=new DW(Ze()),BW=new PB({gitService:MW,sessionState:FW,watchers:AW},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),VW=60*1e3;function HW(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(E(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),iG(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,VW),a.unref())},checkNow:o}}const UW=HW(),WW=sL({entryUrl:import.meta.url,intervalMs:VW,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>UW.checkNow(),log:Z});let GW=null,KW=null,qW=0;function JW(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),iG(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),iG(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),iG(0)});try{qW=lj(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),iG(1);return}GW=uN(t.pid);let e=bN(SN(GW));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),iG(1);return}KW=e.registryPath,r.mkdirSync(Re(),{recursive:!0}),He(ze()),FW.useStorage(new VB(Ge(),500,Z)),IW.useStorage(gH(Ke(),Z)),pN({anchor:fN(t.env),isAlive:mN,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),iG(0)}}),YW(x.createServer({allowHalfOpen:!1},e=>{aG(e)}),ze(),!1)}function YW(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),iG(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}XW(e,n)}),e.listen(n,()=>ZW(n))}function XW(e,n){let i=eN(tN(Ue(n)),(e,t)=>lN(e,t,{readStartTime:cN,pidAlive:mN}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),iG(1);return}}YW(e,n,!0)}function ZW(e){let n=iN(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),iG(0);return}tG(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(re.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(qW/1048576)}MB`),Ej();let i=zW.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),UW.arm(),WW.arm(),eG(),QW(e,n.identity)}function QW(e,n){sN({bound:n,myPid:t.pid,readIdentity:()=>iN(e),readLease:()=>tN(Ue(e)),shutdown:e=>iG(e),log:Z}).arm()}let $W=null;function eG(){$W=pj(_j(OW.startedAt.getTime(),e=>iG(e),{rssLimitBytes:qW})),$W.arm()}function tG(e){let n=nN(Ue(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:GW});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let nG=0,rG=!1;function iG(e){if(!rG){rG=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{MW.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{NW.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{AW.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{FW.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}rN(We(),t.pid),KW!==null&&xN(KW,t.pid,vN,e=>r.unlinkSync(e)),t.exit(e)}}function aG(e){nG++,OW.inFlight=nG;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>iG(r);try{e.end(RA(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{OW.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=zA(e=>{sG(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),nG=Math.max(0,nG-1),OW.inFlight=nG})}const oG=e=>({resp:e,exitAfterFlush:null});async function sG(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return oG({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return oG({ok:!0,stats:OW.snapshot({gitCache:MW.getStats(),usageCache:NW.getStats(),renderCacheSize:BW.size,effectCache:RW.getStats(),watchersActive:AW.size(),nextRestartReason:$W?.describeNextRestart()??null,handlerProbes:kW.list()})});if(e.kind===`render`){OW.requestsTotal++;let t=new Date,n=wC(t),r=t.getTime();try{let{report:t}=lW(e.hookData);for(let e of t.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let i=[];for(let e of t.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:n,got:r}of t.typeMismatches)i.push(`field '${e}' expected ${n}, got ${r}`);if(e.cwd===``&&i.push(`request 'cwd' is empty`),i.length>0)return OW.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${i.join(`; `)}`),oG({ok:!1,error:`malformed hookData: ${i.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let a=e.hookData.workspace.project_dir,{configFile:o,unknownFlagsError:s}=cG(e.args),c=e.hookData.session_id,l=OA(e),u=JSON.stringify(l);FW.get(c,`client-hints`)!==u&&FW.set(c,GU,u);let d=FW.get(c,`config-override`)??o??l.configEnv,f=BW.getOrCreate(a,e.cwd,d),p=xU({projectDir:a,cwd:e.cwd,configFile:d??null});FW.get(c,`render-origin`)!==p&&FW.set(c,bU,p);let m=l.termCols,h=EW(m??120),g=tP(l.termRows),{authoredRoots:_}=f.state,v=t=>FW.get(e.hookData.session_id,t),y=MF(f.state.config,v,e=>_.has(e)),b=await YF(e.hookData,n,{...pG,navigation:e=>LW.depth(e,FW,zI(f.state.config))},e.cwd,f.state.neededInputPaths(y.preset),y,l,{...EI(f.state.config,f.state.fileHeldSettings,v),configPath:f.configLayers.includes(f.configHome)?f.configHome:null}),x=[],S=NF(y,h),C=RW.of(c),ee=pB(f.state.config,f.state.compiled,f.state.store,f.state.registry,b,n,S,{perSegmentSink:f.state.lastRenderCellsBySegment,onRenderWarning:e=>x.push(e)},{...PF(y),effects:C}),w=FW.get(e.hookData.session_id,`click.error`);w&&FW.clear(e.hookData.session_id,`click.error`);let te=[s,f.lastError,w].filter(Boolean).join(`
211
+ `),ne=WW.notice({sessionId:c,dismissed:FW.get(c,GI),enabled:y.updateNotice}),re=f.lastError===null?null:f.failedFile,ie=[...f.lastWarning===null?[]:[{kind:`load`,message:f.lastWarning}],...x],T=oP(te,ne,ie.map(e=>e.message).join(`
212
+ `)),E=zW.sync(c,T===null?null:cP(T));E!==null&&Z(`warn`,`diagnostic dump failed: ${E}`);let ae=lP(ee,T,{fullText:E===null?{kind:`file`,path:zW.pathFor(c)}:{kind:`unavailable`,reason:E},failedConfigFile:re},{width:h,rowCap:g,colorCompatibility:y.colorCompatibility}),oe=Date.now()-r,se=MW.getStats(),ce=NW.getStats(),le=C.lastFrame(),ue=le.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,fe=ie.map(e=>e.kind).join(`,`)||`-`;return Z(`info`,`render sid=${e.hookData.session_id??`?`} at=${n.toFixed(3)} took=${oe}ms termCols=${m??`?`} termRows=${l.termRows??`?`} width=${h} git=${se.size}/${se.hits}h/${se.misses}m usage=${ce.size}/${ce.hits}h/${ce.misses}m effect=${le.effect} effectT=${le.t.toFixed(3)} effectRows=${le.made}made/${le.reused}reused effectOwn=${ue} fadeBasis=${le.basis} stateRev=${le.revision} fades=${de(le.fades)} leaves=${de(le.leaves)} err=${te?`Y`:`N`} upd=${ne.length} warn=${fe}`),oG({ok:!0,output:ae+`
213
+ `})}catch(e){throw OW.requestsErrored++,e}}if(e.kind===`click`)return oG(mG(e.verb,e.value,IA(e.clientVersion)));if(e.kind===`debug`){if(!TW(e.what))return oG({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${wW.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=BW.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?fG(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):dG};return oG({ok:!0,debug:pW(e.what,n)})}return oG({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function cG(e){let{values:t,tokens:n}=y({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:jA(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const lG={sessionState:FW,dlog:Z,applyUpdate:()=>WW.act(),doctor:bH(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];BW.reload(...t);let n=BW.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),probes:kW,memento:PW,claudeInput:rU(),history:IW,navigation:LW,configFor:e=>BW.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>BW.reload(e.projectDir,e.cwd,e.configFile??void 0)};lG.reloadConfig;const uG={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:rl,width:1/0},dG=new Map;function fG(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,eP(a,{...uG,charset:t,colorCompatibility:n}));return r}const pG={...jW,history:e=>IW.depth(e)};function mG(e,t,n){let r=aW.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...lG,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const hG={connectMs:200,budgetMs:500};async function gG(e,n){let r=n.includes(`--json`),i=await _G(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${qA(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
214
+ `);return}t.stdout.write(vG(i.value))}function _G(e){return VA({kind:`debug`,what:e},hG,e=>`debug`in e?e.debug:void 0)}function vG(e){switch(e.what){case`vars`:return yG(e.vars);case`segments`:return bG(e.segments);case`config`:return xG(e.config);default:return e}}function yG(e){if(e.length===0)return`no variables (DSL not active)
215
+ `;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?``:` ${CG(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${SG(a.value)}${e}${o}`)}return t.join(`
216
216
  `)+`
217
- `}function mG(e){if(e.length===0)return`no segments (DSL not active)
217
+ `}function bG(e){if(e.length===0)return`no segments (DSL not active)
218
218
  `;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(`
219
219
  `)+`
220
- `}function hG(e){return e===null?`config: DSL not active
220
+ `}function xG(e){return e===null?`config: DSL not active
221
221
  `:JSON.stringify(e,null,2)+`
222
- `}function gG(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function _G(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function vG(){let e=bG();return e===null?null:r.readFileSync(e,`utf-8`)}function yG(){let e;try{e=vG()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function bG(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function xG(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const SG=5e3;function CG(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:BT(4e5,1e6),...PF(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:nw(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:AF(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function wG(e,t){let n=kk(e,e),r=Mk(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function TG(e,n=t.cwd()){let i=[],a=e===void 0?null:l.resolve(Ek(e)),o=a===null?wG(n,i):[a];if(a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let s=Pk(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await OG(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof pu&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof pu||e instanceof Error?e.message:String(e),warnings:i})}}async function EG(e,t,n){let r=hA(e,$P,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t}),{config:i}=r,a=new yB,o=new qC(a,i.globals.default_empty_value??``,void 0,new NB);try{let s=nB(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(SG);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${SG} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function DG({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u={"theme-rule":e=>c.set(`theme rule`,e),"band-floor":e=>l.add(e)};return{rendered:sB(t,n,r,i,CG(a,e.at(-1)??null,s),s,MF(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:({kind:e,message:t})=>u[e](t)},NF(a)),failures:c,advisories:l}}async function OG(e,t,n){let r=await EG(e,t,n),{config:i}=r,a=CC(new Date);try{let e=aL();try{RI(i),IP(i)}finally{e()}let t=Nb(null,i.globals.preset,i.presets),o=(e,t)=>{let n=jF(i,t=>t===`preset`?e:null,()=>t),o;try{o=DG(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Mb(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
222
+ `}function SG(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function CG(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function wG(){let e=EG();return e===null?null:r.readFileSync(e,`utf-8`)}function TG(){let e;try{e=wG()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function EG(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function DG(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const OG=5e3;function kG(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:VT(4e5,1e6),...FF(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:rw(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:jF(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function AG(e,t){let n=Ak(e,e),r=Nk(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function jG(e,n=t.cwd()){let i=[],a=e===void 0?null:l.resolve(Dk(e)),o=a===null?AG(n,i):[a];if(a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let s=Fk(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await PG(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof pu&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof pu||e instanceof Error?e.message:String(e),warnings:i})}}async function MG(e,t,n){let r=gA(e,eF,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t}),{config:i}=r,a=new TB,o=new JC(a,i.globals.default_empty_value??``,void 0,new zB);try{let s=cB(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(OG);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${OG} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function NG({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u={"theme-rule":e=>c.set(`theme rule`,e),"band-floor":e=>l.add(e)};return{rendered:pB(t,n,r,i,kG(a,e.at(-1)??null,s),s,NF(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:({kind:e,message:t})=>u[e](t)},PF(a)),failures:c,advisories:l}}async function PG(e,t,n){let r=await MG(e,t,n),{config:i}=r,a=wC(new Date);try{let e=oL();try{zI(i),LP(i)}finally{e()}let t=Pb(null,i.globals.preset,i.presets),o=(e,t)=>{let n=MF(i,t=>t===`preset`?e:null,()=>t),o;try{o=NG(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Nb(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
223
223
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
224
- `));return d}finally{r.registry.dispose()}}function kG(e){return e.map(e=>`warning: ${e}\n`).join(``)}function AG(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:kG(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:kG(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const jG=`--render`,MG=`Usage: cc-candybar check [${jG}] [config-file]\n`;function NG(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==jG);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${MG}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${MG}`}:{kind:`run`,target:n[0],render:t.includes(jG)}}async function PG(e){let n=NG(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:AG(await TG(n.target??xG(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const FG=`${EN}${TN}`;function IG(e){return`${FG}⚠ cc-candybar: ${LG(e)}\n`}function LG(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: ${wN(e.message,60)}`;case`render_failed`:return`render failed: ${wN(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${wN(e.message,60)}`}}function RG(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
225
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:IG(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function zG(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 BG=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function VG(e,t,n){return{termCols:zG(e.COLUMNS,n.columns),termRows:zG(e.LINES,n.rows),ssh:BG.some(t=>(e[t]??``)!==``),tmux:eT(e),configEnv:xG(e),claudeConfigDir:OT(e,t),mementoEnv:et(e,t)}}const HG=` (fix: click the settings menu (${Vd} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function UG({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:HG}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function WG(e){let t={sessionState:new NB},n=EB(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??DB(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}async function GG(e,t,n,r,i=void 0){let a;try{a={...bH(e,{tmux:eT(n),claudeConfigDir:OT(n,r)},{projectDir:r,cwd:r,configFile:AA(i??xG(n))??null},()=>null),urlHandler:await IH(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=lT(a);return{stdout:o.map(UG).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function KG(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
224
+ `));return d}finally{r.registry.dispose()}}function FG(e){return e.map(e=>`warning: ${e}\n`).join(``)}function IG(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:FG(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:FG(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const LG=`--render`,RG=`Usage: cc-candybar check [${LG}] [config-file]\n`;function zG(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==LG);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${RG}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${RG}`}:{kind:`run`,target:n[0],render:t.includes(LG)}}async function BG(e){let n=zG(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:IG(await jG(n.target??DG(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const VG=`${DN}${EN}`;function HG(e){return`${VG}⚠ cc-candybar: ${UG(e)}\n`}function UG(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: ${TN(e.message,60)}`;case`render_failed`:return`render failed: ${TN(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${TN(e.message,60)}`}}function WG(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
225
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:HG(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function GG(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 KG=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function qG(e,t,n){return{termCols:GG(e.COLUMNS,n.columns),termRows:GG(e.LINES,n.rows),ssh:KG.some(t=>(e[t]??``)!==``),tmux:tT(e),configEnv:DG(e),claudeConfigDir:kT(e,t),mementoEnv:et(e,t)}}const JG=` (fix: click the settings menu (${Vd} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function YG({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:JG}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function XG(e){let t={sessionState:new zB},n=MB(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??NB(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}async function ZG(e,t,n,r,i=void 0){let a;try{a={...EH(e,{tmux:tT(n),claudeConfigDir:kT(n,r)},{projectDir:r,cwd:r,configFile:jA(i??DG(n))??null},()=>null),urlHandler:await HH(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=uT(a);return{stdout:o.map(YG).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function QG(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
226
226
  Usage: cc-candybar doctor [config-file]
227
- `),t.exit(2));let n=t.cwd(),r=await GG(mH(WG),BH(),t.env,n,e[0]===void 0?void 0:l.resolve(n,Ek(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const qG=e=>e.some(e=>t.argv.includes(e));function JG(){console.log(Zw)}async function YG(){try{qG(Yw.help)&&(JG(),t.exit(0)),qG(Yw.version)&&(console.log(`cc-candybar ${qA}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await ZM(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(KM(),t.exit(0)),e===`url-handle`){await JM(t.argv[3]);return}if(e===`daemon`){HW();return}if(e===`daemon-stats`&&(await CH(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await PG(t.argv.slice(3));return}if(e===`schema`){yG();return}if(e===`doctor`){await KG(t.argv.slice(3));return}yW(e)&&(await uG(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
227
+ `),t.exit(2));let n=t.cwd(),r=await ZG(bH(XG),KH(),t.env,n,e[0]===void 0?void 0:l.resolve(n,Dk(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const $G=e=>e.some(e=>t.argv.includes(e));function eK(){console.log(Qw)}async function tK(){try{$G(Xw.help)&&(eK(),t.exit(0)),$G(Xw.version)&&(console.log(`cc-candybar ${JA}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await QM(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(qM(),t.exit(0)),e===`url-handle`){await YM(t.argv[3]);return}if(e===`daemon`){JW();return}if(e===`daemon-stats`&&(await kH(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await BG(t.argv.slice(3));return}if(e===`schema`){TG();return}if(e===`doctor`){await QG(t.argv.slice(3));return}TW(e)&&(await gG(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
228
228
 
229
229
  cc-candybar is designed to be used as a Claude Code statusLine command.
230
230
  It reads hook data from stdin and outputs formatted statusline.
@@ -240,4 +240,4 @@ Add to ~/.claude/settings.json:
240
240
  Run with --help for more options.
241
241
 
242
242
  To test output manually:
243
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),JG(),t.exit(1));let i=RG(await ZA(r,t.argv,t.cwd(),VG(t.env,t.cwd(),t.stderr)));i.debug!==null&&D(i.debug),i.kick&&_j(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}YG();export{};
243
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),eK(),t.exit(1));let i=WG(await QA(r,t.argv,t.cwd(),qG(t.env,t.cwd(),t.stderr)));i.debug!==null&&D(i.debug),i.kick&&vj(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}tK();export{};