@promptctl/cc-candybar 1.36.0 → 1.37.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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as e}from"node:module";import t from"node:process";import{json as n}from"node:stream/consumers";import r,{createReadStream as i,existsSync as a,statSync as o,watch as s}from"node:fs";import c,{basename as l,dirname as u,join as d}from"node:path";import f,{homedir as p}from"node:os";import{spawn as m,spawnSync as h}from"node:child_process";import g from"node:net";import{URL as _,URLSearchParams as v,fileURLToPath as y}from"node:url";import{parseArgs as b}from"node:util";import{get as x}from"node:https";import{createHash as S}from"node:crypto";import{setTimeout as C}from"node:timers/promises";import{open as w,readFile as ee,readdir as T,stat as te}from"node:fs/promises";import{createInterface as ne}from"node:readline";import{clearInterval as re,setInterval as E}from"node:timers";import D from"node:v8";var ie=Object.create,ae=Object.defineProperty,oe=Object.getOwnPropertyDescriptor,se=Object.getOwnPropertyNames,ce=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty,ue=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),de=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!le.call(e,s)&&s!==n&&ae(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=oe(t,s))||r.enumerable});return e},fe=(e,t,n)=>(n=e==null?{}:ie(ce(e)),de(t||!e||!e.__esModule?ae(n,`default`,{value:e,enumerable:!0}):n,e));function O(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const pe={"click.pbcopy":1e3,"click.open":1e3},me=new Map;function he(e){let t=pe[e];if(t===void 0)return{allowed:!0};let n=me.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function ge(e){me.set(e,Date.now())}function k(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let _e=null;function ve(e){_e=e}async function ye(e){let t=he(e.category);if(!t.allowed)return k(e.category,t.minIntervalMs,t.sinceLastMs);ge(e.category);let n=Date.now();return _e?.onStart(e.category),new Promise(t=>{let r;try{r=m(e.bin,e.args??[],{cwd:e.cwd,env:e.env,stdio:[`pipe`,`pipe`,`pipe`]})}catch(r){_e?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:r instanceof Error?r.message:String(r)});return}let i=``,a=``,o=!1,s=null,c=null,l=!1,u=r=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),_e?.onEnd(e.category,Date.now()-n),t(r))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,e=>{u({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:e.message})}),r.on(`close`,(e,t)=>{if(l){u({ok:!1,reason:`timeout`,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){u({ok:!0,stdout:i,stderr:a,exitCode:e});return}u({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>{l=!0,r.pid!==void 0&&(r.kill(`SIGTERM`),c=setTimeout(()=>{r.kill(`SIGKILL`)},250))},e.timeoutMs)),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function be(e){let t=he(e.category);if(!t.allowed)return k(e.category,t.minIntervalMs,t.sinceLastMs);ge(e.category);let n=Date.now();_e?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=h(e.bin,e.args??[],{cwd:e.cwd,env:e.env,input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});_e?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:t.error.message};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return _e?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:t instanceof Error?t.message:String(t)}}}function xe(e){let t=he(e.category);if(!t.allowed)return k(e.category,t.minIntervalMs,t.sinceLastMs);ge(e.category);let n=Date.now();_e?.onStart(e.category);let r=Se(e);return _e?.onEnd(e.category,Date.now()-n),r}function Se(e){let t;try{t=m(e.bin,e.args??[],{cwd:e.cwd,env:e.env,detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function Ce(e){let t=process.env[e];return t&&t.length>0?t:void 0}function we(){let e=Ce(`XDG_STATE_HOME`)??c.join(f.homedir(),`.local`,`state`);return c.join(e,`cc-candybar`)}function Te(){let e=Ce(`XDG_CACHE_HOME`)??c.join(f.homedir(),`.cache`);return c.join(e,`cc-candybar`)}function Ee(){return we()}function De(){let e=process.env.CC_CANDYBAR_SOCKET;if(e)return e;let t=f.userInfo().uid;return c.join(`/tmp`,`cc-candybar-${t}`,`socket`)}function Oe(e){r.mkdirSync(e,{recursive:!0,mode:448});let t=r.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=f.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function ke(e){Oe(c.dirname(e));for(let t of[e,A(e)])try{if(r.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function A(e){return`${e}.lease`}function Ae(){return A(De())}function je(){return c.join(we(),`session-state.json`)}function Me(){return c.join(we(),`config-overrides.json`)}function Ne(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=f.userInfo().uid;return c.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Pe(){return c.join(we(),`spawn.lock`)}function Fe(){return c.join(we(),`spawn.cooldown`)}function Ie(){return c.join(we(),`spawn.backoff`)}function Le(){return c.join(we(),`daemon.log`)}function Re(e){let t=Be(e.termCols),n=Ve(e.ssh);return{...t!==void 0&&{termCols:t},...n!==void 0&&{ssh:n}}}const ze=1e4;function Be(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>ze?ze:t}function Ve(e){return typeof e==`boolean`?e:void 0}var He=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Ue(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function We(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 He(`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 He(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Ge(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=We(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(Ue(t))})}async function Ke(e,t,n){let r=null;try{r=await Ze(De(),t.connectMs);let i=await Ge(r,{v:3,...e},t.budgetMs);return Ye(e.kind,i,n)}catch(e){return Xe(e)}finally{r&&r.destroy()}}function qe(e,t){return typeof e==`string`?e:t}function Je(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Ye(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=qe(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Je(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 Xe(e){if(e instanceof He||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 Ze(e,t){return new Promise((n,r)=>{let i=g.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 Qe(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 $e={connectMs:50,budgetMs:150},et={connectMs:50,budgetMs:200};function tt(e){let t=e.output;return typeof t==`string`?t:void 0}function nt(e,t,n,r){return Ke({kind:`render`,hookData:e,args:t,cwd:n,...r},$e,tt)}function rt(e,t){return Ke({kind:`click`,verb:e,value:t},et,tt)}function it(e={}){if(bt()!==null)return;let n=e.spawn??xt,r=_t();if(r.kind===`contended`){let e=ot();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),at(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),at(n);return}try{at(n)}finally{yt()}}function at(e){pt()&&st(e)}function ot(){try{let e=r.statSync(Pe());return Date.now()-e.mtimeMs}catch{return null}}function st(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
3
3
  `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function ct(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function lt(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function ut(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 dt(e,n){try{r.mkdirSync(c.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 ft(){try{r.unlinkSync(Ie())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function pt(){let e=Fe(),n=Ie(),r=ut(n),i=ct(mt(e),lt(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`),ht(e),dt(n,Math.min(r+1,5)),!0)}function mt(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function ht(e){try{r.mkdirSync(c.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 gt=null;function _t(){let e=Pe();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 gt={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(!vt(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 vt(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function yt(){if(!gt)return;let{fd:e,path:t}=gt;gt=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function bt(){try{return r.mkdirSync(Ee(),{recursive:!0}),null}catch(e){return`mkdir ${Ee()}: ${e.message}`}}function xt(){let e=t.execPath,n=t.argv[1];return n?xe({bin:e,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const St=`cc-candybar`,Ct=`dispatch`,wt=`set-state`,Tt=`step-state`,Et=`copy`,Dt=`open-vscode`,Ot=`show-config-error`,kt=`show-config-warning`,At=`set-config`,jt=`step-config`,Mt=`reset-config`,Nt=`apply-layout-op`,Pt=`undo`,j=`redo`;function Ft(e){return e.map(encodeURIComponent).join(`/`)}function M(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function It(e){return`${St}://${Ct}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Ft(e.args)}`)}`).join(`&`)}`}function Lt(e){return new v(e).getAll(`e`).map(Rt)}function Rt(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const zt=`closed`;function Bt(e,t){return{kind:`state`,key:e,default:t}}function Vt(e,t){return{set:e,cycle:[zt,t]}}const Ht=`@promptctl/cc-candybar`,Ut=`CCCandybarURLHandler`,Wt=[],Gt={"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 Kt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function qt(e,t){return[e,...t].map(Kt).join(` `)}function Jt(){return c.join(f.homedir(),`Applications`,`${Ut}.app`)}function Yt(){return c.join(f.homedir(),`.claude`,`settings.json`)}function Xt(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Zt(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function Qt(){return c.join(Zt(),`bin`,`cc-candybar`)}function $t(){return c.join(Zt(),`dist`,`index.mjs`)}function en(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(`
4
- `)}function tn(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function nn(t){let n=Gt[`${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:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function N(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function rn(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 ${Ht}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function an(){let e=tn(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=nn(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname($t()),{recursive:!0}),r.mkdirSync(c.dirname(Qt()),{recursive:!0}),N(e,$t()),N(t.sourcePath,Qt()),r.chmodSync(Qt(),493),r.rmSync(c.join(Zt(),`url-handler.mjs`),{force:!0});let n=rn(Qt());return process.stdout.write(`Staged cc-candybar v1.36.0 runtime at ${Zt()}\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:Qt(),distPath:$t(),entryKind:n}}function on(){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>${St}</string>`,` </array>`,` </dict>`,`</array>`].join(`
4
+ `)}function tn(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function nn(t){let n=Gt[`${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:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function N(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function rn(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 ${Ht}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function an(){let e=tn(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=nn(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname($t()),{recursive:!0}),r.mkdirSync(c.dirname(Qt()),{recursive:!0}),N(e,$t()),N(t.sourcePath,Qt()),r.chmodSync(Qt(),493),r.rmSync(c.join(Zt(),`url-handler.mjs`),{force:!0});let n=rn(Qt());return process.stdout.write(`Staged cc-candybar v1.37.0 runtime at ${Zt()}\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:Qt(),distPath:$t(),entryKind:n}}function on(){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>${St}</string>`,` </array>`,` </dict>`,`</array>`].join(`
5
5
  `)}]}function sn(e){let t=Jt();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=be({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,en(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of on())be({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of on()){let n=be({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 ${St}:// with Launch Services\n`);let a=be({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(`✓ ${Ut}.app installed and registered.\n`),process.stdout.write(` Test: open '${St}://hello-world' && pbpaste\n`)}function cn(){Xt(),sn(an().distPath)}function ln(e,t=St){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:Et,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function un(e){e||(process.stderr.write(`url-handle: missing URL argument.
6
6
  `),process.exit(1));let t;try{t=ln(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await rt(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(it(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(dn(n)+`
7
7
  `),process.exit(1)}function dn(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 fn(){return`✓ install complete.
@@ -82,54 +82,54 @@ Use 'override' annotation for methods overridden by subclass.`)}}var na=oa(0),ra
82
82
  `)),u.isContinuation&&h.push(new Y(this._continuationMarker,c));let d;n===0&&f?d={ch:`▲`,style:m}:n===a-1&&p&&(d={ch:`▼`,style:m});let _=u.isContinuation?U(Math.max(0,e.maxWidth-this._markerWidth)):U(e.maxWidth);this._emitRowContent(h,u,o===r&&g,s,l,d,_)}for(let t=0;t<o;t++)h.push(new Y(`
83
83
  `)),h.push(new Y(Xi(``,U(e.maxWidth)),s));return h}_emitRowContent(e,t,n,r,i,a,o){let s=t.content,c=n?this.cursorPosition-t.valueStart:-1;if(a===void 0){if(!n){s.length>0&&e.push(new Y(s,r));return}let t=s.slice(0,c),a=$i(s,Yi(c)),o=s.slice(c,a)||` `,l=s.slice(a);t.length>0&&e.push(new Y(t,r)),e.push(new Y(o,i)),l.length>0&&e.push(new Y(l,r));return}let l=U(H(a.ch)),u=U(Math.max(0,o-l)),[d]=Zi(s,u),f=Xi(d,u),p=n&&c>=0?H(s.slice(0,c)):-1;if(p>=0&&p<u){let[t,n]=Zi(f,U(p)),a=``;for(let e of n){a=e;break}let o=a||` `,s=n.slice(a.length);t.length>0&&e.push(new Y(t,r)),e.push(new Y(o,i)),s.length>0&&e.push(new Y(s,r))}else f.length>0&&e.push(new Y(f,r));e.push(new Y(a.ch,a.style))}_computeVisualRows(e){let t=U(Math.max(1,e)),n=U(Math.max(1,t-this._markerWidth)),r=[],i=this.value.split(`
84
84
  `),a=0;for(let e=0;e<i.length;e++){let o=i[e];if(this._wrap!==void 0){let e=this._wrap(o,{firstWidth:t,continuationWidth:n});if(e.length===0)r.push({content:``,valueStart:Yi(a),isContinuation:!1});else for(let t=0;t<e.length;t++){let n=e[t];r.push({content:n.content,valueStart:Yi(a+n.start),isContinuation:t>0})}}else r.push({content:o,valueStart:Yi(a),isContinuation:!1});a+=o.length+1}return r}measure(e){return{minimum:10,maximum:Math.max(10,Math.max(H(this.value),H(this.placeholder))+2)}}get scrollIndicatorText(){if(this._scrollIndicator!==`indices`||this._maxRows===void 0)return;let e=this._visualRows;if(!(e===null||e.length<=this._maxRows))return`[${this._cursorVisualRow()+1}/${e.length}]`}resolvePalette(e){let t=this._theme.palette.get(e);return q.fromRgba(t)}}})();var Us=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Ws=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t;let n=_s,r=[],i,a=[],o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C,w,ee;return class extends n{static{let T=typeof Symbol==`function`&&Symbol.metadata?Object.create(n[Symbol.metadata]??null):void 0;i=[(e=X.observable).shallow.bind(e)],s=[X.observable],u=[X.observable],p=[X.observable],g=[X.observable],y=[(t=X.observable).ref.bind(t)],S=[X.action],C=[X.action],w=[X.action],ee=[X.action],Ws(this,null,i,{kind:`accessor`,name:`options`,static:!1,private:!1,access:{has:e=>`options`in e,get:e=>e.options,set:(e,t)=>{e.options=t}},metadata:T},a,o),Ws(this,null,s,{kind:`accessor`,name:`selectedIndex`,static:!1,private:!1,access:{has:e=>`selectedIndex`in e,get:e=>e.selectedIndex,set:(e,t)=>{e.selectedIndex=t}},metadata:T},c,l),Ws(this,null,u,{kind:`accessor`,name:`expanded`,static:!1,private:!1,access:{has:e=>`expanded`in e,get:e=>e.expanded,set:(e,t)=>{e.expanded=t}},metadata:T},d,f),Ws(this,null,p,{kind:`accessor`,name:`highlightedIndex`,static:!1,private:!1,access:{has:e=>`highlightedIndex`in e,get:e=>e.highlightedIndex,set:(e,t)=>{e.highlightedIndex=t}},metadata:T},m,h),Ws(this,null,g,{kind:`accessor`,name:`filter`,static:!1,private:!1,access:{has:e=>`filter`in e,get:e=>e.filter,set:(e,t)=>{e.filter=t}},metadata:T},_,v),Ws(this,null,y,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:T},b,x),Ws(this,null,S,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:T},null,r),Ws(this,null,C,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:T},null,r),Ws(this,null,w,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:T},null,r),Ws(this,null,ee,{kind:`method`,name:`handleFocus`,static:!1,private:!1,access:{has:e=>`handleFocus`in e,get:e=>e.handleFocus},metadata:T},null,r),T&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:T})}id=Us(this,r);focusable=!0;#e=Us(this,a,void 0);get options(){return this.#e}set options(e){this.#e=e}#t=(Us(this,o),Us(this,c,void 0));get selectedIndex(){return this.#t}set selectedIndex(e){this.#t=e}#n=(Us(this,l),Us(this,d,!1));get expanded(){return this.#n}set expanded(e){this.#n=e}#r=(Us(this,f),Us(this,m,void 0));get highlightedIndex(){return this.#r}set highlightedIndex(e){this.#r=e}#i=(Us(this,h),Us(this,_,``));get filter(){return this.#i}set filter(e){this.#i=e}get filteredOptions(){let e=this.filter.toLowerCase(),t=[];for(let n=0;n<this.options.length;n++){let r=this.options[n];r.toLowerCase().includes(e)&&t.push({label:r,idx:n})}return t}#a=(Us(this,v),Us(this,b,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}constructor(e){super(),Us(this,x),this.id=e.id??`dropdown-${Math.random().toString(36).slice(2,8)}`,this.options=[...e.options],this.selectedIndex=this.clampIndex(e.selectedIndex??0),this.highlightedIndex=this.selectedIndex,this.disabled=e.disabled??!1,this._theme=e.theme??po}clampIndex(e){return this.options.length===0?0:Math.max(0,Math.min(e,this.options.length-1))}setTheme(e){this._theme=e}handleKey(e){if(this.disabled)return;let t=e.character.length===1&&!e.ctrl&&!e.meta&&e.character>=` `&&e.character!==``;if(!this.expanded){if(e.key===`enter`||e.key===`space`){this.expanded=!0,this.highlightedIndex=this.clampIndex(this.selectedIndex),e.stop();return}t&&(this.expanded=!0,this.filter+=e.character,this.highlightedIndex=0,e.stop());return}switch(e.key){case`up`:this.highlightedIndex=Math.max(0,this.highlightedIndex-1),e.stop();return;case`down`:{let t=Math.max(0,this.filteredOptions.length-1);this.highlightedIndex=Math.min(t,this.highlightedIndex+1),e.stop();return}case`enter`:{let t=this.filteredOptions[this.highlightedIndex];if(e.stop(),t===void 0)return;this.selectedIndex=t.idx,this.filter=``,this.expanded=!1,this.emitChange(),this.emitSubmit();return}case`escape`:this.filter=``,this.expanded=!1,e.stop();return;case`backspace`:this.filter=this.filter.slice(0,-1),this.highlightedIndex=0,e.stop();return;case`tab`:this.filter=``,this.expanded=!1,e.stop();return}t&&(this.filter+=e.character,this.highlightedIndex=0,e.stop())}handleMouse(e){if(this.disabled||e.type!==`mouse_up`)return;let t=this.bounds;if(!t)return;let n=e.x>=t.x&&e.x<t.x+t.width&&e.y>=t.y&&e.y<t.y+t.height;if(!this.expanded){n&&(this.expanded=!0,this.highlightedIndex=this.clampIndex(this.selectedIndex));return}if(!n){this.filter=``,this.expanded=!1;return}let r=e.y-t.y;if(r===0){this.filter=``,this.expanded=!1;return}let i=this.filteredOptions[r-1];i!==void 0&&(this.selectedIndex=i.idx,this.filter=``,this.expanded=!1,this.emitChange(),this.emitSubmit())}handleFocus(e){super.handleFocus(e),e.type===`blur`&&(this.filter=``,this.expanded=!1)}render(e){let t=e.asciiOnly?`v`:`▾`,n=this.focused?e.asciiOnly?`|`:`│`:``,r=this.maxLabelLen(),i=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0}):new J({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),underline:this.focused}),a=this.headerText(r,n);return[new Y(`[`,i),new Y(`${a} ${t}`,i),new Y(`]`,i)]}headerText(e,t){if(this.filter===``){let t=this.options[this.selectedIndex]??``,n=H(t);if(n>=e)return Xi(t,U(e));let r=e-n,i=Math.floor(r/2),a=r-i;return` `.repeat(i)+t+` `.repeat(a)}let n=Math.max(0,e-H(t)-1),[r]=Zi(this.filter,U(n));return Xi(` `+r+t,U(e))}renderOverlay(e){if(!this.expanded)return null;let t=this.maxLabelLen(),n=this.filteredOptions;if(n.length===0)return this.renderNoMatchRow(t);let r=[];for(let e=0;e<n.length;e++)e>0&&r.push(new Y(`
85
- `)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${Xi(`(no matches)`,U(e))} `,n=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0}):new J({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),dim:!0});return[new Y(` `,n),new Y(t,n),new Y(` `,n)]}renderOptionRow(e,t,n){let r=` ${Xi(e.label,U(n))} `,i=e.idx===this.selectedIndex,a=t===this.highlightedIndex,o=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0}):a?new J({color:this.resolvePalette(`text-primary`),bgcolor:this.resolvePalette(`primary-muted`)}):i?new J({color:this.resolvePalette(`on-primary`),bgcolor:this.resolvePalette(`primary`)}):new J({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`)});return[new Y(` `,o),new Y(r,o),new Y(` `,o)]}maxLabelLen(){let e=0;for(let t of this.options){let n=H(t);n>e&&(e=n)}return e}measure(e){let t=this.maxLabelLen()+4;return{minimum:t,maximum:t}}resolvePalette(e){let t=this._theme.palette.get(e);return q.fromRgba(t)}}})();var Gs=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Ks=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t,n,r,i;let a=_s,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],w=[],ee,T,te,ne;return class extends a{static{let re=typeof Symbol==`function`&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;s=[X.observable],u=[(e=X.observable).ref.bind(e)],p=[(t=X.observable).ref.bind(t)],g=[(n=X.observable).ref.bind(n)],y=[(r=X.observable).ref.bind(r)],S=[(i=X.observable).ref.bind(i)],ee=[X.action],T=[X.action],te=[X.action],ne=[X.action],Ks(this,null,s,{kind:`accessor`,name:`value`,static:!1,private:!1,access:{has:e=>`value`in e,get:e=>e.value,set:(e,t)=>{e.value=t}},metadata:re},c,l),Ks(this,null,u,{kind:`accessor`,name:`min`,static:!1,private:!1,access:{has:e=>`min`in e,get:e=>e.min,set:(e,t)=>{e.min=t}},metadata:re},d,f),Ks(this,null,p,{kind:`accessor`,name:`max`,static:!1,private:!1,access:{has:e=>`max`in e,get:e=>e.max,set:(e,t)=>{e.max=t}},metadata:re},m,h),Ks(this,null,g,{kind:`accessor`,name:`step`,static:!1,private:!1,access:{has:e=>`step`in e,get:e=>e.step,set:(e,t)=>{e.step=t}},metadata:re},_,v),Ks(this,null,y,{kind:`accessor`,name:`width`,static:!1,private:!1,access:{has:e=>`width`in e,get:e=>e.width,set:(e,t)=>{e.width=t}},metadata:re},b,x),Ks(this,null,S,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:re},C,w),Ks(this,null,ee,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:re},null,o),Ks(this,null,T,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:re},null,o),Ks(this,null,te,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:re},null,o),Ks(this,null,ne,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:re},null,o),re&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:re})}id=Gs(this,o);focusable=!0;#e=Gs(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Gs(this,l),Gs(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Gs(this,f),Gs(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Gs(this,h),Gs(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Gs(this,v),Gs(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Gs(this,x),Gs(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Gs(this,w),!1);constructor(e={}){super(),this.id=e.id??`slider-${Math.random().toString(36).slice(2,8)}`,this.min=e.min??0,this.max=e.max??100,this.step=e.step??1;let t=e.width??20;if(!Number.isInteger(t)||t<1)throw RangeError(`Slider width must be a positive integer; got ${t}`);this.width=t,this.value=qs(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??po}setTheme(e){this._theme=e}handleKey(e){if(!this.disabled)switch(e.key){case`left`:this.setValue(this.value-this.step),e.stop();return;case`right`:this.setValue(this.value+this.step),e.stop();return;case`home`:this.setValue(this.min),e.stop();return;case`end`:this.setValue(this.max),e.stop();return}}handleMouse(e){if(!this.disabled){if(e.type===`mouse_down`){this._dragging=!0,this.setValueFromMouseX(e.x);return}if(e.type===`mouse_move`){this._dragging&&this.setValueFromMouseX(e.x);return}if(e.type===`mouse_up`){let t=this._dragging;this._dragging=!1,t&&(this.setValueFromMouseX(e.x),this.emitSubmit());return}}}setValue(e){let t=qs(e,this.min,this.max,this.step);t!==this.value&&(this.value=t,this.emitChange())}setValueFromMouseX(e){let t=this.bounds;if(!t)return;let n=Math.max(1,this.width-1),r=Math.max(0,Math.min(this.width-1,e-t.x))/n,i=this.min+r*(this.max-this.min);this.setValue(i)}render(e){let t=e.asciiOnly?`-`:`─`,n=e.asciiOnly?`*`:`●`,r=this.max-this.min,i=r===0?0:(this.value-this.min)/r,a=Math.round(i*(this.width-1)),o={underline:this.focused},s=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new J({color:this.resolvePalette(`primary`),...o}),c=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new J({color:this.resolvePalette(`surface`),...o}),l=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,bold:!0,...o}):new J({color:this.resolvePalette(`primary`),bold:!0,...o}),u=[];a>0&&u.push(new Y(t.repeat(a),s)),u.push(new Y(n,l));let d=this.width-a-1;return d>0&&u.push(new Y(t.repeat(d),c)),u}measure(e){return{minimum:this.width,maximum:this.width}}resolvePalette(e){let t=this._theme.palette.get(e);return q.fromRgba(t)}}})();function qs(e,t,n,r){let i=Math.max(t,Math.min(n,e));if(r<=0)return i;let a=t+Math.round((i-t)/r)*r;return Math.max(t,Math.min(n,a))}new TextEncoder,new TextDecoder(`utf-8`),new TextDecoder(`ascii`);function Js(e,t){if(!(e instanceof Vo))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=e.style.add(t),n}function Ys(e){return{fn:(t=>Js(t,e)),argTypes:[`liftable`],returnType:`T`}}function Xs(e){return{fn:((t,n)=>Js(n,new J({[e]:q.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Zs(e,t){return new J({[e]:t})}function Qs(){let e={};for(let t of xo)e[t]=Ys(Zs(t,!0)),e[`not_${t}`]=Ys(Zs(t,!1));for(let[t,n]of Object.entries(Co))e[t]=Ys(Zs(n,!0));return e}const $s={fn:((e,t)=>Js(t,J.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},ec={fn:((e,t)=>Js(t,new J({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function tc(){return{fg:Xs(`color`),bg:Xs(`bgcolor`),...Qs(),link:ec,style:$s}}function nc(e,t){if(!Ia.test(e.trim()))throw 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)}) …`);return La(e)}function rc(e,t){return{fn:t,argTypes:e,returnType:`string`}}function ic(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}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const ac=rc([`string`,`int`],((e,t)=>Wa(nc(e,`darken`),ic(t,`darken`,`levels`)).hex)),oc=rc([`string`,`int`],((e,t)=>Wa(nc(e,`lighten`),-ic(t,`lighten`,`levels`)).hex)),sc={min:0,max:100,note:`0 = from, 100 = toward`},cc=rc([`string`,`string`,`float`],((e,t,n)=>_a(nc(e,`mix`),nc(t,`mix`),ic(n,`mix`,`percentage`,sc)/100).hex)),lc={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},uc=rc([`string`],(e=>qa(nc(e,`contrastOn`)).hex)),dc=rc([`string`,`string`,`float`],((e,t,n)=>Xa(nc(e,`readableOn`),nc(t,`readableOn`),ic(n,`readableOn`,`ratio`,lc)).hex)),fc={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function pc(){let e={};for(let[t,n]of Object.entries(fc)){let r=t;e[n]=rc([`string`,`float`],((e,t)=>{let i={...Ea,[r]:ic(t,n,`amount`)};return Pa.fromRgba(nc(e,n)).applyKey(i).toRgba().hex}))}return e}function mc(){return{darken:ac,lighten:oc,mix:cc,contrastOn:uc,readableOn:dc,...pc()}}function hc(e){return{color:{fn:(t=>Ra(e(),t).hex),argTypes:[`string`],returnType:`string`}}}function gc(){return{...tc(),...mc()}}new J({color:`red`,dim:!0});const _c={dark:`textual-dark`,light:`textual-light`};function vc(e){return _c[e]??e}function yc(e,t){return e??t??`textual-dark`}function bc(){return Object.keys(_c)}function xc(){return[...ro(),...bc()]}function Sc(e,t,n,r){let i=e??t??n;return Object.prototype.hasOwnProperty.call(r,i)?i:n}function Cc(e,t,n){return Sc(e,t,`none`,n)}function wc(e,t){let n=e[t];if(n===void 0)throw Error(`Look "${t}" is not declared in this config — effectiveLookName collapses unknown names to "none", and every merged config carries "none"; a miss here is merge/policy drift`);return n}const Tc=[`powerline`,`capsule`,`plain`];function Ec(e){return Tc.includes(e)}function Dc(e,t){let n=e??t??`powerline`;return Ec(n)?n:`powerline`}const Oc=[`unicode`,`ascii`],kc=[`truecolor`,`256`,`ansi`,`none`];var Ac=class extends Error{file;issues;constructor(e,t){super(Nc(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function Z(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=jc(e,n,i);if(t===-1)return r===void 0?void 0:Mc(e,r);n=t,r=t}return r===void 0?void 0:Mc(e,r)}function jc(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 Mc(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Nc(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(`
86
- `)}function Pc(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 ${Bc(i)}`,line:Z(e.source,[...t.split(`.`),r])}),null)}function Fc(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 ${Bc(i)}`,line:Z(e.source,[...t.split(`.`),`default`])});return}return i}}function Ic(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 ${Bc(i)}`,line:Z(e.source,[...t.split(`.`),r])});return}return i}}function Lc(e,t,n){let r=Ic(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:Z(e.source,[...t.split(`.`),`palette`])});return}return r}}function Rc(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 ${Vc(a)}`,line:Z(e.source,[...t.split(`.`),r])});return}return a}}function zc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Vc(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Hc(e,t,n,r){return zc(r)?(Wc(e,n,r,t.noun,new Set(Object.keys(t.fields))),Uc(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Bc(r)}`,line:Z(e.source,n.split(`.`))}),null)}function Uc(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}function Wc(e,t,n,r,i){for(let a of Object.keys(n))i.has(a)||e.issues.push({path:`${t}.${a}`,message:`Unknown ${r} "${a}". Expected one of: ${[...i].join(`, `)}`,line:Z(e.source,[...t.split(`.`),a])})}function Gc(e,t,n,r){if(!zc(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Bc(r)}`,line:Z(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:Z(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:Z(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:Z(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Kc(e,t,n,r){if(!zc(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Bc(r)}`,line:Z(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 ${Bc(i)}`,line:Z(e.source,n.split(`.`))}),null;let a=t.arms;return i in a?a[i].parse(e,n,r):(e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:Z(e.source,[...n.split(`.`),t.tag])}),null)}function qc(e){return(...t)=>e()(...t)}function Jc(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:Z(n.source,o.split(`.`))}),null}return a}}function Yc(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ic(e,t,r,n)}}function Xc(){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 ${Bc(i)}`,line:Z(e.source,[n])});return}return i}}}}function Zc(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 ${Vc(o)}`,line:Z(e.source,[i])});return}return o}}}}function Qc(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 ${Vc(a)}`,line:Z(e.source,[r])});return}return a}}}}function $c(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Lc(e,t,r)}}function el(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Pc(e,t,r,n)??void 0}}function tl(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Rc(t,n,i,r,e)}}function nl(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 rl(e){return nl(e.fields)}function il(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function al(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function ol(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function sl(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:{...t.segments,...e.segments??{}},root:e.root===void 0?t.root:e.root,actions:{...t.actions,...e.actions??{}},looks:{...t.looks,...e.looks??{}},presets:{...t.presets,...e.presets??{}},helpers:{...t.helpers,...e.helpers??{}}}}function cl(e,t){let n=Object.entries(t);if(n.length===0)return e;let r=Object.assign(Object.create(null),e.segments);for(let[e,t]of n){let n=r[e];n!==void 0&&(r[e]={...n,palette:t})}return{...e,segments:r}}const ll={required:!1,json:{enum:[...kc]},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: ${kc.join(`, `)}`,line:Z(e.source,[...t.split(`.`),n])});return}return Rc(e,t,r,n,kc)}},ul={default_bg:Yc(),default_fg:Yc(),default_empty_value:Yc(),default_separator:Yc(),default_truncate_marker:Yc(),palette:$c(),look:Yc(),preset:Yc(),style:tl(Tc),autoWrap:Xc(),padding:Zc({min:0,max:16}),charset:tl(Oc),colorCompatibility:ll},dl={noun:`globals key`,fields:ul},fl={required:!1,json:{not:{},description:`not allowed inside a preset — a preset cannot select a preset`},parse:(e,t,n,r)=>{r[n]!==void 0&&e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: a preset cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a preset naming another would be a second authority over that, and a cyclic one. Set the default arrangement in the top-level globals.preset instead.`,line:Z(e.source,[...t.split(`.`),n])})}},pl={noun:`preset globals key`,fields:{...ul,preset:fl}};function ml(e,t,n){return n===void 0?{}:Hc(e,dl,t,n)??{}}function hl(e,t,n){return Hc(e,pl,t,n)??{}}function gl(){return rl(pl)}const _l=new Set(Object.keys(dl.fields));function vl(e){return _l.has(e)}function yl(){return[..._l]}function bl(e,t,n,r){return n.cache===void 0?(ti.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Qr.join(`, `)})`,line:Z(e.source,t.split(`.`))}),null):El(e,`${t}.cache`,n.cache)}function xl(e,t,n){if(n.cache!==void 0)return El(e,`${t}.cache`,n.cache)??void 0}function Sl(e){return{required:!0,json:kl(),parse:(t,n,r,i)=>bl(t,n,i,e)??void 0}}function Cl(){return{required:!1,json:kl(),parse:(e,t,n,r)=>xl(e,t,r)}}function wl(e,t,n){return e.issues.push({path:t,message:n,line:Z(e.source,t.split(`.`))}),null}const Tl={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&jl(n)?{ttl:n}:wl(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Vc(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:wl(e,t,`cache.watch_file must be a non-empty path string, got ${Vc(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:wl(e,t,`cache.depends_on must be an array of variable-name strings, got ${Vc(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:wl(e,t,`cache.key must be a non-empty template string, got ${Vc(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:wl(e,t,`cache.never must be the literal boolean true, got ${Vc(n)}`)}}};function El(e,t,n){return Gc(e,Tl,t,n)}const Dl={noun:`time-variable cache`,arms:{ttl:Tl.arms.ttl}};function Ol(){return{required:!1,json:ol(Dl),parse:(e,t,n,r)=>r.cache===void 0?void 0:Gc(e,Dl,`${t}.cache`,r.cache)??void 0}}function kl(){return ol(Tl)}const Al=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function jl(e){return Al.test(e)}function Ml(e,t,n){if(n===void 0)return{};if(!zc(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Bc(n)}`,line:Z(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Kc(e,Kl,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Nl(){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 ${Bc(i)}`,line:Z(e.source,t.split(`.`))});return}return i}}}function Pl(){return{required:!0,json:{enum:[...ei]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!ei.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${ei.join(`, `)}, got ${JSON.stringify(i)}`,line:Z(e.source,[...t.split(`.`),`field`])});return}return i}}}function Fl(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Fc(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Il={value:Nl(),default:Yc()},Ll={path:el(),type:tl([`string`,`number`,`boolean`]),default:Fl()},Rl={name:el(),default:Yc()},zl={path:el(),readMode:tl([`whole`,`first-line`]),regex:Yc(),cache:Sl(`file`),default:Yc()},Bl={command:el(),regex:Yc(),cache:Sl(`shell`),default:Yc()},Vl={template:el(),cache:Cl(),default:Yc()},Hl={layout:el(),cache:Ol(),default:Yc()},Ul={field:Pl(),cache:Sl(`git`),default:Yc()},Wl={key:el(),default:Yc()};function Gl(e,t){return{json:il(nl(t),`kind`,e),parse:(n,r,i)=>{let a=Uc(n,t,r,i);return a===null?null:{kind:e,...a}}}}const Kl={tag:`kind`,noun:`source kind`,arms:{literal:Gl(`literal`,Il),input:Gl(`input`,Ll),env:Gl(`env`,Rl),file:Gl(`file`,zl),shell:Gl(`shell`,Bl),template:Gl(`template`,Vl),time:Gl(`time`,Hl),git:Gl(`git`,Ul),state:Gl(`state`,Wl)}};function ql(){return al(Kl)}function Jl(){return{type:`object`,additionalProperties:ql()}}function Yl(e,t){if(t===void 0)return{};if(!zc(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Bc(t)}`,line:Z(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=Hc(e,Ql,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function Xl(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${Vc(i)}`,line:Z(e.source,[...t.split(`.`),n])})}}}}function Zl(){return{required:!1,json:Jl(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Ml(e,`${t}.${n}`,i)}}}const Ql={noun:`segment key`,fields:{template:el(),width:Xl(),justify:tl(ni),truncate:tl(ri),bg:Yc(),fg:Yc(),when:Yc(),palette:$c(),vars:Zl()}};function $l(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:Z(e.source,[`root`])})}const eu=`#/definitions/LayoutNode`,tu={kind:`container`,direction:`vertical`,children:[]};function nu(e){return{required:!0,json:{const:e},parse:()=>e}}function ru(){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 ${Vc(i)}`,line:Z(e.source,[`root`])}),``)}}}function iu(){return{required:!0,json:{enum:[...Xr]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Xr.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Xr.join(`, `)} (got ${JSON.stringify(i)})`,line:Z(e.source,[`root`])}),`vertical`)}}}function au(e){return{required:!0,json:{type:`array`,items:{$ref:eu}},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 ${Bc(a)}`,line:Z(t.source,[`root`])}),[])}}}const ou={noun:`layout-node key`,fields:{kind:nu(`segment`),name:ru(),when:Yc()}},su={noun:`layout-node key`,fields:{kind:nu(`container`),direction:iu(),children:au(qc(()=>fu)),when:Yc()}};function cu(){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 ${Vc(i)}`,line:Z(e.source,[`root`])}),``)}}}const lu={noun:`layout-node key`,fields:{seg:cu(),when:Yc()}},uu={noun:`layout-node key`,fields:{h:au(qc(()=>fu)),when:Yc()}},du={noun:`layout-node key`,fields:{v:au(qc(()=>fu)),when:Yc()}},fu=(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:Z(e.source,[`root`])}),tu):{kind:`segment`,name:n};if(!zc(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 ${Bc(n)}`,line:Z(e.source,[`root`])}),tu;if(n.kind===`container`)return Hc(e,su,t,n)??tu;if(n.kind===`segment`)return Hc(e,ou,t,n)??tu;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
85
+ `)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${Xi(`(no matches)`,U(e))} `,n=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0}):new J({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),dim:!0});return[new Y(` `,n),new Y(t,n),new Y(` `,n)]}renderOptionRow(e,t,n){let r=` ${Xi(e.label,U(n))} `,i=e.idx===this.selectedIndex,a=t===this.highlightedIndex,o=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0}):a?new J({color:this.resolvePalette(`text-primary`),bgcolor:this.resolvePalette(`primary-muted`)}):i?new J({color:this.resolvePalette(`on-primary`),bgcolor:this.resolvePalette(`primary`)}):new J({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`)});return[new Y(` `,o),new Y(r,o),new Y(` `,o)]}maxLabelLen(){let e=0;for(let t of this.options){let n=H(t);n>e&&(e=n)}return e}measure(e){let t=this.maxLabelLen()+4;return{minimum:t,maximum:t}}resolvePalette(e){let t=this._theme.palette.get(e);return q.fromRgba(t)}}})();var Gs=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Ks=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t,n,r,i;let a=_s,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],w=[],ee,T,te,ne;return class extends a{static{let re=typeof Symbol==`function`&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;s=[X.observable],u=[(e=X.observable).ref.bind(e)],p=[(t=X.observable).ref.bind(t)],g=[(n=X.observable).ref.bind(n)],y=[(r=X.observable).ref.bind(r)],S=[(i=X.observable).ref.bind(i)],ee=[X.action],T=[X.action],te=[X.action],ne=[X.action],Ks(this,null,s,{kind:`accessor`,name:`value`,static:!1,private:!1,access:{has:e=>`value`in e,get:e=>e.value,set:(e,t)=>{e.value=t}},metadata:re},c,l),Ks(this,null,u,{kind:`accessor`,name:`min`,static:!1,private:!1,access:{has:e=>`min`in e,get:e=>e.min,set:(e,t)=>{e.min=t}},metadata:re},d,f),Ks(this,null,p,{kind:`accessor`,name:`max`,static:!1,private:!1,access:{has:e=>`max`in e,get:e=>e.max,set:(e,t)=>{e.max=t}},metadata:re},m,h),Ks(this,null,g,{kind:`accessor`,name:`step`,static:!1,private:!1,access:{has:e=>`step`in e,get:e=>e.step,set:(e,t)=>{e.step=t}},metadata:re},_,v),Ks(this,null,y,{kind:`accessor`,name:`width`,static:!1,private:!1,access:{has:e=>`width`in e,get:e=>e.width,set:(e,t)=>{e.width=t}},metadata:re},b,x),Ks(this,null,S,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:re},C,w),Ks(this,null,ee,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:re},null,o),Ks(this,null,T,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:re},null,o),Ks(this,null,te,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:re},null,o),Ks(this,null,ne,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:re},null,o),re&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:re})}id=Gs(this,o);focusable=!0;#e=Gs(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Gs(this,l),Gs(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Gs(this,f),Gs(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Gs(this,h),Gs(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Gs(this,v),Gs(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Gs(this,x),Gs(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Gs(this,w),!1);constructor(e={}){super(),this.id=e.id??`slider-${Math.random().toString(36).slice(2,8)}`,this.min=e.min??0,this.max=e.max??100,this.step=e.step??1;let t=e.width??20;if(!Number.isInteger(t)||t<1)throw RangeError(`Slider width must be a positive integer; got ${t}`);this.width=t,this.value=qs(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??po}setTheme(e){this._theme=e}handleKey(e){if(!this.disabled)switch(e.key){case`left`:this.setValue(this.value-this.step),e.stop();return;case`right`:this.setValue(this.value+this.step),e.stop();return;case`home`:this.setValue(this.min),e.stop();return;case`end`:this.setValue(this.max),e.stop();return}}handleMouse(e){if(!this.disabled){if(e.type===`mouse_down`){this._dragging=!0,this.setValueFromMouseX(e.x);return}if(e.type===`mouse_move`){this._dragging&&this.setValueFromMouseX(e.x);return}if(e.type===`mouse_up`){let t=this._dragging;this._dragging=!1,t&&(this.setValueFromMouseX(e.x),this.emitSubmit());return}}}setValue(e){let t=qs(e,this.min,this.max,this.step);t!==this.value&&(this.value=t,this.emitChange())}setValueFromMouseX(e){let t=this.bounds;if(!t)return;let n=Math.max(1,this.width-1),r=Math.max(0,Math.min(this.width-1,e-t.x))/n,i=this.min+r*(this.max-this.min);this.setValue(i)}render(e){let t=e.asciiOnly?`-`:`─`,n=e.asciiOnly?`*`:`●`,r=this.max-this.min,i=r===0?0:(this.value-this.min)/r,a=Math.round(i*(this.width-1)),o={underline:this.focused},s=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new J({color:this.resolvePalette(`primary`),...o}),c=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new J({color:this.resolvePalette(`surface`),...o}),l=this.disabled?new J({color:`#666666`,bgcolor:`#333333`,dim:!0,bold:!0,...o}):new J({color:this.resolvePalette(`primary`),bold:!0,...o}),u=[];a>0&&u.push(new Y(t.repeat(a),s)),u.push(new Y(n,l));let d=this.width-a-1;return d>0&&u.push(new Y(t.repeat(d),c)),u}measure(e){return{minimum:this.width,maximum:this.width}}resolvePalette(e){let t=this._theme.palette.get(e);return q.fromRgba(t)}}})();function qs(e,t,n,r){let i=Math.max(t,Math.min(n,e));if(r<=0)return i;let a=t+Math.round((i-t)/r)*r;return Math.max(t,Math.min(n,a))}new TextEncoder,new TextDecoder(`utf-8`),new TextDecoder(`ascii`);function Js(e,t){if(!(e instanceof Vo))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=e.style.add(t),n}function Ys(e){return{fn:(t=>Js(t,e)),argTypes:[`liftable`],returnType:`T`}}function Xs(e){return{fn:((t,n)=>Js(n,new J({[e]:q.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Zs(e,t){return new J({[e]:t})}function Qs(){let e={};for(let t of xo)e[t]=Ys(Zs(t,!0)),e[`not_${t}`]=Ys(Zs(t,!1));for(let[t,n]of Object.entries(Co))e[t]=Ys(Zs(n,!0));return e}const $s={fn:((e,t)=>Js(t,J.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},ec={fn:((e,t)=>Js(t,new J({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function tc(){return{fg:Xs(`color`),bg:Xs(`bgcolor`),...Qs(),link:ec,style:$s}}function nc(e,t){if(!Ia.test(e.trim()))throw 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)}) …`);return La(e)}function rc(e,t){return{fn:t,argTypes:e,returnType:`string`}}function ic(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}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const ac=rc([`string`,`int`],((e,t)=>Wa(nc(e,`darken`),ic(t,`darken`,`levels`)).hex)),oc=rc([`string`,`int`],((e,t)=>Wa(nc(e,`lighten`),-ic(t,`lighten`,`levels`)).hex)),sc={min:0,max:100,note:`0 = from, 100 = toward`},cc=rc([`string`,`string`,`float`],((e,t,n)=>_a(nc(e,`mix`),nc(t,`mix`),ic(n,`mix`,`percentage`,sc)/100).hex)),lc={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},uc=rc([`string`],(e=>qa(nc(e,`contrastOn`)).hex)),dc=rc([`string`,`string`,`float`],((e,t,n)=>Xa(nc(e,`readableOn`),nc(t,`readableOn`),ic(n,`readableOn`,`ratio`,lc)).hex)),fc={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function pc(){let e={};for(let[t,n]of Object.entries(fc)){let r=t;e[n]=rc([`string`,`float`],((e,t)=>{let i={...Ea,[r]:ic(t,n,`amount`)};return Pa.fromRgba(nc(e,n)).applyKey(i).toRgba().hex}))}return e}function mc(){return{darken:ac,lighten:oc,mix:cc,contrastOn:uc,readableOn:dc,...pc()}}function hc(e){return{color:{fn:(t=>Ra(e(),t).hex),argTypes:[`string`],returnType:`string`}}}function gc(){return{...tc(),...mc()}}new J({color:`red`,dim:!0});const _c={dark:`textual-dark`,light:`textual-light`};function vc(e){return _c[e]??e}function yc(e,t,n,r){return(e===null?null:r(e))??t??n}function bc(e,t){return yc(e,t,`textual-dark`,e=>e)}function xc(){return Object.keys(_c)}function Sc(){return[...ro(),...xc()]}function Cc(e,t,n,r){let i=e=>Object.prototype.hasOwnProperty.call(r,e)?e:null;return yc(e,i(t??n),n,i)}function wc(e,t,n){return Cc(e,t,`none`,n)}function Tc(e,t){let n=e[t];if(n===void 0)throw Error(`Look "${t}" is not declared in this config — effectiveLookName collapses unknown names to "none", and every merged config carries "none"; a miss here is merge/policy drift`);return n}const Ec=[`powerline`,`capsule`,`plain`];function Dc(e){return Ec.includes(e)}function Oc(e,t){return yc(e,t,`powerline`,e=>Dc(e)?e:null)}const kc=[`unicode`,`ascii`],Ac=[`truecolor`,`256`,`ansi`,`none`],jc=[`true`,`false`],Mc={min:0,max:16};function Nc(e){return e===`true`?!0:e===`false`?!1:null}function Pc(e){if(!/^\d+$/.test(e))return null;let t=Number(e);return t>=Mc.min&&t<=Mc.max?t:null}function Fc(e,t){return yc(e,t,!0,Nc)}function Ic(e,t){return yc(e,t,1,Pc)}var Lc=class extends Error{file;issues;constructor(e,t){super(Bc(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function Z(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=Rc(e,n,i);if(t===-1)return r===void 0?void 0:zc(e,r);n=t,r=t}return r===void 0?void 0:zc(e,r)}function Rc(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 zc(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Bc(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(`
86
+ `)}function Vc(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 ${qc(i)}`,line:Z(e.source,[...t.split(`.`),r])}),null)}function Hc(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 ${qc(i)}`,line:Z(e.source,[...t.split(`.`),`default`])});return}return i}}function Uc(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 ${qc(i)}`,line:Z(e.source,[...t.split(`.`),r])});return}return i}}function Wc(e,t,n){let r=Uc(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:Z(e.source,[...t.split(`.`),`palette`])});return}return r}}function Gc(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 ${Jc(a)}`,line:Z(e.source,[...t.split(`.`),r])});return}return a}}function Kc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Jc(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Yc(e,t,n,r){return Kc(r)?(Zc(e,n,r,t.noun,new Set(Object.keys(t.fields))),Xc(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${qc(r)}`,line:Z(e.source,n.split(`.`))}),null)}function Xc(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}function Zc(e,t,n,r,i){for(let a of Object.keys(n))i.has(a)||e.issues.push({path:`${t}.${a}`,message:`Unknown ${r} "${a}". Expected one of: ${[...i].join(`, `)}`,line:Z(e.source,[...t.split(`.`),a])})}function Qc(e,t,n,r){if(!Kc(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${qc(r)}`,line:Z(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:Z(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:Z(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:Z(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function $c(e,t,n,r){if(!Kc(r))return e.issues.push({path:n,message:`${n} must be an object, got ${qc(r)}`,line:Z(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 ${qc(i)}`,line:Z(e.source,n.split(`.`))}),null;let a=t.arms;return i in a?a[i].parse(e,n,r):(e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:Z(e.source,[...n.split(`.`),t.tag])}),null)}function el(e){return(...t)=>e()(...t)}function tl(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:Z(n.source,o.split(`.`))}),null}return a}}function nl(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Uc(e,t,r,n)}}function rl(){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 ${qc(i)}`,line:Z(e.source,[n])});return}return i}}}}function il(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 ${Jc(o)}`,line:Z(e.source,[i])});return}return o}}}}function al(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 ${Jc(a)}`,line:Z(e.source,[r])});return}return a}}}}function ol(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Wc(e,t,r)}}function sl(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Vc(e,t,r,n)??void 0}}function cl(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Gc(t,n,i,r,e)}}function ll(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 ul(e){return ll(e.fields)}function dl(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function fl(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function pl(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function ml(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:{...t.segments,...e.segments??{}},root:e.root===void 0?t.root:e.root,actions:{...t.actions,...e.actions??{}},looks:{...t.looks,...e.looks??{}},presets:{...t.presets,...e.presets??{}},helpers:{...t.helpers,...e.helpers??{}}}}function hl(e,t){let n=Object.entries(t);if(n.length===0)return e;let r=Object.assign(Object.create(null),e.segments);for(let[e,t]of n){let n=r[e];n!==void 0&&(r[e]={...n,palette:t})}return{...e,segments:r}}const gl={required:!1,json:{enum:[...Ac]},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: ${Ac.join(`, `)}`,line:Z(e.source,[...t.split(`.`),n])});return}return Gc(e,t,r,n,Ac)}},_l={default_bg:nl(),default_fg:nl(),default_empty_value:nl(),default_separator:nl(),default_truncate_marker:nl(),palette:ol(),look:nl(),preset:nl(),style:cl(Ec),autoWrap:rl(),padding:il(Mc),charset:cl(kc),colorCompatibility:gl},vl={noun:`globals key`,fields:_l},yl={required:!1,json:{not:{},description:`not allowed inside a preset — a preset cannot select a preset`},parse:(e,t,n,r)=>{r[n]!==void 0&&e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: a preset cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a preset naming another would be a second authority over that, and a cyclic one. Set the default arrangement in the top-level globals.preset instead.`,line:Z(e.source,[...t.split(`.`),n])})}},bl={noun:`preset globals key`,fields:{..._l,preset:yl}};function xl(e,t,n){return n===void 0?{}:Yc(e,vl,t,n)??{}}function Sl(e,t,n){return Yc(e,bl,t,n)??{}}function Cl(){return ul(bl)}const wl=new Set(Object.keys(vl.fields));function Tl(e){return wl.has(e)}function El(){return[...wl]}function Dl(e,t,n,r){return n.cache===void 0?(ti.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Qr.join(`, `)})`,line:Z(e.source,t.split(`.`))}),null):Nl(e,`${t}.cache`,n.cache)}function Ol(e,t,n){if(n.cache!==void 0)return Nl(e,`${t}.cache`,n.cache)??void 0}function kl(e){return{required:!0,json:Il(),parse:(t,n,r,i)=>Dl(t,n,i,e)??void 0}}function Al(){return{required:!1,json:Il(),parse:(e,t,n,r)=>Ol(e,t,r)}}function jl(e,t,n){return e.issues.push({path:t,message:n,line:Z(e.source,t.split(`.`))}),null}const Ml={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Rl(n)?{ttl:n}:jl(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Jc(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:jl(e,t,`cache.watch_file must be a non-empty path string, got ${Jc(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:jl(e,t,`cache.depends_on must be an array of variable-name strings, got ${Jc(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:jl(e,t,`cache.key must be a non-empty template string, got ${Jc(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:jl(e,t,`cache.never must be the literal boolean true, got ${Jc(n)}`)}}};function Nl(e,t,n){return Qc(e,Ml,t,n)}const Pl={noun:`time-variable cache`,arms:{ttl:Ml.arms.ttl}};function Fl(){return{required:!1,json:pl(Pl),parse:(e,t,n,r)=>r.cache===void 0?void 0:Qc(e,Pl,`${t}.cache`,r.cache)??void 0}}function Il(){return pl(Ml)}const Ll=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Rl(e){return Ll.test(e)}function zl(e,t,n){if(n===void 0)return{};if(!Kc(n))return e.issues.push({path:t,message:`${t} must be an object, got ${qc(n)}`,line:Z(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=$c(e,$l,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Bl(){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 ${qc(i)}`,line:Z(e.source,t.split(`.`))});return}return i}}}function Vl(){return{required:!0,json:{enum:[...ei]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!ei.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${ei.join(`, `)}, got ${JSON.stringify(i)}`,line:Z(e.source,[...t.split(`.`),`field`])});return}return i}}}function Hl(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Hc(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Ul={value:Bl(),default:nl()},Wl={path:sl(),type:cl([`string`,`number`,`boolean`]),default:Hl()},Gl={name:sl(),default:nl()},Kl={path:sl(),readMode:cl([`whole`,`first-line`]),regex:nl(),cache:kl(`file`),default:nl()},ql={command:sl(),regex:nl(),cache:kl(`shell`),default:nl()},Jl={template:sl(),cache:Al(),default:nl()},Yl={layout:sl(),cache:Fl(),default:nl()},Xl={field:Vl(),cache:kl(`git`),default:nl()},Zl={key:sl(),default:nl()};function Ql(e,t){return{json:dl(ll(t),`kind`,e),parse:(n,r,i)=>{let a=Xc(n,t,r,i);return a===null?null:{kind:e,...a}}}}const $l={tag:`kind`,noun:`source kind`,arms:{literal:Ql(`literal`,Ul),input:Ql(`input`,Wl),env:Ql(`env`,Gl),file:Ql(`file`,Kl),shell:Ql(`shell`,ql),template:Ql(`template`,Jl),time:Ql(`time`,Yl),git:Ql(`git`,Xl),state:Ql(`state`,Zl)}};function eu(){return fl($l)}function tu(){return{type:`object`,additionalProperties:eu()}}function nu(e,t){if(t===void 0)return{};if(!Kc(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${qc(t)}`,line:Z(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=Yc(e,au,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function ru(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${Jc(i)}`,line:Z(e.source,[...t.split(`.`),n])})}}}}function iu(){return{required:!1,json:tu(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return zl(e,`${t}.${n}`,i)}}}const au={noun:`segment key`,fields:{template:sl(),width:ru(),justify:cl(ni),truncate:cl(ri),bg:nl(),fg:nl(),when:nl(),palette:ol(),vars:iu()}};function ou(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:Z(e.source,[`root`])})}const su=`#/definitions/LayoutNode`,cu={kind:`container`,direction:`vertical`,children:[]};function lu(e){return{required:!0,json:{const:e},parse:()=>e}}function uu(){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 ${Jc(i)}`,line:Z(e.source,[`root`])}),``)}}}function du(){return{required:!0,json:{enum:[...Xr]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Xr.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Xr.join(`, `)} (got ${JSON.stringify(i)})`,line:Z(e.source,[`root`])}),`vertical`)}}}function fu(e){return{required:!0,json:{type:`array`,items:{$ref:su}},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 ${qc(a)}`,line:Z(t.source,[`root`])}),[])}}}const pu={noun:`layout-node key`,fields:{kind:lu(`segment`),name:uu(),when:nl()}},mu={noun:`layout-node key`,fields:{kind:lu(`container`),direction:du(),children:fu(el(()=>yu)),when:nl()}};function hu(){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 ${Jc(i)}`,line:Z(e.source,[`root`])}),``)}}}const gu={noun:`layout-node key`,fields:{seg:hu(),when:nl()}},_u={noun:`layout-node key`,fields:{h:fu(el(()=>yu)),when:nl()}},vu={noun:`layout-node key`,fields:{v:fu(el(()=>yu)),when:nl()}},yu=(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:Z(e.source,[`root`])}),cu):{kind:`segment`,name:n};if(!Kc(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 ${qc(n)}`,line:Z(e.source,[`root`])}),cu;if(n.kind===`container`)return Yc(e,mu,t,n)??cu;if(n.kind===`segment`)return Yc(e,pu,t,n)??cu;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
87
87
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
88
- New: { h: ["seg1", "seg2"] }`,line:Z(e.source,[`root`])}),tu;if(n.kind===`group`){let r=Hc(e,vu,t,n);return r===null?tu:(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}),bu(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:Z(e.source,[`root`])}),tu}if(a){let r=Hc(e,lu,t,n);return r===null?tu:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Hc(e,uu,t,n);return r===null?tu:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when}}}if(i){let r=Hc(e,du,t,n);return r===null?tu:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when}}}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:Z(e.source,[`root`])}),tu},pu=`groups.`,mu=/^[A-Za-z_][A-Za-z0-9_]*$/;function hu(){return{required:!0,json:{type:`string`,pattern:mu.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!mu.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 "${zt}", got ${Vc(i)}`,line:Z(e.source,[`root`])});return}return i}}}function gu(){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 ${Vc(i)}`,line:Z(e.source,[`root`])});return}return i}}}}function _u(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Pc(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:Z(e.source,[...t.split(`.`),n])});return}return i}}}}const vu={noun:`layout-node key`,fields:{kind:nu(`group`),name:hu(),label:_u(),open:Xc(),direction:tl(Xr),key:gu(),bg:Yc(),fg:Yc(),when:Yc(),children:au(qc(()=>fu))}};function yu(e){return e.key??`groups.`+e.name}function bu(e){let t=pu+e.name;return{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:t},{kind:`container`,direction:e.direction??`vertical`,children:e.children,when:`{{ eq .${t} "${e.name}" }}`}],...e.when!==void 0&&{when:e.when}}}function xu(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Su(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,[`root`])})}function Cu(e,t){$l(e,t,pu,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&Su(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}.`)&&yu(t)===yu(r)&&Su(e,t.path,`group "${t.name}" shares key "${yu(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=yu(t);if(i.has(n)||i.set(n,zt),t.open===!0){let r=i.get(n);r!==`closed`&&Su(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=pu+e.name,r=yu(e),c=xu(e.label),l=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,u=` `.repeat(l);a[t]=Bt(r,i.get(r)),o[t]=Vt(r,e.name),s[t]={template:`{{ action "${t}" "${u}${c} ▸" "${u}${c} ▾" }}`,...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 wu=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?ju(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}},Tu=class extends wu{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Eu=class extends wu{name=`EvalError`;kind=`EvalError`},Du=class extends Eu{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Mu(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}},Ou=class extends Eu{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}},ku=class extends Eu{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Au=class extends Eu{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function ju(e,t){let n=e.split(`
88
+ New: { h: ["seg1", "seg2"] }`,line:Z(e.source,[`root`])}),cu;if(n.kind===`group`){let r=Yc(e,Tu,t,n);return r===null?cu:(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}),Du(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:Z(e.source,[`root`])}),cu}if(a){let r=Yc(e,gu,t,n);return r===null?cu:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Yc(e,_u,t,n);return r===null?cu:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when}}}if(i){let r=Yc(e,vu,t,n);return r===null?cu:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when}}}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:Z(e.source,[`root`])}),cu},bu=`groups.`,xu=/^[A-Za-z_][A-Za-z0-9_]*$/;function Su(){return{required:!0,json:{type:`string`,pattern:xu.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!xu.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 "${zt}", got ${Jc(i)}`,line:Z(e.source,[`root`])});return}return i}}}function Cu(){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 ${Jc(i)}`,line:Z(e.source,[`root`])});return}return i}}}}function wu(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Vc(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:Z(e.source,[...t.split(`.`),n])});return}return i}}}}const Tu={noun:`layout-node key`,fields:{kind:lu(`group`),name:Su(),label:wu(),open:rl(),direction:cl(Xr),key:Cu(),bg:nl(),fg:nl(),when:nl(),children:fu(el(()=>yu))}};function Eu(e){return e.key??`groups.`+e.name}function Du(e){let t=bu+e.name;return{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:t},{kind:`container`,direction:e.direction??`vertical`,children:e.children,when:`{{ eq .${t} "${e.name}" }}`}],...e.when!==void 0&&{when:e.when}}}function Ou(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function ku(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,[`root`])})}function Au(e,t){ou(e,t,bu,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&ku(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}.`)&&Eu(t)===Eu(r)&&ku(e,t.path,`group "${t.name}" shares key "${Eu(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=Eu(t);if(i.has(n)||i.set(n,zt),t.open===!0){let r=i.get(n);r!==`closed`&&ku(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=bu+e.name,r=Eu(e),c=Ou(e.label),l=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,u=` `.repeat(l);a[t]=Bt(r,i.get(r)),o[t]=Vt(r,e.name),s[t]={template:`{{ action "${t}" "${u}${c} ▸" "${u}${c} ▾" }}`,...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 ju=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Ru(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}},Mu=class extends ju{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Nu=class extends ju{name=`EvalError`;kind=`EvalError`},Pu=class extends Nu{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=zu(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}},Fu=class extends Nu{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}},Iu=class extends Nu{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Lu=class extends Nu{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Ru(e,t){let n=e.split(`
89
89
  `),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(`
90
- `)}function Mu(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Nu(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 Nu(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 Pu(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Fu=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`]]),Iu={left:`{{`,right:`}}`};var Lu=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Iu){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 Tu(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&&Ru(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);Ru(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);Ru(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(;Ru(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`;Ru(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&&(Bu(e)||zu(e)&&Bu(this.src[this.offset+1]??``)||e===`.`&&Bu(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Gu(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===`
90
+ `)}function zu(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Bu(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 Bu(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 Vu(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Hu=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`]]),Uu={left:`{{`,right:`}}`};var Wu=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Uu){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 Mu(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&&Gu(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);Gu(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);Gu(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(;Gu(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`;Gu(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&&(qu(e)||Ku(e)&&qu(this.src[this.offset+1]??``)||e===`.`&&qu(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Qu(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===`
91
91
  `)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===`
92
- `)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(zu(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);Vu(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);Hu(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);Uu(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Bu(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Bu(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),zu(this.src[this.offset]??``)&&this.advanceBy(1);Bu(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Vu(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);Ku(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Gu(this.src[this.offset+1]??``);)for(this.advanceBy(1);Ku(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),!Gu(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;Ku(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Gu(this.src[this.offset+1]??``);)for(this.advanceBy(1);Ku(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(;Ku(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Fu.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===`
92
+ `)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(Ku(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);Ju(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);Yu(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);Xu(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;qu(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);qu(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),Ku(this.src[this.offset]??``)&&this.advanceBy(1);qu(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Ju(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);$u(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Qu(this.src[this.offset+1]??``);)for(this.advanceBy(1);$u(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),!Qu(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;$u(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Qu(this.src[this.offset+1]??``);)for(this.advanceBy(1);$u(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(;$u(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Hu.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===`
93
93
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
94
- `?(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 Ru(e){return e===` `||e===` `||e===`\r`||e===`
95
- `}function zu(e){return e===`+`||e===`-`}function Bu(e){return e>=`0`&&e<=`9`}function Vu(e){return Bu(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Hu(e){return e>=`0`&&e<=`7`}function Uu(e){return e===`0`||e===`1`}function Wu(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Gu(e){return Wu(e)||e===`_`}function Ku(e){return Gu(e)||Bu(e)}function qu(e,t){return new Ju(e,t).parseTemplate()}var Ju=class{lex;buf=[];defines=new Map;source;rangeDepth=0;constructor(e,t){this.source=e,this.lex=t?new Lu(e,t):new Lu(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:Zu(n)});return n}errAt(e,t,n={}){return new Tu(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 ${Zu(e)}`,{found:Zu(e)})}return{root:e,defines: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=Xu(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 Yu(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${Zu(n)} at top level`,{found:Zu(n)})}return Yu(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 Tu(`{{${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.defines.set(n,a),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))throw new Tu(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,i)}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:Zu(e)});return ad(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(!Qu(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:Zu(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=[$u(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push($u(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;Qu(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 $u(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:ad(e.value,e.pos,this.source)};case`Number`:return td(e);case`Char`:return nd(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 ${Zu(e)}`,{expected:`command argument`,found:Zu(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 Yu(e,t){return{type:`List`,pos:e,nodes:t}}function Xu(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function Zu(e){return e.type===`EOF`?`end of input`:e.value||e.type}function Qu(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 $u(e){return{type:`Variable`,pos:e.pos,idents:ed(e.value)}}function ed(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function td(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=rd(i);return{...s,intValue:e}}if(a){let e=id(i);return{...s,floatValue:e}}let c=id(i);return{...s,complexValue:[0,c]}}function nd(e,t){let n=od(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 rd(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 id(e){return Number(e)}function ad(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+=`
96
- `;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 Tu(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function od(e,t,n){let r=ad(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Tu(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function sd(e,t){if(t(e)!==!1)for(let n of cd(e))sd(n,t)}function cd(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 Pu(e)}}const ld=Symbol(`go-template-js.MISSING`);function ud(e,t){if(e==null)return ld;if(e instanceof Map)return e.has(t)?e.get(t):ld;if(Array.isArray(e))return ld;if(typeof e==`object`){let n=e;return t in n?n[t]:ld}return ld}function dd(e,t){let n=e;for(let e of t){if(n===ld)return ld;n=ud(n,e)}return n}function fd(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)=>fd(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)||!fd(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=>fd(e[n],t[n])):!1}return!1}const pd=new WeakSet;function md(e){return pd.add(e),e}function hd(e){return pd.has(e)}function gd(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 _d(e){return{eq:{fn:(e,...t)=>t.some(t=>bd(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!bd(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>xd(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>xd(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>xd(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>xd(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>Sd(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Cd(n,e);return n},argTypes:[`collection`,`index-key`]},slice:{fn:(e,...t)=>{let n=t.length>=1?t[0]:0,r=t.length>=2?t[1]:void 0;return e.slice(n,r)},argTypes:[`sliceable`,`int`]},print:{fn:(...t)=>Ed(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Ed(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>Fd(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>kd(Ed(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>Md(Ed(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>Pd(Ed(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!gd(e),argTypes:[`truthy`]}}}function vd(){return{and:md({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!gd(t))return t;return t}}),or:md({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),gd(t))return t;return t}})}}function yd(e){return{..._d(e),...vd()}}function bd(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):fd(e,t)}function xd(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 Sd(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Cd(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${wd(t)}`);if(n<0||n>=e.length)throw Error(`index: out of range [${n}] with length ${e.length}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`string`)return e[Number(t)];if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${wd(t)}`);return e[t]}throw Error(`index: cannot index ${wd(e)}`)}function wd(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Td(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 Ed(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+=Dd(a,t),r=o}return n}function Dd(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Od={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function kd(e){return e.replace(/[\0"'&<>]/g,e=>Od[e]??e)}const Ad={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},jd=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Md(e){let t=``;for(let n of e){let e=Ad[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!jd.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Nd=new TextEncoder;function Pd(e){let t=``,n=Nd.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 Fd(e,t,n){let r=``,i=0,a=0;for(;a<e.length;){let o=e[a];if(o!==`%`){r+=o,a+=1;continue}if(e[a+1]===`%`){r+=`%`,a+=2;continue}let s=a+1;for(;s<e.length&&`+-# 0`.includes(e[s]??``);)s+=1;for(;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;if(e[s]===`.`)for(s+=1;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;let c=e[s],l=e.slice(a+1,s),u=t[i++];r+=Id(c??``,l,u,n),a=s+1}return r}function Id(e,t,n,r){switch(e){case`s`:return typeof n==`string`?Ld(t,n):Ld(t,Dd(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Td(n)}=${Dd(n,r)})`:Ld(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return Ld(t,Rd(n));case`q`:return Ld(t,JSON.stringify(Dd(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Td(n)}=${Dd(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return Ld(t,Number(n).toFixed(i))}case`t`:return Ld(t,gd(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 Ld(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Td(n)}=${Dd(n,r)})`:typeof n==`bigint`?Ld(t,n.toString(16)):Ld(t,Math.trunc(n).toString(16));default:return`%!${e}(${Td(n)}=${Dd(n,r)})`}}function Ld(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 Rd(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(Rd).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${Rd(e)}:${Rd(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(Rd).join(` `)}}`:String(e)}function zd(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function Bd(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function Vd(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 Hd(e,t,n){e.vars.set(t,n)}const Ud=new Set([`default`,`zero`,`error`]);function Wd(e){if(e===void 0)return`default`;if(Ud.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${Gd(e)}`)}function Gd(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 Kd(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${Gd(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${Gd(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${Gd(e.right)}`);return{left:e.left,right:e.right}}}const qd=Object.freeze({kind:`break`}),Jd=Object.freeze({kind:`continue`}),Yd={kind:`none`};let Xd;(class e{source;_evaluate;_referencedFunctions;_referencedCalls;constructor(e,t,n,r){this.source=e,this._evaluate=t,this._referencedFunctions=n,this._referencedCalls=r}static{Xd=(t,n,r,i)=>new e(t,n,r,i)}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function Zd(e){let t=new Set,n=e=>{sd(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}const Qd={kind:`dynamic`};function $d(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=Sf(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:Qd}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return Qd;let t=e.cmds[0];if(t===void 0)return Qd;let n=t.args[0];return n===void 0||n.type!==`Identifier`?Qd:{kind:`call`,name:n.ident,args:t.args.slice(1).map($d)}}default:return Qd}}function ef(e){let t=[],n=e=>{sd(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($d);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.defines.values())n(t);return t}var tf=class{fromString;toString;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??df,this.missingKey=Wd(e.missingKey),this.delims=Kd(e.delims),this.funcs={...yd(this.toString),...e.funcs??{}}}parse(e){let t=qu(e,this.delims);return Xd(t.source,e=>this.evalParsed(t,e),Zd(t),ef(t))}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=zd(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 qd;case`Continue`:throw Jd;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 Eu(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Pu(e)}}evalIf(e,t,n){gd(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(gd(r)){let i=Bd(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=yf(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=Bd(t,o);if(i.length===1)Hd(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;Hd(a,e,r),Hd(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===Jd)continue;throw e}}}catch(e){if(e===qd)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Eu(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=Bd(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=Bd(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=n.defines.get(e.name)??e.list;this.evalList(i,r,n)}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Eu(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Yd);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)Hd(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 Eu(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Eu(`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 Du(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=hd(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)}sf(i.ident,a.argTypes,c,e.pos,n.source,this.toString,a.argTypePattern,this.fromString);try{return a.fn(...c)}catch(t){throw t instanceof Ou?new Ou(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof Au?new Au(t.message,e.pos,{source:n.source}):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 Sf(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 Du(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return sf(e.ident,t.argTypes,[],e.pos,n.source,this.toString,t.argTypePattern,this.fromString),t.fn()}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 Eu(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=dd(e,t);if(i!==ld)return i;if(this.missingKey===`error`)throw new ku(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=Vd(t,i);if(!a.found)throw new Eu(`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(Array.isArray(e)){t.out.push(this.fromString(nf(e)));return}if(e instanceof Map){t.out.push(this.fromString(rf(e)));return}t.out.push(e)}};function nf(e){return`[${e.map(af).join(` `)}]`}function rf(e){let t=[];for(let[n,r]of e)t.push(`${af(n)}:${af(r)}`);return`map[${t.join(` `)}]`}function af(e){return e==null?`<nil>`:Array.isArray(e)?nf(e):e instanceof Map?rf(e):String(e)}function of(e){return new tf(e)}function sf(e,t,n,r,i,a=df,o,s=uf){let c=cf(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!lf(o,d,a))throw new Ou(e,t+1,_f(o),vf(d),r,{source:i});if(o===`liftable`&&typeof d==`string`&&(n[t]=s(d)),o===`int`?n[t]=Math.trunc(Number(d)):o===`float`&&(n[t]=Number(d)),o===`ordered`){if(l===-1)l=t;else if(!mf(n[l],d))throw new Ou(e,t+1,`${_f(`ordered`)} of the same kind as ${vf(n[l])}`,vf(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!hf(n[u],d))throw new Ou(e,t+1,`${_f(`comparable`)} of the same kind as ${vf(n[u])}`,vf(d),r,{source:i})}}}function cf(e,t){if(e.length===0)return()=>`value`;if(t===`alternating`){let t=e.length;return n=>e[n%t]}let n=e[e.length-1];return t=>t<e.length?e[t]:n}function lf(e,t,n){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`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 t!=null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`list`:return Array.isArray(t);case`dict`:return ff(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||ff(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||ff(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||ff(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`||t!=null&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`serializable`:return pf(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function uf(e){return e}function df(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 Ou(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,vf(e),{line:0,column:0,offset:0})}function ff(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 pf(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function mf(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function hf(e,t){let n=gf(e),r=gf(t);return n===`nil`||r===`nil`?!0:n===r}function gf(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 _f(e){switch(e){case`int`:return`integer (finite number 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 vf(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function yf(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?bf([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?bf(Object.entries(e)):[]}function bf(e){return[...e].sort((e,t)=>xf(e[0],t[0]))}function xf(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 Sf(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 Cf(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function wf(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 Tf(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 Ef(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=Tf(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 Df(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Tf(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 Of(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 kf(e){return JSON.stringify(e)??`null`}function Af(e){return typeof e==`string`?e:Rd(e)}function jf(e){return e.map(Af)}function Mf(){return{atoi:{fn:e=>Cf(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Ef(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>Df(e),argTypes:[`value`]},float64:{fn:e=>wf(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Af(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>jf(e),argTypes:[`list`]},toDecimal:{fn:e=>Of(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>kf(e),argTypes:[`serializable`],returnType:`string`}}}const Nf={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Pf(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*Nf[a],n=n.slice(e[0].length)}return t?-r:r}function Ff(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Nf.us?`${Math.floor(n)}ns`:n<Nf.ms?If(n,Nf.us,3,`µs`):n<Nf.s?If(n,Nf.ms,6,`ms`):Lf(n),t?`-${r}`:r}function If(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 Lf(e){let t=Math.floor(e/Nf.h);e-=t*Nf.h;let n=Math.floor(e/Nf.m);e-=n*Nf.m;let r=Math.floor(e/Nf.s),i=e-r*Nf.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 Rf(e){return e*Nf.s}function zf(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 Bf(e,t){let n=t().getTime()-zf(e).getTime();return Ff(Math.round(n/1e3)*1e9)}const Vf=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Hf=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Uf=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Wf=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Gf(e){return e<10?`0${e}`:String(e)}function Kf(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function qf(e){return e<10?` ${e}`:String(e)}function Jf(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Gf(Math.floor(n/60))}${Gf(n%60)}`}function Yf(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Gf(Math.floor(n/60))}:${Gf(n%60)}`}function Xf(e){return`${e>=0?`+`:`-`}${Gf(Math.floor(Math.abs(e)/60))}`}function Zf(e){return e===0?`Z`:Jf(e)}function Qf(e){return e===0?`Z`:Yf(e)}function $f(e){return e===0?`Z`:Xf(e)}function ep(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const tp=[[`.000000000`,e=>`.${ep(e.ms,9,!1)}`],[`.999999999`,e=>{let t=ep(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${ep(e.ms,6,!1)}`],[`.999999`,e=>{let t=ep(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${Kf(e.ms)}`],[`.999`,e=>{let t=Kf(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Vf[e.month-1]??`January`],[`Monday`,e=>Uf[e.weekday]??`Monday`],[`Z07:00`,e=>Qf(e.offsetMinutes)],[`-07:00`,e=>Yf(e.offsetMinutes)],[`Z0700`,e=>Zf(e.offsetMinutes)],[`-0700`,e=>Jf(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Hf[e.month-1]??`Jan`],[`Mon`,e=>Wf[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>Xf(e.offsetMinutes)],[`Z07`,e=>$f(e.offsetMinutes)],[`15`,e=>Gf(e.hour)],[`01`,e=>Gf(e.month)],[`02`,e=>Gf(e.day)],[`_2`,e=>qf(e.day)],[`03`,e=>Gf(e.hour12)],[`04`,e=>Gf(e.minute)],[`05`,e=>Gf(e.second)],[`06`,e=>Gf(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 np(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of tp)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const rp={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function ip(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const ap=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function op(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=ip(new Intl.DateTimeFormat(`en-US`,{...rp,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=ip(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=sp(ip(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=ap.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 sp(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 cp(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function lp(e,t){return np(e,op(zf(t),cp()))}function up(e,t,n){return np(e,op(zf(t),n))}function dp(e,t){let n=zf(t),r=Pf(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function fp(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Ff(Rf(t))}return typeof e==`bigint`?Ff(Rf(Number(e))):typeof e==`number`?Ff(Rf(e)):`0s`}const pp=36e11*24*365,mp=36e11*24*30,hp=36e11*24,gp=36e11,_p=6e10,vp=1e9;function yp(e){let t=Pf(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>pp?`${Math.floor(n/pp)}y`:n>mp?`${Math.floor(n/mp)}mo`:n>hp?`${Math.floor(n/hp)}d`:n>gp?`${Math.floor(n/gp)}h`:n>_p?`${Math.floor(n/_p)}m`:n>vp?`${Math.floor(n/vp)}s`:`0s`}function bp(e){let t=op(zf(e),cp());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function xp(e,t){let n=op(zf(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Sp(e){return e()}const Cp=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],wp=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Tp(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Ep(e,t,n){return[e.slice(t,t+n),t+n]}function Dp(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 Op(e,t){for(let[n,r]of Cp.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function kp(e,t){for(let[n,r]of wp.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Ap(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 jp(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 Mp(e,t){if(e[t]===` `){let[n,r]=Dp(e,t+1,1,1);return[n,r]}return Dp(e,t,1,2)}function Np(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]=Dp(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=Dp(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=Dp(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Pp(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]=Dp(e,t+1,2,2);return[n*r*60,i]}return Np(e,t,n)}function Fp(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 Ip(e,t,n){let[r,i]=Ep(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function Lp(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Op(t,n);return i.month=e,[r,i]}case`Monday`:return[Ap(t,n),i];case`Jan`:{let[e,r]=kp(t,n);return i.month=e,[r,i]}case`Mon`:return[jp(t,n),i];case`2006`:{let[e,r]=Dp(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=Dp(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=Dp(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=Dp(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=Mp(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=Dp(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=Dp(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=Dp(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=Dp(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=Dp(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=Dp(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=Dp(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=Dp(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=Dp(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[Fp(t,n),i];case`-0700`:{let[e,r]=Np(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=Np(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]=Dp(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Pp(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Pp(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Pp(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]=Ip(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]=Ip(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]=Ip(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 Rp=`.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 zp(e,t){let n=0,r=0,i=Tp();for(;n<e.length;){let a=!1;for(let o of Rp)if(e.startsWith(o,n)){let[e,s]=Lp(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 Bp(e,t){return zp(e,t)}function Vp(e){return String(Math.floor(zf(e).getTime()/1e3))}function Hp(e=()=>new Date){return{now:{fn:()=>Sp(e),argTypes:[]},date:{fn:(e,t)=>lp(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>up(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>dp(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>bp(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>xp(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>fp(e),argTypes:[`value`]},durationRound:{fn:e=>yp(e),argTypes:[`value`]},toDate:{fn:(e,t)=>Bp(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>Bf(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>Vp(e),argTypes:[`value`]}}}function Up(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 Wp(...e){for(let t of e)if(!Up(t))return t}function Gp(e,t){return Up(t)?e:t}function Kp(e){return JSON.parse(e)}function qp(e,t,n){return gd(n)?e:t}function Jp(e){return JSON.stringify(e)??`null`}function Yp(e){return JSON.stringify(e,null,2)??`null`}function Xp(){return{default:{fn:(e,t)=>Gp(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>Up(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>Wp(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>qp(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>Kp(e),argTypes:[`string`]},toJson:{fn:e=>Jp(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>Yp(e),argTypes:[`serializable`],returnType:`string`}}}function Zp(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function Qp(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 Zp(...t)}function $p(e,t){return e[t]}function em(e,t){return t in e}function tm(e){return Object.keys(e)}function nm(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 rm(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function im(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 am(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function om(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function sm(e,t,n){return e[t]=n,e}function cm(e,t){return delete e[t],e}function lm(e){return Object.values(e)}function um(){return{dict:{fn:(...e)=>Zp(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>$p(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>sm(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>cm(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>tm(e),argTypes:[`dict`]},values:{fn:e=>lm(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>om(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>am(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>im(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>em(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>nm(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>rm(e,...t),argTypes:[`dict`]}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function dm(...e){for(let t of e)if(Up(t))return!1;return!0}function fm(...e){for(let t of e)if(!Up(t))return!0;return!1}function pm(e,t){return[...e,t]}function mm(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 hm(e){return e.filter(e=>!Up(e))}function gm(...e){let t=[];for(let n of e)t.push(...n);return t}const _m={line:0,column:0,offset:0};function vm(e,t,n,r){return new Ou(e,t,n,r,_m)}function ym(...e){if(e.length<3)throw vm(`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(!xm(t))throw vm(`dig`,e.length-1,`dict`,Sm(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw vm(`dig`,e,`string`,Sm(r[e]));return bm(t,n,r,e.length)}function bm(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(!xm(a))throw vm(`dig`,r-1,`dict at intermediate key`,Sm(a));return bm(a,t,n.slice(1),r)}function xm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Sm(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Cm(e){return e[0]}function wm(e,t){return t.some(t=>fd(t,e))}function Tm(e){return e.slice(0,-1)}function Em(e){return e[e.length-1]}function Dm(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Om(...e){return e}function km(e,t){return[t,...e]}function Am(e){return e.slice(1)}function jm(e){return[...e].reverse()}function Mm(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Nm(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Pm(e){let t=[];for(let n of e)t.some(e=>fd(e,n))||t.push(n);return t}function Fm(e,...t){return e.filter(e=>!t.some(t=>fd(t,e)))}function Im(){return{list:{fn:(...e)=>Om(...e),argTypes:[`value`]},first:{fn:e=>Cm(e),argTypes:[`list`]},last:{fn:e=>Em(e),argTypes:[`list`]},rest:{fn:e=>Am(e),argTypes:[`list`]},initial:{fn:e=>Tm(e),argTypes:[`list`]},len:{fn:e=>Dm(e),argTypes:[`sized`]},reverse:{fn:e=>jm(e),argTypes:[`list`]},uniq:{fn:e=>Pm(e),argTypes:[`list`]},without:{fn:(e,...t)=>Fm(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>wm(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>hm(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>Mm(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>gm(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>mm(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>km(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>pm(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>Nm(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>pm(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>Om(...e),argTypes:[`value`]},dig:{fn:(...e)=>ym(...e),argTypes:[`value`]},all:{fn:(...e)=>dm(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>fm(...e),argTypes:[`truthy`],returnType:`bool`}}}function Lm(...e){return e.reduce((e,t)=>e+t,0)}function Rm(e){return e+1}function zm(e){return e+1}function Bm(...e){return e.reduce((e,t)=>e+t,0)}function Vm(e){return Math.ceil(e)}function Hm(e,t){return Math.trunc(e/t)}function Um(e,t){return e/t}function Wm(e){return Math.floor(e)}function Gm(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function Km(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function qm(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function Jm(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function Ym(e,t){return e%t}function Xm(...e){return e.reduce((e,t)=>e*t,1)}function Zm(...e){return e.reduce((e,t)=>e*t,1)}function Qm(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function $m(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 eh(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),$m(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return $m(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:$m(n,i+t,r).join(` `)}default:return``}}function th(e,t){return e-t}function nh(e,t){return e-t}function rh(e){return $m(0,e,e<0?-1:1)}function ih(){return{add:{fn:(...e)=>Lm(...e),argTypes:[`int`]},sub:{fn:(e,t)=>th(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>Xm(...e),argTypes:[`int`]},div:{fn:(e,t)=>Hm(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>Ym(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>qm(...e),argTypes:[`int`]},max:{fn:(...e)=>Gm(...e),argTypes:[`int`]},floor:{fn:e=>Wm(e),argTypes:[`float`]},ceil:{fn:e=>Vm(e),argTypes:[`float`]},round:{fn:(e,t)=>Qm(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>Bm(...e),argTypes:[`float`]},subf:{fn:(e,t)=>nh(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>Zm(...e),argTypes:[`float`]},divf:{fn:(e,t)=>Um(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>Rm(e),argTypes:[`int`]},add1f:{fn:e=>zm(e),argTypes:[`float`]},maxf:{fn:(...e)=>Km(...e),argTypes:[`float`]},minf:{fn:(...e)=>Jm(...e),argTypes:[`float`]},biggest:{fn:(...e)=>Gm(...e),argTypes:[`int`]},seq:{fn:(...e)=>eh(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>rh(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>$m(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function ah(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function oh(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const Q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},sh=/^[-_\s]$/,ch=/^\p{P}$/u,lh=/^\p{L}$/u,uh=/^\p{Lu}$/u,dh=/^\p{N}$/u;function fh(e){return e!==void 0&&sh.test(e)}function ph(e){return e!==void 0&&lh.test(e)}function mh(e){return e!==void 0&&uh.test(e)}function hh(e){return e!==void 0&&dh.test(e)}function gh(e){return e!==void 0&&ch.test(e)}function _h(e,t){if(t>=e.length)return{word:{wt:Q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(fh(n)){for(;r<e.length&&fh(e[r]);)r++;return{word:{wt:Q.Connector,text:e.slice(t,r).join(``)},next:r}}if(gh(n)){for(;r<e.length&&gh(e[r]);)r++;return{word:{wt:Q.Punct,text:e.slice(t,r).join(``)},next:r}}if(mh(n)){if(r>=e.length)return{word:{wt:Q.UpperCase,text:n},next:r};if(mh(e[r])){let n=r;for(;n<e.length&&mh(e[n]);)n++;return n<e.length&&ph(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(ph(e[r])){let n=r+1;for(;n<e.length&&ph(e[n])&&!mh(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(ph(n)){for(;r<e.length&&ph(e[r])&&!mh(e[r]);)r++;return{word:{wt:Q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(hh(n)){for(;r<e.length&&hh(e[r]);)r++;return{word:{wt:Q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!fh(e[r])&&!ph(e[r])&&!hh(e[r])&&!gh(e[r]);)r++;return{word:{wt:Q.Other,text:e.slice(t,r).join(``)},next:r}}function vh(e,t,n){if(t.wt!==Q.UpperCase&&t.wt!==Q.Connector){e.push(t.text);return}for(let r of t.text)fh(r)?e.push(n):mh(r)?e.push(r.toLowerCase()):e.push(r)}function yh(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=_h(n,0);for(;a<n.length;){i.wt!==Q.Connector&&vh(r,i,t);let e=i,o=i;if({word:i,next:a}=_h(n,a),e.wt===Q.Number){for(;i.wt===Q.Alphabet||i.wt===Q.Number;)vh(r,i,t),{word:i,next:a}=_h(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Punct&&i.wt!==Q.Connector&&r.push(t);continue}if(e.wt===Q.Connector){vh(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}=_h(n,a),i.wt!==Q.Alphabet){vh(r,s,t),i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t);continue}for(r.push(t),vh(r,s,t);i.wt===Q.Alphabet||i.wt===Q.Number;)vh(r,i,t),{word:i,next:a}=_h(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t)}return vh(r,i,t),r.join(``).toLowerCase()}function bh(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!fh(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++,fh(i)&&fh(e)){n.push(e);continue}fh(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function xh(e){return bh(e)}function Sh(...e){return e.join(` `)}function Ch(e,t){return t.includes(e)}function wh(e,t){return t.startsWith(e)}function Th(e,t){return t.endsWith(e)}function Eh(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
94
+ `?(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 Gu(e){return e===` `||e===` `||e===`\r`||e===`
95
+ `}function Ku(e){return e===`+`||e===`-`}function qu(e){return e>=`0`&&e<=`9`}function Ju(e){return qu(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Yu(e){return e>=`0`&&e<=`7`}function Xu(e){return e===`0`||e===`1`}function Zu(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Qu(e){return Zu(e)||e===`_`}function $u(e){return Qu(e)||qu(e)}function ed(e,t){return new td(e,t).parseTemplate()}var td=class{lex;buf=[];defines=new Map;source;rangeDepth=0;constructor(e,t){this.source=e,this.lex=t?new Wu(e,t):new Wu(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:id(n)});return n}errAt(e,t,n={}){return new Mu(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 ${id(e)}`,{found:id(e)})}return{root:e,defines: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=rd(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 nd(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${id(n)} at top level`,{found:id(n)})}return nd(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 Mu(`{{${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.defines.set(n,a),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))throw new Mu(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,i)}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:id(e)});return fd(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(!ad(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:id(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=[od(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(od(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;ad(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 od(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:fd(e.value,e.pos,this.source)};case`Number`:return cd(e);case`Char`:return ld(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 ${id(e)}`,{expected:`command argument`,found:id(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 nd(e,t){return{type:`List`,pos:e,nodes:t}}function rd(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function id(e){return e.type===`EOF`?`end of input`:e.value||e.type}function ad(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 od(e){return{type:`Variable`,pos:e.pos,idents:sd(e.value)}}function sd(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function cd(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=ud(i);return{...s,intValue:e}}if(a){let e=dd(i);return{...s,floatValue:e}}let c=dd(i);return{...s,complexValue:[0,c]}}function ld(e,t){let n=pd(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 ud(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 dd(e){return Number(e)}function fd(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+=`
96
+ `;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 Mu(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function pd(e,t,n){let r=fd(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Mu(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function md(e,t){if(t(e)!==!1)for(let n of hd(e))md(n,t)}function hd(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 Vu(e)}}const gd=Symbol(`go-template-js.MISSING`);function _d(e,t){if(e==null)return gd;if(e instanceof Map)return e.has(t)?e.get(t):gd;if(Array.isArray(e))return gd;if(typeof e==`object`){let n=e;return t in n?n[t]:gd}return gd}function vd(e,t){let n=e;for(let e of t){if(n===gd)return gd;n=_d(n,e)}return n}function yd(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)=>yd(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)||!yd(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=>yd(e[n],t[n])):!1}return!1}const bd=new WeakSet;function xd(e){return bd.add(e),e}function Sd(e){return bd.has(e)}function Cd(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 wd(e){return{eq:{fn:(e,...t)=>t.some(t=>Dd(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!Dd(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>Od(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>Od(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>Od(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>Od(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>kd(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Ad(n,e);return n},argTypes:[`collection`,`index-key`]},slice:{fn:(e,...t)=>{let n=t.length>=1?t[0]:0,r=t.length>=2?t[1]:void 0;return e.slice(n,r)},argTypes:[`sliceable`,`int`]},print:{fn:(...t)=>Nd(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Nd(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>Hd(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>Id(Nd(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>zd(Nd(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>Vd(Nd(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!Cd(e),argTypes:[`truthy`]}}}function Td(){return{and:xd({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Cd(t))return t;return t}}),or:xd({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Cd(t))return t;return t}})}}function Ed(e){return{...wd(e),...Td()}}function Dd(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):yd(e,t)}function Od(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 kd(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Ad(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${jd(t)}`);if(n<0||n>=e.length)throw Error(`index: out of range [${n}] with length ${e.length}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`string`)return e[Number(t)];if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${jd(t)}`);return e[t]}throw Error(`index: cannot index ${jd(e)}`)}function jd(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Md(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 Nd(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+=Pd(a,t),r=o}return n}function Pd(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Fd={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Id(e){return e.replace(/[\0"'&<>]/g,e=>Fd[e]??e)}const Ld={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Rd=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function zd(e){let t=``;for(let n of e){let e=Ld[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Rd.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Bd=new TextEncoder;function Vd(e){let t=``,n=Bd.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 Hd(e,t,n){let r=``,i=0,a=0;for(;a<e.length;){let o=e[a];if(o!==`%`){r+=o,a+=1;continue}if(e[a+1]===`%`){r+=`%`,a+=2;continue}let s=a+1;for(;s<e.length&&`+-# 0`.includes(e[s]??``);)s+=1;for(;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;if(e[s]===`.`)for(s+=1;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;let c=e[s],l=e.slice(a+1,s),u=t[i++];r+=Ud(c??``,l,u,n),a=s+1}return r}function Ud(e,t,n,r){switch(e){case`s`:return typeof n==`string`?Wd(t,n):Wd(t,Pd(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Md(n)}=${Pd(n,r)})`:Wd(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return Wd(t,Gd(n));case`q`:return Wd(t,JSON.stringify(Pd(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Md(n)}=${Pd(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return Wd(t,Number(n).toFixed(i))}case`t`:return Wd(t,Cd(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 Wd(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Md(n)}=${Pd(n,r)})`:typeof n==`bigint`?Wd(t,n.toString(16)):Wd(t,Math.trunc(n).toString(16));default:return`%!${e}(${Md(n)}=${Pd(n,r)})`}}function Wd(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 Gd(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(Gd).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${Gd(e)}:${Gd(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(Gd).join(` `)}}`:String(e)}function Kd(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function qd(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function Jd(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 Yd(e,t,n){e.vars.set(t,n)}const Xd=new Set([`default`,`zero`,`error`]);function Zd(e){if(e===void 0)return`default`;if(Xd.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${Qd(e)}`)}function Qd(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 $d(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${Qd(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${Qd(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${Qd(e.right)}`);return{left:e.left,right:e.right}}}const ef=Object.freeze({kind:`break`}),tf=Object.freeze({kind:`continue`}),nf={kind:`none`};let rf;(class e{source;_evaluate;_referencedFunctions;_referencedCalls;constructor(e,t,n,r){this.source=e,this._evaluate=t,this._referencedFunctions=n,this._referencedCalls=r}static{rf=(t,n,r,i)=>new e(t,n,r,i)}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function af(e){let t=new Set,n=e=>{md(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}const of={kind:`dynamic`};function sf(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=kf(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:of}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return of;let t=e.cmds[0];if(t===void 0)return of;let n=t.args[0];return n===void 0||n.type!==`Identifier`?of:{kind:`call`,name:n.ident,args:t.args.slice(1).map(sf)}}default:return of}}function cf(e){let t=[],n=e=>{md(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(sf);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.defines.values())n(t);return t}var lf=class{fromString;toString;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??vf,this.missingKey=Zd(e.missingKey),this.delims=$d(e.delims),this.funcs={...Ed(this.toString),...e.funcs??{}}}parse(e){let t=ed(e,this.delims);return rf(t.source,e=>this.evalParsed(t,e),af(t),cf(t))}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=Kd(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 ef;case`Continue`:throw tf;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 Nu(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Vu(e)}}evalIf(e,t,n){Cd(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(Cd(r)){let i=qd(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=Ef(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=qd(t,o);if(i.length===1)Yd(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;Yd(a,e,r),Yd(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===tf)continue;throw e}}}catch(e){if(e===ef)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Nu(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=qd(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=qd(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=n.defines.get(e.name)??e.list;this.evalList(i,r,n)}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Nu(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,nf);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)Yd(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 Nu(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Nu(`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 Pu(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Sd(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)}mf(i.ident,a.argTypes,c,e.pos,n.source,this.toString,a.argTypePattern,this.fromString);try{return a.fn(...c)}catch(t){throw t instanceof Fu?new Fu(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof Lu?new Lu(t.message,e.pos,{source:n.source}):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 kf(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 Pu(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return mf(e.ident,t.argTypes,[],e.pos,n.source,this.toString,t.argTypePattern,this.fromString),t.fn()}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 Nu(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=vd(e,t);if(i!==gd)return i;if(this.missingKey===`error`)throw new Iu(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=Jd(t,i);if(!a.found)throw new Nu(`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(Array.isArray(e)){t.out.push(this.fromString(uf(e)));return}if(e instanceof Map){t.out.push(this.fromString(df(e)));return}t.out.push(e)}};function uf(e){return`[${e.map(ff).join(` `)}]`}function df(e){let t=[];for(let[n,r]of e)t.push(`${ff(n)}:${ff(r)}`);return`map[${t.join(` `)}]`}function ff(e){return e==null?`<nil>`:Array.isArray(e)?uf(e):e instanceof Map?df(e):String(e)}function pf(e){return new lf(e)}function mf(e,t,n,r,i,a=vf,o,s=_f){let c=hf(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!gf(o,d,a))throw new Fu(e,t+1,wf(o),Tf(d),r,{source:i});if(o===`liftable`&&typeof d==`string`&&(n[t]=s(d)),o===`int`?n[t]=Math.trunc(Number(d)):o===`float`&&(n[t]=Number(d)),o===`ordered`){if(l===-1)l=t;else if(!xf(n[l],d))throw new Fu(e,t+1,`${wf(`ordered`)} of the same kind as ${Tf(n[l])}`,Tf(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!Sf(n[u],d))throw new Fu(e,t+1,`${wf(`comparable`)} of the same kind as ${Tf(n[u])}`,Tf(d),r,{source:i})}}}function hf(e,t){if(e.length===0)return()=>`value`;if(t===`alternating`){let t=e.length;return n=>e[n%t]}let n=e[e.length-1];return t=>t<e.length?e[t]:n}function gf(e,t,n){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`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 t!=null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`list`:return Array.isArray(t);case`dict`:return yf(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||yf(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||yf(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||yf(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`||t!=null&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`serializable`:return bf(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function _f(e){return e}function vf(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 Fu(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Tf(e),{line:0,column:0,offset:0})}function yf(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 bf(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function xf(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Sf(e,t){let n=Cf(e),r=Cf(t);return n===`nil`||r===`nil`?!0:n===r}function Cf(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 wf(e){switch(e){case`int`:return`integer (finite number 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 Tf(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Ef(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?Df([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Df(Object.entries(e)):[]}function Df(e){return[...e].sort((e,t)=>Of(e[0],t[0]))}function Of(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 kf(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 Af(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function jf(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 Mf(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 Nf(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=Mf(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 Pf(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Mf(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 Ff(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 If(e){return JSON.stringify(e)??`null`}function Lf(e){return typeof e==`string`?e:Gd(e)}function Rf(e){return e.map(Lf)}function zf(){return{atoi:{fn:e=>Af(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Nf(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>Pf(e),argTypes:[`value`]},float64:{fn:e=>jf(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Lf(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>Rf(e),argTypes:[`list`]},toDecimal:{fn:e=>Ff(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>If(e),argTypes:[`serializable`],returnType:`string`}}}const Bf={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Vf(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*Bf[a],n=n.slice(e[0].length)}return t?-r:r}function Hf(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Bf.us?`${Math.floor(n)}ns`:n<Bf.ms?Uf(n,Bf.us,3,`µs`):n<Bf.s?Uf(n,Bf.ms,6,`ms`):Wf(n),t?`-${r}`:r}function Uf(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 Wf(e){let t=Math.floor(e/Bf.h);e-=t*Bf.h;let n=Math.floor(e/Bf.m);e-=n*Bf.m;let r=Math.floor(e/Bf.s),i=e-r*Bf.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 Gf(e){return e*Bf.s}function Kf(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 qf(e,t){let n=t().getTime()-Kf(e).getTime();return Hf(Math.round(n/1e3)*1e9)}const Jf=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Yf=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Xf=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Zf=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Qf(e){return e<10?`0${e}`:String(e)}function $f(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function ep(e){return e<10?` ${e}`:String(e)}function tp(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Qf(Math.floor(n/60))}${Qf(n%60)}`}function np(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Qf(Math.floor(n/60))}:${Qf(n%60)}`}function rp(e){return`${e>=0?`+`:`-`}${Qf(Math.floor(Math.abs(e)/60))}`}function ip(e){return e===0?`Z`:tp(e)}function ap(e){return e===0?`Z`:np(e)}function op(e){return e===0?`Z`:rp(e)}function sp(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const cp=[[`.000000000`,e=>`.${sp(e.ms,9,!1)}`],[`.999999999`,e=>{let t=sp(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${sp(e.ms,6,!1)}`],[`.999999`,e=>{let t=sp(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${$f(e.ms)}`],[`.999`,e=>{let t=$f(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Jf[e.month-1]??`January`],[`Monday`,e=>Xf[e.weekday]??`Monday`],[`Z07:00`,e=>ap(e.offsetMinutes)],[`-07:00`,e=>np(e.offsetMinutes)],[`Z0700`,e=>ip(e.offsetMinutes)],[`-0700`,e=>tp(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Yf[e.month-1]??`Jan`],[`Mon`,e=>Zf[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>rp(e.offsetMinutes)],[`Z07`,e=>op(e.offsetMinutes)],[`15`,e=>Qf(e.hour)],[`01`,e=>Qf(e.month)],[`02`,e=>Qf(e.day)],[`_2`,e=>ep(e.day)],[`03`,e=>Qf(e.hour12)],[`04`,e=>Qf(e.minute)],[`05`,e=>Qf(e.second)],[`06`,e=>Qf(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 lp(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of cp)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const up={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function dp(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const fp=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function pp(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=dp(new Intl.DateTimeFormat(`en-US`,{...up,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=dp(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=mp(dp(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=fp.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 mp(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 hp(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function gp(e,t){return lp(e,pp(Kf(t),hp()))}function _p(e,t,n){return lp(e,pp(Kf(t),n))}function vp(e,t){let n=Kf(t),r=Vf(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function yp(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Hf(Gf(t))}return typeof e==`bigint`?Hf(Gf(Number(e))):typeof e==`number`?Hf(Gf(e)):`0s`}const bp=36e11*24*365,xp=36e11*24*30,Sp=36e11*24,Cp=36e11,wp=6e10,Tp=1e9;function Ep(e){let t=Vf(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>bp?`${Math.floor(n/bp)}y`:n>xp?`${Math.floor(n/xp)}mo`:n>Sp?`${Math.floor(n/Sp)}d`:n>Cp?`${Math.floor(n/Cp)}h`:n>wp?`${Math.floor(n/wp)}m`:n>Tp?`${Math.floor(n/Tp)}s`:`0s`}function Dp(e){let t=pp(Kf(e),hp());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Op(e,t){let n=pp(Kf(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function kp(e){return e()}const Ap=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],jp=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Mp(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Np(e,t,n){return[e.slice(t,t+n),t+n]}function Pp(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 Fp(e,t){for(let[n,r]of Ap.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function Ip(e,t){for(let[n,r]of jp.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Lp(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 Rp(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 zp(e,t){if(e[t]===` `){let[n,r]=Pp(e,t+1,1,1);return[n,r]}return Pp(e,t,1,2)}function Bp(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]=Pp(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=Pp(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=Pp(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Vp(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]=Pp(e,t+1,2,2);return[n*r*60,i]}return Bp(e,t,n)}function Hp(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 Up(e,t,n){let[r,i]=Np(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function Wp(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Fp(t,n);return i.month=e,[r,i]}case`Monday`:return[Lp(t,n),i];case`Jan`:{let[e,r]=Ip(t,n);return i.month=e,[r,i]}case`Mon`:return[Rp(t,n),i];case`2006`:{let[e,r]=Pp(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=Pp(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=Pp(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=Pp(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=zp(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=Pp(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=Pp(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=Pp(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=Pp(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=Pp(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=Pp(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=Pp(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=Pp(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=Pp(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[Hp(t,n),i];case`-0700`:{let[e,r]=Bp(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=Bp(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]=Pp(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Vp(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Vp(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Vp(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]=Up(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]=Up(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]=Up(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 Gp=`.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 Kp(e,t){let n=0,r=0,i=Mp();for(;n<e.length;){let a=!1;for(let o of Gp)if(e.startsWith(o,n)){let[e,s]=Wp(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 qp(e,t){return Kp(e,t)}function Jp(e){return String(Math.floor(Kf(e).getTime()/1e3))}function Yp(e=()=>new Date){return{now:{fn:()=>kp(e),argTypes:[]},date:{fn:(e,t)=>gp(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>_p(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>vp(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>Dp(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>Op(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>yp(e),argTypes:[`value`]},durationRound:{fn:e=>Ep(e),argTypes:[`value`]},toDate:{fn:(e,t)=>qp(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>qf(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>Jp(e),argTypes:[`value`]}}}function Xp(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 Zp(...e){for(let t of e)if(!Xp(t))return t}function Qp(e,t){return Xp(t)?e:t}function $p(e){return JSON.parse(e)}function em(e,t,n){return Cd(n)?e:t}function tm(e){return JSON.stringify(e)??`null`}function nm(e){return JSON.stringify(e,null,2)??`null`}function rm(){return{default:{fn:(e,t)=>Qp(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>Xp(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>Zp(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>em(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>$p(e),argTypes:[`string`]},toJson:{fn:e=>tm(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>nm(e),argTypes:[`serializable`],returnType:`string`}}}function im(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function am(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 im(...t)}function om(e,t){return e[t]}function sm(e,t){return t in e}function cm(e){return Object.keys(e)}function lm(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 um(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function dm(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 fm(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function pm(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function mm(e,t,n){return e[t]=n,e}function hm(e,t){return delete e[t],e}function gm(e){return Object.values(e)}function _m(){return{dict:{fn:(...e)=>im(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>om(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>mm(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>hm(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>cm(e),argTypes:[`dict`]},values:{fn:e=>gm(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>pm(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>fm(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>dm(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>sm(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>lm(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>um(e,...t),argTypes:[`dict`]}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function vm(...e){for(let t of e)if(Xp(t))return!1;return!0}function ym(...e){for(let t of e)if(!Xp(t))return!0;return!1}function bm(e,t){return[...e,t]}function xm(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 Sm(e){return e.filter(e=>!Xp(e))}function Cm(...e){let t=[];for(let n of e)t.push(...n);return t}const wm={line:0,column:0,offset:0};function Tm(e,t,n,r){return new Fu(e,t,n,r,wm)}function Em(...e){if(e.length<3)throw Tm(`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(!Om(t))throw Tm(`dig`,e.length-1,`dict`,km(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Tm(`dig`,e,`string`,km(r[e]));return Dm(t,n,r,e.length)}function Dm(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(!Om(a))throw Tm(`dig`,r-1,`dict at intermediate key`,km(a));return Dm(a,t,n.slice(1),r)}function Om(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function km(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Am(e){return e[0]}function jm(e,t){return t.some(t=>yd(t,e))}function Mm(e){return e.slice(0,-1)}function Nm(e){return e[e.length-1]}function Pm(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Fm(...e){return e}function Im(e,t){return[t,...e]}function Lm(e){return e.slice(1)}function Rm(e){return[...e].reverse()}function zm(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Bm(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Vm(e){let t=[];for(let n of e)t.some(e=>yd(e,n))||t.push(n);return t}function Hm(e,...t){return e.filter(e=>!t.some(t=>yd(t,e)))}function Um(){return{list:{fn:(...e)=>Fm(...e),argTypes:[`value`]},first:{fn:e=>Am(e),argTypes:[`list`]},last:{fn:e=>Nm(e),argTypes:[`list`]},rest:{fn:e=>Lm(e),argTypes:[`list`]},initial:{fn:e=>Mm(e),argTypes:[`list`]},len:{fn:e=>Pm(e),argTypes:[`sized`]},reverse:{fn:e=>Rm(e),argTypes:[`list`]},uniq:{fn:e=>Vm(e),argTypes:[`list`]},without:{fn:(e,...t)=>Hm(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>jm(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>Sm(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>zm(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>Cm(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>xm(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>Im(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>bm(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>Bm(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>bm(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>Fm(...e),argTypes:[`value`]},dig:{fn:(...e)=>Em(...e),argTypes:[`value`]},all:{fn:(...e)=>vm(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>ym(...e),argTypes:[`truthy`],returnType:`bool`}}}function Wm(...e){return e.reduce((e,t)=>e+t,0)}function Gm(e){return e+1}function Km(e){return e+1}function qm(...e){return e.reduce((e,t)=>e+t,0)}function Jm(e){return Math.ceil(e)}function Ym(e,t){return Math.trunc(e/t)}function Xm(e,t){return e/t}function Zm(e){return Math.floor(e)}function Qm(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function $m(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function eh(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function th(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function nh(e,t){return e%t}function rh(...e){return e.reduce((e,t)=>e*t,1)}function ih(...e){return e.reduce((e,t)=>e*t,1)}function ah(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function oh(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 sh(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),oh(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return oh(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:oh(n,i+t,r).join(` `)}default:return``}}function ch(e,t){return e-t}function lh(e,t){return e-t}function uh(e){return oh(0,e,e<0?-1:1)}function dh(){return{add:{fn:(...e)=>Wm(...e),argTypes:[`int`]},sub:{fn:(e,t)=>ch(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>rh(...e),argTypes:[`int`]},div:{fn:(e,t)=>Ym(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>nh(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>eh(...e),argTypes:[`int`]},max:{fn:(...e)=>Qm(...e),argTypes:[`int`]},floor:{fn:e=>Zm(e),argTypes:[`float`]},ceil:{fn:e=>Jm(e),argTypes:[`float`]},round:{fn:(e,t)=>ah(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>qm(...e),argTypes:[`float`]},subf:{fn:(e,t)=>lh(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>ih(...e),argTypes:[`float`]},divf:{fn:(e,t)=>Xm(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>Gm(e),argTypes:[`int`]},add1f:{fn:e=>Km(e),argTypes:[`float`]},maxf:{fn:(...e)=>$m(...e),argTypes:[`float`]},minf:{fn:(...e)=>th(...e),argTypes:[`float`]},biggest:{fn:(...e)=>Qm(...e),argTypes:[`int`]},seq:{fn:(...e)=>sh(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>uh(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>oh(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function fh(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function ph(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const Q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},mh=/^[-_\s]$/,hh=/^\p{P}$/u,gh=/^\p{L}$/u,_h=/^\p{Lu}$/u,vh=/^\p{N}$/u;function yh(e){return e!==void 0&&mh.test(e)}function bh(e){return e!==void 0&&gh.test(e)}function xh(e){return e!==void 0&&_h.test(e)}function Sh(e){return e!==void 0&&vh.test(e)}function Ch(e){return e!==void 0&&hh.test(e)}function wh(e,t){if(t>=e.length)return{word:{wt:Q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(yh(n)){for(;r<e.length&&yh(e[r]);)r++;return{word:{wt:Q.Connector,text:e.slice(t,r).join(``)},next:r}}if(Ch(n)){for(;r<e.length&&Ch(e[r]);)r++;return{word:{wt:Q.Punct,text:e.slice(t,r).join(``)},next:r}}if(xh(n)){if(r>=e.length)return{word:{wt:Q.UpperCase,text:n},next:r};if(xh(e[r])){let n=r;for(;n<e.length&&xh(e[n]);)n++;return n<e.length&&bh(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(bh(e[r])){let n=r+1;for(;n<e.length&&bh(e[n])&&!xh(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(bh(n)){for(;r<e.length&&bh(e[r])&&!xh(e[r]);)r++;return{word:{wt:Q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(Sh(n)){for(;r<e.length&&Sh(e[r]);)r++;return{word:{wt:Q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!yh(e[r])&&!bh(e[r])&&!Sh(e[r])&&!Ch(e[r]);)r++;return{word:{wt:Q.Other,text:e.slice(t,r).join(``)},next:r}}function Th(e,t,n){if(t.wt!==Q.UpperCase&&t.wt!==Q.Connector){e.push(t.text);return}for(let r of t.text)yh(r)?e.push(n):xh(r)?e.push(r.toLowerCase()):e.push(r)}function Eh(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=wh(n,0);for(;a<n.length;){i.wt!==Q.Connector&&Th(r,i,t);let e=i,o=i;if({word:i,next:a}=wh(n,a),e.wt===Q.Number){for(;i.wt===Q.Alphabet||i.wt===Q.Number;)Th(r,i,t),{word:i,next:a}=wh(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Punct&&i.wt!==Q.Connector&&r.push(t);continue}if(e.wt===Q.Connector){Th(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}=wh(n,a),i.wt!==Q.Alphabet){Th(r,s,t),i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t);continue}for(r.push(t),Th(r,s,t);i.wt===Q.Alphabet||i.wt===Q.Number;)Th(r,i,t),{word:i,next:a}=wh(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t)}return Th(r,i,t),r.join(``).toLowerCase()}function Dh(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!yh(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++,yh(i)&&yh(e)){n.push(e);continue}yh(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Oh(e){return Dh(e)}function kh(...e){return e.join(` `)}function Ah(e,t){return t.includes(e)}function jh(e,t){return t.startsWith(e)}function Mh(e,t){return t.endsWith(e)}function Nh(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
97
97
  `).map(e=>n+e).join(`
98
- `)}function Dh(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function Oh(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw vm(`join`,2,`list of strings/primitives`,`list element of type ${kh(e)}`);n.push(String(e))}return n.join(e)}function kh(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Ah(e){return yh(e,`-`)}function jh(e){return e.toLowerCase()}function Mh(e,t){return`\n${Eh(e,t)}`}function Nh(e){return e.replace(/\s+/g,``)}function Ph(e,t,n){return n===1?e:t}function Fh(...e){return e.map(e=>`"${e}"`).join(` `)}function Ih(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Lh(e,t){return t.repeat(Math.max(0,e))}function Rh(e,t,n){return n.split(e).join(t)}function zh(e){return yh(e,`_`)}function Bh(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Vh(e,t){return t.split(e)}function Hh(e,t,n){let r=Uh(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Uh(e,t,n){if(n===0)return[];let r=t===``?Array.from(e):e.split(t);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 Wh(...e){return e.map(e=>`'${e}'`).join(` `)}function Gh(e,t,n){let r=t<0||t>n.length?n.length:t,i=Math.min(Math.max(0,e),r);return n.slice(i,r)}function Kh(e){let t=``;for(let n of e)qh(n)?t+=n.toLowerCase():Jh(n)?t+=n.toUpperCase():t+=n;return t}function qh(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function Jh(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Yh(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Xh(e){return e.trim()}function Zh(e,t){if(e.length===0)return t;let n=new Set([...e]),r=0;for(;r<t.length&&n.has(t[r]);)r+=1;let i=t.length;for(;i>r&&n.has(t[i-1]);)--i;return t.slice(r,i)}function Qh(e,t){return t.startsWith(e)?t.slice(e.length):t}function $h(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function eg(e,t){if(e<0){let n=-e;return n>=t.length?t:t.slice(t.length-n)}return e>=t.length?t:t.slice(0,e)}function tg(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function ng(e){return e.toUpperCase()}function rg(e,t){return ig(e,`
99
- `,t)}function ig(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
100
- `)){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 ag(e,t,n){return ig(e,t,n)}function og(){return{abbrev:{fn:(e,t)=>ah(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>oh(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>xh(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Sh(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Ch(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>wh(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Th(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Eh(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Dh(e),argTypes:[`string`]},join:{fn:(e,t)=>Oh(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>Ah(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>jh(e),argTypes:[`string`]},nindent:{fn:(e,t)=>Mh(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Nh(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Ph(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Fh(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Ih(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Lh(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>Rh(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>zh(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>Bh(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>Vh(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>Hh(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>Wh(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>Gh(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>Kh(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>Yh(e),argTypes:[`string`]},trim:{fn:e=>Xh(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>Zh(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>Qh(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>$h(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>eg(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>tg(e),argTypes:[`string`]},upper:{fn:e=>ng(e),argTypes:[`string`]},wrap:{fn:(e,t)=>rg(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>ag(e,t,n),argTypes:[`int`,`string`,`string`]}}}function sg(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const cg=`menus.`;function lg(e){return e}function ug(e,t,n){return n===void 0?cg+sg(e)+`.`+sg(t):cg+sg(n)}function dg(e,t){return e+`.`+t}function fg(e){return e+`.page`}function pg(e){for(let t of Object.keys(e))if(t!==`closeOnPick`&&t!==`paged`&&t!==`key`)throw Error(`unknown {{ menu }} option "${t}" — the options dict takes "closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping)`);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)`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n}}const mg=`menu`,hg=`the positional tail ("pageAction" closeOnPick paged "key") was removed: the page cursor is now synthesized from the menu's identity, and rare knobs are named options in ONE trailing dict — write {{ menu "applyTheme" }} or {{ menu "applyTheme" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key)`;function gg(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 (e.g. {{ menu "applyTheme" }})`);if(e.argExprs.length>2)return t(`with more than two arguments — ${hg}`);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" }})`);if(r!==void 0&&(r.kind!==`call`||r.name!==`dict`))return t(`whose second argument is not an options (dict …) — ${hg}`);let i=r===void 0?{}:Qp(r);if(i===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)`);try{return{kind:`ok`,apply:n.value,options:pg(i)}}catch(e){return t(`with invalid options — ${e.message}`)}}function _g(e){let t=of({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===mg).map(gg)}catch{return`parse-failed`}}function vg(e){let t=of({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(mg)}catch{return!1}}function yg(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,[`root`])})}function bg(e,t){$l(e,t,cg,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))vg(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:Z(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`&&vg(i)&&yg(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.`)}let r=new Map;if(t.root!==void 0)for(let n of Zr(t.root))typeof n.when==`string`&&vg(n.when)&&yg(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.`),n.kind===`segment`&&r.set(n.name,(r.get(n.name)??0)+1);for(let[t,i]of Object.entries(n))vg(i.template)&&(r.get(t)??0)>1&&yg(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`);let i=new Set,a={},o=new Set,s=new Map;for(let[t,r]of Object.entries(n)){if(!vg(r.template))continue;let n=_g(r.template);if(n!==`parse-failed`)for(let r of n){if(r.kind===`issue`){yg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${r.message}.`);continue}let{apply:n,options:c}=r;if(n===``){yg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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.`);continue}let l=lg(n);if(l===`closed`){yg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${zt}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=ug(t,n,c.key),d=fg(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=s.get(e);return t!==void 0&&t!==f});if(p!==void 0){yg(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") 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}s.set(u,f),s.set(d,f);let m=dg(u,l);if(o.has(m)){yg(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}o.add(m),i.add(u),a[m]=Vt(u,l)}}if(i.size===0)return;let c={};for(let e of i){c[e]=Bt(e,zt);let t=fg(e);c[t]={kind:`state`,key:t,default:`0`},a[t]={set:t,int:!0}}t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const xg=`edit.`,Sg=`edit.mode`,Cg=`edit.toggle`,wg=`open`,Tg=`{{ eq .${Sg} "${wg}" }}`;function Eg(e){let t=of({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Dg(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Eg(e))return!0;return!1}function Og(e,t){if($l(e,t,xg,`edit mode`),!Dg(t))return;let n={[Sg]:Bt(Sg,zt)},r={[Cg]:Vt(Sg,wg)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function kg(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Ag(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 jg(e){let t=new Set,n=e=>{if(e.kind===`segment`){t.add(e.name);return}for(let t of e.children)n(t)};return n(e),t}function Mg(e,t){return t.reduce(Ng,e)}function Ng(e,t){return t.op===`remove`?Pg(e,t.target):Fg(e,t.segment,t.anchor,t.relation)}function Pg(e,t){let n=!1;function r(e){if(n||e.kind===`segment`)return e;let i=[];for(let a of e.children){if(!n&&a.kind===`segment`&&a.name===t){n=!0;continue}i.push(r(a))}return{...e,children:i}}let i=r(e);return n?i:e}function Fg(e,t,n,r){let i=!1;function a(e){if(i||e.kind===`segment`)return e;let o=[];for(let s of e.children){if(!i&&s.kind===`segment`&&s.name===n){i=!0;let e={kind:`segment`,name:t};r===`before`?o.push(e,s):o.push(s,e);continue}o.push(a(s))}return{...e,children:o}}let o=a(e);return i?o:e}const Ig=`default`,Lg={};function Rg(e){return[...new Set([Ig,...Object.keys(e)])]}function zg(e,t,n){return Sc(e,t,Ig,n)}function Bg(e,t){let n={[Ig]:Lg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Ig}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Vg(e,t){let n=Bg(e.presets,t).root;return n===void 0?{node:e.root,path:`root`}:{node:n,path:`presets.${t}.root`}}function Hg(e,t){return{...e.globals,...Bg(e.presets,t).globals}}function Ug(e,t){let n=e.preset;if(n===void 0||Rg(t).includes(n))return e;let r={...e};return delete r.preset,r}function Wg(e,t){let n=new Set(Rg(t)),r=Object.entries(e).filter(([e])=>n.has(e));return r.length===Object.keys(e).length?e:Object.fromEntries(r)}function Gg(e,t){let n=e[t];return n===void 0?!1:n.some(e=>Ag(e)!==null)}function Kg(e,t){let n=Object.entries(t).filter(([,e])=>e.length>0);if(n.length===0)return e;let r={...e.presets};for(let[t,i]of n){let n=i.map(Ag).filter(e=>e!==null);if(n.length===0)continue;let{node:a}=Vg(e,t);r[t]={...Bg(e.presets,t),root:Mg(a,n)}}return{...e,presets:r}}const qg=/^segments\.([^.]+)\.palette$/,Jg=/^presets\.(.+)\.rootOps$/;function Yg(e){return`presets.${e}.rootOps`}function Xg(e){if(vl(e))return{scope:`globals`,field:e};let t=qg.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Jg.exec(e);return n?{scope:`preset-root-ops`,preset:n[1]}:null}const Zg=`settings.`,Qg=`${Zg}menu`,$g=wg,e_=`${Zg}presets`,t_=`${Zg}edit`,n_=`${Zg}applyPreset`,r_=`{{ eq .${Qg} "${$g}" }}`;function i_(e){return e===Qg}function a_(e){let t={kind:`segment`,name:Qg};if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t],...e.when!==void 0&&{when:e.when}};let[n,...r]=e.children;return e.direction===`vertical`&&n!==void 0&&n.when===void 0?{...e,children:[a_(n),...r]}:{...e,children:[...e.children,t]}}function o_(e){return s_(e)>0?e:a_(e)}function s_(e){return e.kind===`segment`?+!!i_(e.name):e.children.reduce((e,t)=>e+s_(t),0)}function c_(e){return e.kind===`segment`?i_(e.name)?{kind:`container`,direction:`vertical`,children:[e,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:e_},{kind:`segment`,name:t_}],when:r_}]}:e:{...e,children:e.children.map(c_)}}function l_(e,t,n){let r=lg(t),i=ug(e,t,void 0),a=fg(i);n.variables[i]=Bt(i,zt),n.variables[a]={kind:`state`,key:a,default:`0`},n.actions[dg(i,r)]=Vt(i,r),n.actions[a]={set:a,int:!0}}function u_(){let e={variables:{[Qg]:Bt(Qg,zt)},actions:{[Qg]:Vt(Qg,$g),[n_]:{set:`preset`,from:`presets`}},segments:{[Qg]:{template:`{{ action "${Qg}" "☰ ▸" "☰ ▾" }}`,bg:`surface`,fg:`foreground`},[e_]:{template:`▦ {{ menu "${n_}" (dict "closeOnPick" true) }}`,bg:`surface`,fg:`foreground`},[t_]:{template:`{{ action "${Cg}" "✎ edit" "✎ done" }}`,bg:`surface`,fg:`foreground`}}};return l_(e_,n_,e),e}function d_(e){e.variables[Sg]=Bt(Sg,zt),e.actions[Cg]=Vt(Sg,wg)}const f_=`session.id`;function p_(e){return Object.prototype.hasOwnProperty.call(e.variables,f_)}function m_(e){if(!p_(e))return e;let t=u_();d_(t);let n={...e.presets};for(let t of Rg(e.presets)){let{node:r}=Vg(e,t);n[t]={...Bg(e.presets,t),root:c_(o_(r))}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const h_=`preset.customized`,g_=`{{ .${h_} }}`;function __(e){return e.startsWith(`edit.`)||e.startsWith(`menus.`)||e.startsWith(`groups.`)||e.startsWith(`settings.`)}function v_(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function y_(e){return`${xg}addable.${e}`}function b_(e){let t=Object.keys(e.segments).filter(e=>!__(e)),n=new Map;for(let r of Rg(e.presets)){let{node:i}=Vg(e,r),a=jg(i);n.set(y_(r),t.filter(e=>!a.has(e)))}return n}function x_(e,t,n,r){let i=`${xg}${e}.remove.${sg(n)}`,a=`${xg}${e}.removeSeg.${sg(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:Tg},{kind:`segment`,name:a}}function S_(e,t,n,r,i,a,o){let s=`${xg}${e}.insert.${n}`,c=`${xg}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=lg(s),u=ug(c,s,void 0),d=fg(u),f=dg(u,l);return o.variables[u]=Bt(u,zt),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=Vt(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`+{{ menu "${s}" }}`,when:Tg},{kind:`segment`,name:c}}function C_(e,t,n,r,i,a){let o=[],s=e.children.reduce((e,t,n)=>t.kind===`segment`&&!__(t.name)?n:e,-1);for(let[c,l]of e.children.entries()){if(l.kind===`container`){o.push(C_(l,t,n,r,i,a));continue}if(__(l.name)){o.push(l);continue}o.push(S_(t,n,String(a.n++),r,l.name,`before`,i)),o.push(l),o.push(x_(t,n,l.name,i)),c===s&&o.push(S_(t,n,String(a.n++),r,l.name,`after`,i))}return{...e,children:o}}function w_(e,t,n,r,i){let a=`${xg}${n}.resetLayout`,o=`${xg}${n}.customized`;i.actions[a]={reset:r},i.ensured[h_]={kind:`input`,path:h_,type:`boolean`,default:!1};let s=v_(t);return i.segments[o]={template:`{{ action "${a}" "↺ ${s} customized" }}`,when:g_},{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:o},e],...e.when!==void 0&&{when:e.when}}}function T_(e,t,n){let{node:r}=Vg(e,t),i=Yg(t),a=y_(t),o=sg(t),s={n:0};return w_(C_(r.kind===`container`?r:{kind:`container`,direction:`horizontal`,children:[r],...r.when!==void 0&&{when:r.when}},o,i,a,n,s),t,o,i,n)}function E_(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},ensured:{},actions:{},segments:{}},n={...e.presets};for(let r of Rg(e.presets)){let i=T_(e,r,t);n[r]={...Bg(e.presets,r),root:i}}return{...e,variables:{...t.ensured,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const D_=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`];function O_(e){return`set`in e}function k_(e){return`persist`in e}function A_(e){return`reset`in e}function j_(e){return`undo`in e}function M_(e){return`redo`in e}function N_(e,t){if(t===void 0)return{};if(!zc(t))return P_(e,`actions`,`actions must be an object, got ${Bc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=F_(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function P_(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,t.split(`.`))})}function F_(e,t,n){if(!zc(n))return P_(e,t,`${t} must be an action object, got ${Bc(n)}`),null;let r=D_.filter(e=>e in n);return r.length===1?I_[r[0]](e,t,n):(P_(e,t,`action must declare exactly one of: ${D_.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const I_={set:(e,t,n)=>sv(e,t,n,`set`,rv,`the SessionState key to write`),persist:(e,t,n)=>sv(e,t,n,`persist`,iv,`the config globals field to write`),copy:L_(`copy`),open:L_(`open`),reset:R_,undo:z_(`undo`),redo:z_(`redo`)};function L_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&P_(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Pc(t,n,r,e);return i===null?null:{[e]:i}}}function R_(e,t,n){for(let r of Object.keys(n))r!==`reset`&&P_(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=B_(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}}function z_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&P_(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(P_(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the ONE global history over the whole overrides layer), got ${Vc(r[e])}`),null)}}function B_(e,t,n,r,i,a){let o=Pc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(P_(e,s,i),null):o.includes(`/`)?(P_(e,s,a(o)),null):o}function V_(e,t,n,r,i){return B_(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`)}function H_(e){return e===`set`?`set-state`:`set-config`}const U_={to:cv(`set`)},W_={to:cv(`persist`)},G_={from:lv(`set`)},K_={from:lv(`persist`)},q_={min:mv(),max:mv(),by:mv()},J_={int:dv()},Y_={cycle:uv(`set`)},X_={cycle:uv(`persist`)},Z_={removeSegment:fv(`removeSegment`)},Q_={insertSegment:fv(`insertSegment`),anchor:fv(`anchor`),relation:pv()},$_={insertSegmentFrom:lv(`persist`),anchor:fv(`anchor`),relation:pv()},ev={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},tv={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function nv(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=(e,n,r)=>Uc(e,t,n,r),s=nl(t);return{detect:a,allowed:[e,...i],label:i.join(`/`),json:{type:`object`,properties:{[e]:{type:`string`},...s.properties},required:[e,...s.required??[]],additionalProperties:!1},parse:n.length?Jc(o,...n):o}}const rv=[nv(`set`,U_),nv(`set`,G_),nv(`set`,q_,[ev,tv]),nv(`set`,J_),nv(`set`,Y_)],iv=[nv(`persist`,W_),nv(`persist`,K_),nv(`persist`,q_,[ev,tv]),nv(`persist`,X_),nv(`persist`,Z_),nv(`persist`,Q_,[],[`insertSegment`]),nv(`persist`,$_,[],[`insertSegmentFrom`])];function av(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", 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 ov(e){let t=av(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 sv(e,t,n,r,i,a){let o=V_(e,t,n,r,a),s=i.filter(e=>e.detect.some(e=>e in n));if(s.length!==1)return P_(e,t,`${ov(r)}${s.length>1?` — found: ${s.map(e=>e.label).join(`, `)}`:``}`),null;let c=s[0];for(let i of Object.keys(n))c.allowed.includes(i)||P_(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${c.allowed.join(`, `)}`);let l=c.parse(e,t,n);return o===null||l===null?null:{[r]:o,...l}}function cv(e){let t=H_(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>B_(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 lv(e){let t=H_(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===``){P_(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){P_(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===``)){P_(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){P_(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){P_(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}P_(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Vc(o)}`)}}}function uv(e){let t=H_(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`)){P_(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Bc(o)}`);return}let c=o;if(c.length<2){P_(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){P_(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){P_(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){P_(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function dv(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){P_(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Vc(r[n])}`);return}return!0}}}function fv(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Pc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){P_(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){P_(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 pv(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){P_(e,`${t}.${n}`,`relation must be "before" or "after", got ${Vc(i)}`);return}return i}}}function mv(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){P_(e,`${t}.${n}`,`${n} must be an integer, got ${Vc(i)}`);return}return i}}}const hv={noun:`look key`,fields:{hueShift:Qc(),chromaScale:Qc({min:0}),lightnessScale:Qc(),lightnessShift:Qc()}};function gv(e,t){if(!zc(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${Bc(t)}`,line:Z(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:Z(e.source,[`looks`,r])});continue}let t=Hc(e,hv,`looks.${r}`,i);t!==null&&(n[r]={...Ea,...t})}return n}const _v={noun:`preset key`,fields:{root:{required:!1,json:{$ref:eu},parse:(e,t,n,r)=>r[n]===void 0?void 0:fu(e,`${t}.${n}`,r[n])},globals:{required:!1,json:gl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:hl(e,`${t}.${n}`,r[n])}}};function vv(e,t){if(!zc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Bc(t)}`,line:Z(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:Z(e.source,[`presets`,r])});continue}let t=Hc(e,_v,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function yv(e,t){if(t===void 0)return{};if(!zc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Bc(t)}`,line:Z(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 ${Vc(i)}`,line:Z(e.source,[`helpers`,r])});continue}n[r]=i}return n}const bv=new Map;function xv(e,t){bv.set(e,{permanent:!0,resolve:t})}xv(`themes`,()=>xc()),xv(`styles`,()=>Tc),xv(`charsets`,()=>Oc),xv(`colorCompatibilities`,()=>kc);function Sv(e){return new Map([[`looks`,Object.keys(e.looks)],[`presets`,Rg(e.presets)]])}function Cv(e){return[...new Set([...bv.keys(),...e.keys()])]}function wv(e,t){if(typeof e!=`string`)return e;let n=t.get(e);if(n)return n;let r=bv.get(e);if(r)return r.resolve();throw Error(`unknown option domain "${e}" (have: ${Cv(t).join(`, `)})`)}const Tv=/{{([\s\S]*?)}}/g,Ev=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,Dv=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function Ov(e){let t=new Set,n;for(Tv.lastIndex=0;(n=Tv.exec(e))!==null;){let e=n[1].replace(Ev,``),r;for(Dv.lastIndex=0;(r=Dv.exec(e))!==null;)t.add(r[1])}return t}const kv=/\baction\s+$/;function Av(e){let t=new Set;Tv.lastIndex=0;let n;for(;(n=Tv.exec(e))!==null;){let e=n[1],r=0,i;for(Ev.lastIndex=0;(i=Ev.exec(e))!==null;)kv.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const jv=/\b(picker|menu)\s+$/;function Mv(e){let t=new Set;Tv.lastIndex=0;let n;for(;(n=Tv.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(Ev.lastIndex=0;(a=Ev.exec(e))!==null;){let n=jv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function Nv(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const Pv={gitTaculous:`gitaculous`};function Fv(e,t){let n=new Map;for(let e of Object.keys(t)){let t=sg(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:Z(e.source,[`presets`])})}function Iv(e,t){t.globals.look!==void 0&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:Z(e.source,[`globals`,`look`])}),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:Z(e.source,[`globals`,`preset`])}),Fv(e,t.presets);let n=Sv(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||Cv(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${Cv(n).join(`, `)})`,line:Z(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=Xg(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${yl().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.rootOps" target`,line:Z(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root-ops`){Lv(e,t,n,a,i,o.preset,r);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}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:Z(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:Z(e.source,[`actions`,n,a])})}}let r=new Set(Object.keys(t.variables));for(let[e,n]of Object.entries(t.segments))if(n.vars)for(let t of Object.keys(n.vars))r.add(`${e}.${t}`);let i=p_(t),a=(n,a,o)=>{s_(n)>1&&e.issues.push({path:a,message:`${a} places the global settings menu anchor "${Qg}" ${s_(n)} 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:o});for(let s of Zr(n))if(s.when!==void 0&&Hv(e,`${a}.when`,s.when,r,{line:o}),s.kind===`segment`){if(i_(s.name)){i||e.issues.push({path:a,message:`${a} places the global settings menu anchor "${Qg}", but this config declares no "${f_}" variable — the menu is a click surface and every click composes a URL from "${f_}", so it is not synthesized for a config without it. Declare a "${f_}" variable (any config merged onto the bundled default inherits one) or remove the anchor placement.`,line:o});continue}if(!Object.prototype.hasOwnProperty.call(t.segments,s.name)){let t=Pv[s.name],n=t===void 0?``:` (the built-in segment "${s.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:a,message:`${a} entry "${s.name}" does not match any declared segment${n}`,line:o})}}},o=Uv(e.source);a(t.root,o,Z(e.source,[o]));for(let[n,r]of Object.entries(t.presets))r.root!==void 0&&a(r.root,`presets.${n}.root`,Z(e.source,[`presets`,n,`root`]));for(let[n,i]of Object.entries(t.variables))Bv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))Bv(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){Hv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of Av(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:Z(e.source,[`segments`,n,a])});for(let r of Mv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:Z(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))Vv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))Vv(e,`segments.${n}.vars.${t}`,a,r,n);(Rv(t)||zv(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:Z(e.source,[`variables`])})}function Lv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=Z(e.source,[`actions`,n,r]);if(!Rg(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Rg(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>.rootOps" 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=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function Rv(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function zv(e){return Object.values(e.actions).some(e=>O_(e)||k_(e)||A_(e)||j_(e)||M_(e))}function Bv(e,t,n,r,i){n.kind===`template`&&Hv(e,`${t}.template`,n.template,r,{segCtx:i}),$r(n)&&n.cache&&`key`in n.cache&&Hv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function Vv(e,t,n,r,i){if($r(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.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.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:Z(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function Hv(e,t,n,r,i){for(let a of Ov(n)){if(Nv(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&Nv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Z(e.source,t.split(`.`))})}}function Uv(e){try{let t=ci.default.parse(e);if(zc(t)&&`root`in t)return`root`}catch{}return`layout`}function Wv(e,t){let{graph:n,nodeInfo:r}=Gv(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:Z(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function Gv(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=(e,n)=>{for(let i of Ov(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),$r(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 Kv=[`json5`,`json`];function qv(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function Jv(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[qv(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return[...e?Kv.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...Kv.map(e=>c.join(i,`.cc-candybar.${e}`)),...Kv.map(e=>c.join(a,`cc-candybar`,`config.${e}`))]}function Yv(e,t,n){return Jv(e,t,n).find(r.existsSync)??null}function Xv(e,t){let n=Jv(e,t),i=new Set,a=[];for(let e of n)i.has(e)||(i.add(e),r.existsSync(e)&&a.push(e));let o=new Map;for(let e of a){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),r=c.join(t,n);o.has(r)||o.set(r,[]),o.get(r).push(e)}let s=[...o.values()].filter(e=>e.length>1);return s.length===0?null:`config-extension collision: ${s.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Zv(e,t,n){let i=e===null?``:r.readFileSync(e,`utf-8`);return{config:sl(e===null?{}:$v(e,i,n),t),source:i}}function Qv(e,t=`<config>`,n=``,r=new Set(xc())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(Iv(a,e),Wv(a,e),i.length>0)throw new Ac(t,i);return E_(m_(e))}function $v(e,t,n=new Set(xc())){let r=ey(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!zc(r))throw new Ac(e,[{path:``,message:`Config root must be an object, got ${Bc(r)}`}]);let o=ty(a,r);if(i.length>0)throw new Ac(e,i);return o}function ey(e,t){try{return ci.default.parse(t)}catch(t){let n=t;throw new Ac(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function ty(e,t){for(let n of Object.keys(t))ny.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...ny].join(`, `)}`,line:Z(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=ml(e,`globals`,t.globals)),t.variables!==void 0&&(n.variables=Ml(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=Yl(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
98
+ `)}function Ph(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function Fh(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Tm(`join`,2,`list of strings/primitives`,`list element of type ${Ih(e)}`);n.push(String(e))}return n.join(e)}function Ih(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Lh(e){return Eh(e,`-`)}function Rh(e){return e.toLowerCase()}function zh(e,t){return`\n${Nh(e,t)}`}function Bh(e){return e.replace(/\s+/g,``)}function Vh(e,t,n){return n===1?e:t}function Hh(...e){return e.map(e=>`"${e}"`).join(` `)}function Uh(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Wh(e,t){return t.repeat(Math.max(0,e))}function Gh(e,t,n){return n.split(e).join(t)}function Kh(e){return Eh(e,`_`)}function qh(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Jh(e,t){return t.split(e)}function Yh(e,t,n){let r=Xh(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Xh(e,t,n){if(n===0)return[];let r=t===``?Array.from(e):e.split(t);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 Zh(...e){return e.map(e=>`'${e}'`).join(` `)}function Qh(e,t,n){let r=t<0||t>n.length?n.length:t,i=Math.min(Math.max(0,e),r);return n.slice(i,r)}function $h(e){let t=``;for(let n of e)eg(n)?t+=n.toLowerCase():tg(n)?t+=n.toUpperCase():t+=n;return t}function eg(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function tg(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function ng(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function rg(e){return e.trim()}function ig(e,t){if(e.length===0)return t;let n=new Set([...e]),r=0;for(;r<t.length&&n.has(t[r]);)r+=1;let i=t.length;for(;i>r&&n.has(t[i-1]);)--i;return t.slice(r,i)}function ag(e,t){return t.startsWith(e)?t.slice(e.length):t}function og(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function sg(e,t){if(e<0){let n=-e;return n>=t.length?t:t.slice(t.length-n)}return e>=t.length?t:t.slice(0,e)}function cg(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function lg(e){return e.toUpperCase()}function ug(e,t){return dg(e,`
99
+ `,t)}function dg(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
100
+ `)){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 fg(e,t,n){return dg(e,t,n)}function pg(){return{abbrev:{fn:(e,t)=>fh(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>ph(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Oh(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>kh(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Ah(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>jh(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Mh(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Nh(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Ph(e),argTypes:[`string`]},join:{fn:(e,t)=>Fh(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>Lh(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Rh(e),argTypes:[`string`]},nindent:{fn:(e,t)=>zh(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Bh(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Vh(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Hh(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Uh(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Wh(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>Gh(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>Kh(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>qh(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>Jh(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>Yh(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>Zh(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>Qh(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>$h(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>ng(e),argTypes:[`string`]},trim:{fn:e=>rg(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>ig(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>ag(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>og(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>sg(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>cg(e),argTypes:[`string`]},upper:{fn:e=>lg(e),argTypes:[`string`]},wrap:{fn:(e,t)=>ug(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>fg(e,t,n),argTypes:[`int`,`string`,`string`]}}}function mg(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const hg=`menus.`;function gg(e){return e}function _g(e,t,n){return n===void 0?hg+mg(e)+`.`+mg(t):hg+mg(n)}function vg(e,t){return e+`.`+t}function yg(e){return e+`.page`}function bg(e){for(let t of Object.keys(e))if(t!==`closeOnPick`&&t!==`paged`&&t!==`key`)throw Error(`unknown {{ menu }} option "${t}" — the options dict takes "closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping)`);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)`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n}}const xg=`menu`,Sg=`the positional tail ("pageAction" closeOnPick paged "key") was removed: the page cursor is now synthesized from the menu's identity, and rare knobs are named options in ONE trailing dict — write {{ menu "applyTheme" }} or {{ menu "applyTheme" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key)`;function Cg(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 (e.g. {{ menu "applyTheme" }})`);if(e.argExprs.length>2)return t(`with more than two arguments — ${Sg}`);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" }})`);if(r!==void 0&&(r.kind!==`call`||r.name!==`dict`))return t(`whose second argument is not an options (dict …) — ${Sg}`);let i=r===void 0?{}:am(r);if(i===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)`);try{return{kind:`ok`,apply:n.value,options:bg(i)}}catch(e){return t(`with invalid options — ${e.message}`)}}function wg(e){let t=pf({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===xg).map(Cg)}catch{return`parse-failed`}}function Tg(e){let t=pf({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(xg)}catch{return!1}}function Eg(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,[`root`])})}function Dg(e,t){ou(e,t,hg,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))Tg(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:Z(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`&&Tg(i)&&Eg(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.`)}let r=new Map;if(t.root!==void 0)for(let n of Zr(t.root))typeof n.when==`string`&&Tg(n.when)&&Eg(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.`),n.kind===`segment`&&r.set(n.name,(r.get(n.name)??0)+1);for(let[t,i]of Object.entries(n))Tg(i.template)&&(r.get(t)??0)>1&&Eg(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`);let i=new Set,a={},o=new Set,s=new Map;for(let[t,r]of Object.entries(n)){if(!Tg(r.template))continue;let n=wg(r.template);if(n!==`parse-failed`)for(let r of n){if(r.kind===`issue`){Eg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${r.message}.`);continue}let{apply:n,options:c}=r;if(n===``){Eg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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.`);continue}let l=gg(n);if(l===`closed`){Eg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${zt}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=_g(t,n,c.key),d=yg(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=s.get(e);return t!==void 0&&t!==f});if(p!==void 0){Eg(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") 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}s.set(u,f),s.set(d,f);let m=vg(u,l);if(o.has(m)){Eg(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}o.add(m),i.add(u),a[m]=Vt(u,l)}}if(i.size===0)return;let c={};for(let e of i){c[e]=Bt(e,zt);let t=yg(e);c[t]={kind:`state`,key:t,default:`0`},a[t]={set:t,int:!0}}t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const Og=`edit.`,kg=`edit.mode`,Ag=`edit.toggle`,jg=`open`,Mg=`{{ eq .${kg} "${jg}" }}`;function Ng(e){let t=pf({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Pg(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Ng(e))return!0;return!1}function Fg(e,t){if(ou(e,t,Og,`edit mode`),!Pg(t))return;let n={[kg]:Bt(kg,zt)},r={[Ag]:Vt(kg,jg)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Ig(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Lg(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 Rg(e){let t=new Set,n=e=>{if(e.kind===`segment`){t.add(e.name);return}for(let t of e.children)n(t)};return n(e),t}function zg(e,t){return t.reduce(Bg,e)}function Bg(e,t){return t.op===`remove`?Vg(e,t.target):Hg(e,t.segment,t.anchor,t.relation)}function Vg(e,t){let n=!1;function r(e){if(n||e.kind===`segment`)return e;let i=[];for(let a of e.children){if(!n&&a.kind===`segment`&&a.name===t){n=!0;continue}i.push(r(a))}return{...e,children:i}}let i=r(e);return n?i:e}function Hg(e,t,n,r){let i=!1;function a(e){if(i||e.kind===`segment`)return e;let o=[];for(let s of e.children){if(!i&&s.kind===`segment`&&s.name===n){i=!0;let e={kind:`segment`,name:t};r===`before`?o.push(e,s):o.push(s,e);continue}o.push(a(s))}return{...e,children:o}}let o=a(e);return i?o:e}const Ug=`default`,Wg={};function Gg(e){return[...new Set([Ug,...Object.keys(e)])]}function Kg(e,t,n){return Cc(e,t,Ug,n)}function qg(e,t){let n={[Ug]:Wg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Ug}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Jg(e,t){let n=qg(e.presets,t).root;return n===void 0?{node:e.root,path:`root`}:{node:n,path:`presets.${t}.root`}}function Yg(e,t){return{...e.globals,...qg(e.presets,t).globals}}function Xg(e,t){let n=e.preset;if(n===void 0||Gg(t).includes(n))return e;let r={...e};return delete r.preset,r}function Zg(e,t){let n=new Set(Gg(t)),r=Object.entries(e).filter(([e])=>n.has(e));return r.length===Object.keys(e).length?e:Object.fromEntries(r)}function Qg(e,t){let n=e[t];return n===void 0?!1:n.some(e=>Lg(e)!==null)}function $g(e,t){let n=Object.entries(t).filter(([,e])=>e.length>0);if(n.length===0)return e;let r={...e.presets};for(let[t,i]of n){let n=i.map(Lg).filter(e=>e!==null);if(n.length===0)continue;let{node:a}=Jg(e,t);r[t]={...qg(e.presets,t),root:zg(a,n)}}return{...e,presets:r}}const e_=/^segments\.([^.]+)\.palette$/,t_=/^presets\.(.+)\.rootOps$/;function n_(e){return`presets.${e}.rootOps`}function r_(e){if(Tl(e))return{scope:`globals`,field:e};let t=e_.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=t_.exec(e);return n?{scope:`preset-root-ops`,preset:n[1]}:null}const i_=`settings.`,a_=`${i_}menu`,o_=jg,s_=`${i_}presets`,c_=`${i_}edit`,l_=`${i_}applyPreset`,u_=`{{ eq .${a_} "${o_}" }}`;function d_(e){return e===a_}function f_(e){let t={kind:`segment`,name:a_};if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t],...e.when!==void 0&&{when:e.when}};let[n,...r]=e.children;return e.direction===`vertical`&&n!==void 0&&n.when===void 0?{...e,children:[f_(n),...r]}:{...e,children:[...e.children,t]}}function p_(e){return m_(e)>0?e:f_(e)}function m_(e){return e.kind===`segment`?+!!d_(e.name):e.children.reduce((e,t)=>e+m_(t),0)}function h_(e){return e.kind===`segment`?d_(e.name)?{kind:`container`,direction:`vertical`,children:[e,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:s_},{kind:`segment`,name:c_}],when:u_}]}:e:{...e,children:e.children.map(h_)}}function g_(e,t,n){let r=gg(t),i=_g(e,t,void 0),a=yg(i);n.variables[i]=Bt(i,zt),n.variables[a]={kind:`state`,key:a,default:`0`},n.actions[vg(i,r)]=Vt(i,r),n.actions[a]={set:a,int:!0}}function __(){let e={variables:{[a_]:Bt(a_,zt)},actions:{[a_]:Vt(a_,o_),[l_]:{set:`preset`,from:`presets`}},segments:{[a_]:{template:`{{ action "${a_}" "☰ ▸" "☰ ▾" }}`,bg:`surface`,fg:`foreground`},[s_]:{template:`▦ {{ menu "${l_}" (dict "closeOnPick" true) }}`,bg:`surface`,fg:`foreground`},[c_]:{template:`{{ action "${Ag}" "✎ edit" "✎ done" }}`,bg:`surface`,fg:`foreground`}}};return g_(s_,l_,e),e}function v_(e){e.variables[kg]=Bt(kg,zt),e.actions[Ag]=Vt(kg,jg)}const y_=`session.id`;function b_(e){return Object.prototype.hasOwnProperty.call(e.variables,y_)}function x_(e){if(!b_(e))return e;let t=__();v_(t);let n={...e.presets};for(let t of Gg(e.presets)){let{node:r}=Jg(e,t);n[t]={...qg(e.presets,t),root:h_(p_(r))}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const S_=`preset.customized`,C_=`{{ .${S_} }}`;function w_(e){return e.startsWith(`edit.`)||e.startsWith(`menus.`)||e.startsWith(`groups.`)||e.startsWith(`settings.`)}function T_(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function E_(e){return`${Og}addable.${e}`}function D_(e){let t=Object.keys(e.segments).filter(e=>!w_(e)),n=new Map;for(let r of Gg(e.presets)){let{node:i}=Jg(e,r),a=Rg(i);n.set(E_(r),t.filter(e=>!a.has(e)))}return n}function O_(e,t,n,r){let i=`${Og}${e}.remove.${mg(n)}`,a=`${Og}${e}.removeSeg.${mg(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:Mg},{kind:`segment`,name:a}}function k_(e,t,n,r,i,a,o){let s=`${Og}${e}.insert.${n}`,c=`${Og}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=gg(s),u=_g(c,s,void 0),d=yg(u),f=vg(u,l);return o.variables[u]=Bt(u,zt),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=Vt(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`+{{ menu "${s}" }}`,when:Mg},{kind:`segment`,name:c}}function A_(e,t,n,r,i,a){let o=[],s=e.children.reduce((e,t,n)=>t.kind===`segment`&&!w_(t.name)?n:e,-1);for(let[c,l]of e.children.entries()){if(l.kind===`container`){o.push(A_(l,t,n,r,i,a));continue}if(w_(l.name)){o.push(l);continue}o.push(k_(t,n,String(a.n++),r,l.name,`before`,i)),o.push(l),o.push(O_(t,n,l.name,i)),c===s&&o.push(k_(t,n,String(a.n++),r,l.name,`after`,i))}return{...e,children:o}}function j_(e,t,n,r,i){let a=`${Og}${n}.resetLayout`,o=`${Og}${n}.customized`;i.actions[a]={reset:r},i.ensured[S_]={kind:`input`,path:S_,type:`boolean`,default:!1};let s=T_(t);return i.segments[o]={template:`{{ action "${a}" "↺ ${s} customized" }}`,when:C_},{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:o},e],...e.when!==void 0&&{when:e.when}}}function M_(e,t,n){let{node:r}=Jg(e,t),i=n_(t),a=E_(t),o=mg(t),s={n:0};return j_(A_(r.kind===`container`?r:{kind:`container`,direction:`horizontal`,children:[r],...r.when!==void 0&&{when:r.when}},o,i,a,n,s),t,o,i,n)}function N_(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},ensured:{},actions:{},segments:{}},n={...e.presets};for(let r of Gg(e.presets)){let i=M_(e,r,t);n[r]={...qg(e.presets,r),root:i}}return{...e,variables:{...t.ensured,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const P_=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`];function F_(e){return`set`in e}function I_(e){return`persist`in e}function L_(e){return`reset`in e}function R_(e){return`undo`in e}function z_(e){return`redo`in e}function B_(e,t){if(t===void 0)return{};if(!Kc(t))return V_(e,`actions`,`actions must be an object, got ${qc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=H_(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function V_(e,t,n){e.issues.push({path:t,message:n,line:Z(e.source,t.split(`.`))})}function H_(e,t,n){if(!Kc(n))return V_(e,t,`${t} must be an action object, got ${qc(n)}`),null;let r=P_.filter(e=>e in n);return r.length===1?U_[r[0]](e,t,n):(V_(e,t,`action must declare exactly one of: ${P_.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const U_={set:(e,t,n)=>mv(e,t,n,`set`,uv,`the SessionState key to write`),persist:(e,t,n)=>mv(e,t,n,`persist`,dv,`the config globals field to write`),copy:W_(`copy`),open:W_(`open`),reset:G_,undo:K_(`undo`),redo:K_(`redo`)};function W_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&V_(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Vc(t,n,r,e);return i===null?null:{[e]:i}}}function G_(e,t,n){for(let r of Object.keys(n))r!==`reset`&&V_(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=q_(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}}function K_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&V_(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(V_(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the ONE global history over the whole overrides layer), got ${Jc(r[e])}`),null)}}function q_(e,t,n,r,i,a){let o=Vc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(V_(e,s,i),null):o.includes(`/`)?(V_(e,s,a(o)),null):o}function J_(e,t,n,r,i){return q_(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`)}function Y_(e){return e===`set`?`set-state`:`set-config`}const X_={to:hv(`set`)},Z_={to:hv(`persist`)},Q_={from:gv(`set`)},$_={from:gv(`persist`)},ev={min:xv(),max:xv(),by:xv()},tv={int:vv()},nv={cycle:_v(`set`)},rv={cycle:_v(`persist`)},iv={removeSegment:yv(`removeSegment`)},av={insertSegment:yv(`insertSegment`),anchor:yv(`anchor`),relation:bv()},ov={insertSegmentFrom:gv(`persist`),anchor:yv(`anchor`),relation:bv()},sv={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},cv={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function lv(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=(e,n,r)=>Xc(e,t,n,r),s=ll(t);return{detect:a,allowed:[e,...i],label:i.join(`/`),json:{type:`object`,properties:{[e]:{type:`string`},...s.properties},required:[e,...s.required??[]],additionalProperties:!1},parse:n.length?tl(o,...n):o}}const uv=[lv(`set`,X_),lv(`set`,Q_),lv(`set`,ev,[sv,cv]),lv(`set`,tv),lv(`set`,nv)],dv=[lv(`persist`,Z_),lv(`persist`,$_),lv(`persist`,ev,[sv,cv]),lv(`persist`,rv),lv(`persist`,iv),lv(`persist`,av,[],[`insertSegment`]),lv(`persist`,ov,[],[`insertSegmentFrom`])];function fv(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", 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 pv(e){let t=fv(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 mv(e,t,n,r,i,a){let o=J_(e,t,n,r,a),s=i.filter(e=>e.detect.some(e=>e in n));if(s.length!==1)return V_(e,t,`${pv(r)}${s.length>1?` — found: ${s.map(e=>e.label).join(`, `)}`:``}`),null;let c=s[0];for(let i of Object.keys(n))c.allowed.includes(i)||V_(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${c.allowed.join(`, `)}`);let l=c.parse(e,t,n);return o===null||l===null?null:{[r]:o,...l}}function hv(e){let t=Y_(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>q_(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function gv(e){let t=Y_(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===``){V_(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){V_(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===``)){V_(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){V_(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){V_(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}V_(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Jc(o)}`)}}}function _v(e){let t=Y_(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`)){V_(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${qc(o)}`);return}let c=o;if(c.length<2){V_(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){V_(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){V_(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){V_(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function vv(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){V_(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Jc(r[n])}`);return}return!0}}}function yv(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Vc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){V_(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){V_(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 bv(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){V_(e,`${t}.${n}`,`relation must be "before" or "after", got ${Jc(i)}`);return}return i}}}function xv(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){V_(e,`${t}.${n}`,`${n} must be an integer, got ${Jc(i)}`);return}return i}}}const Sv={noun:`look key`,fields:{hueShift:al(),chromaScale:al({min:0}),lightnessScale:al(),lightnessShift:al()}};function Cv(e,t){if(!Kc(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${qc(t)}`,line:Z(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:Z(e.source,[`looks`,r])});continue}let t=Yc(e,Sv,`looks.${r}`,i);t!==null&&(n[r]={...Ea,...t})}return n}const wv={noun:`preset key`,fields:{root:{required:!1,json:{$ref:su},parse:(e,t,n,r)=>r[n]===void 0?void 0:yu(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Cl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Sl(e,`${t}.${n}`,r[n])}}};function Tv(e,t){if(!Kc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${qc(t)}`,line:Z(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:Z(e.source,[`presets`,r])});continue}let t=Yc(e,wv,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function Ev(e,t){if(t===void 0)return{};if(!Kc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${qc(t)}`,line:Z(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 ${Jc(i)}`,line:Z(e.source,[`helpers`,r])});continue}n[r]=i}return n}const Dv=new Map;function Ov(e,t){Dv.set(e,{permanent:!0,resolve:t})}Ov(`themes`,()=>Sc()),Ov(`styles`,()=>Ec),Ov(`charsets`,()=>kc),Ov(`colorCompatibilities`,()=>Ac);function kv(e){return new Map([[`looks`,Object.keys(e.looks)],[`presets`,Gg(e.presets)]])}function Av(e){return[...new Set([...Dv.keys(),...e.keys()])]}function jv(e,t){if(typeof e!=`string`)return e;let n=t.get(e);if(n)return n;let r=Dv.get(e);if(r)return r.resolve();throw Error(`unknown option domain "${e}" (have: ${Av(t).join(`, `)})`)}const Mv=/{{([\s\S]*?)}}/g,Nv=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,Pv=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function Fv(e){let t=new Set,n;for(Mv.lastIndex=0;(n=Mv.exec(e))!==null;){let e=n[1].replace(Nv,``),r;for(Pv.lastIndex=0;(r=Pv.exec(e))!==null;)t.add(r[1])}return t}const Iv=/\baction\s+$/;function Lv(e){let t=new Set;Mv.lastIndex=0;let n;for(;(n=Mv.exec(e))!==null;){let e=n[1],r=0,i;for(Nv.lastIndex=0;(i=Nv.exec(e))!==null;)Iv.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const Rv=/\b(picker|menu)\s+$/;function zv(e){let t=new Set;Mv.lastIndex=0;let n;for(;(n=Mv.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(Nv.lastIndex=0;(a=Nv.exec(e))!==null;){let n=Rv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function Bv(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const Vv={gitTaculous:`gitaculous`};function Hv(e,t){let n=new Map;for(let e of Object.keys(t)){let t=mg(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:Z(e.source,[`presets`])})}function Uv(e,t){t.globals.look!==void 0&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:Z(e.source,[`globals`,`look`])}),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:Z(e.source,[`globals`,`preset`])}),Hv(e,t.presets);let n=kv(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||Av(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${Av(n).join(`, `)})`,line:Z(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=r_(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${El().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.rootOps" target`,line:Z(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root-ops`){Wv(e,t,n,a,i,o.preset,r);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}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:Z(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:Z(e.source,[`actions`,n,a])})}}let r=new Set(Object.keys(t.variables));for(let[e,n]of Object.entries(t.segments))if(n.vars)for(let t of Object.keys(n.vars))r.add(`${e}.${t}`);let i=b_(t),a=(n,a,o)=>{m_(n)>1&&e.issues.push({path:a,message:`${a} places the global settings menu anchor "${a_}" ${m_(n)} 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:o});for(let s of Zr(n))if(s.when!==void 0&&Yv(e,`${a}.when`,s.when,r,{line:o}),s.kind===`segment`){if(d_(s.name)){i||e.issues.push({path:a,message:`${a} places the global settings menu anchor "${a_}", but this config declares no "${y_}" variable — the menu is a click surface and every click composes a URL from "${y_}", so it is not synthesized for a config without it. Declare a "${y_}" variable (any config merged onto the bundled default inherits one) or remove the anchor placement.`,line:o});continue}if(!Object.prototype.hasOwnProperty.call(t.segments,s.name)){let t=Vv[s.name],n=t===void 0?``:` (the built-in segment "${s.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:a,message:`${a} entry "${s.name}" does not match any declared segment${n}`,line:o})}}},o=Xv(e.source);a(t.root,o,Z(e.source,[o]));for(let[n,r]of Object.entries(t.presets))r.root!==void 0&&a(r.root,`presets.${n}.root`,Z(e.source,[`presets`,n,`root`]));for(let[n,i]of Object.entries(t.variables))qv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))qv(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){Yv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of Lv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:Z(e.source,[`segments`,n,a])});for(let r of zv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:Z(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))Jv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))Jv(e,`segments.${n}.vars.${t}`,a,r,n);(Gv(t)||Kv(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:Z(e.source,[`variables`])})}function Wv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=Z(e.source,[`actions`,n,r]);if(!Gg(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Gg(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>.rootOps" 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=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function Gv(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function Kv(e){return Object.values(e.actions).some(e=>F_(e)||I_(e)||L_(e)||R_(e)||z_(e))}function qv(e,t,n,r,i){n.kind===`template`&&Yv(e,`${t}.template`,n.template,r,{segCtx:i}),$r(n)&&n.cache&&`key`in n.cache&&Yv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function Jv(e,t,n,r,i){if($r(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.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.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:Z(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function Yv(e,t,n,r,i){for(let a of Fv(n)){if(Bv(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&Bv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Z(e.source,t.split(`.`))})}}function Xv(e){try{let t=ci.default.parse(e);if(Kc(t)&&`root`in t)return`root`}catch{}return`layout`}function Zv(e,t){let{graph:n,nodeInfo:r}=Qv(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:Z(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function Qv(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=(e,n)=>{for(let i of Fv(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),$r(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 $v=[`json5`,`json`];function ey(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function ty(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[ey(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return[...e?$v.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...$v.map(e=>c.join(i,`.cc-candybar.${e}`)),...$v.map(e=>c.join(a,`cc-candybar`,`config.${e}`))]}function ny(e,t,n){return ty(e,t,n).find(r.existsSync)??null}function ry(e,t){let n=ty(e,t),i=new Set,a=[];for(let e of n)i.has(e)||(i.add(e),r.existsSync(e)&&a.push(e));let o=new Map;for(let e of a){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),r=c.join(t,n);o.has(r)||o.set(r,[]),o.get(r).push(e)}let s=[...o.values()].filter(e=>e.length>1);return s.length===0?null:`config-extension collision: ${s.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function iy(e,t,n){let i=e===null?``:r.readFileSync(e,`utf-8`);return{config:ml(e===null?{}:oy(e,i,n),t),source:i}}function ay(e,t=`<config>`,n=``,r=new Set(Sc())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(Uv(a,e),Zv(a,e),i.length>0)throw new Lc(t,i);return N_(x_(e))}function oy(e,t,n=new Set(Sc())){let r=sy(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!Kc(r))throw new Lc(e,[{path:``,message:`Config root must be an object, got ${qc(r)}`}]);let o=cy(a,r);if(i.length>0)throw new Lc(e,i);return o}function sy(e,t){try{return ci.default.parse(t)}catch(t){let n=t;throw new Lc(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function cy(e,t){for(let n of Object.keys(t))ly.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...ly].join(`, `)}`,line:Z(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=xl(e,`globals`,t.globals)),t.variables!==void 0&&(n.variables=zl(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=nu(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
101
101
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
102
102
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
103
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:Z(e.source,[`layout`])}),t.root!==void 0&&(n.root=fu(e,`root`,t.root)),t.actions!==void 0&&(n.actions=N_(e,t.actions)),t.looks!==void 0&&(n.looks=gv(e,t.looks)),t.presets!==void 0&&(n.presets=vv(e,t.presets)),t.helpers!==void 0&&(n.helpers=yv(e,t.helpers)),Cu(e,n),bg(e,n),Og(e,n),$l(e,n,Zg,`the global settings menu`),n}const ny=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`helpers`]),ry=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function iy(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 ay(e){let t=await oy(e);return t.kind===`ok`?R(Math.floor((t.value+36e5)/1e3)):t}async function oy(e){for(let t of[65536,1048576]){let n=await Or(e,t);if(n.kind!==`ok`)return n;let r=sy(n.value.buf,n.value.fromStart);if(r!=null)return R(r);if(n.value.fromStart)return z}return z}function sy(e,t){let n=e.toString(`utf8`).split(`
104
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!ry.test(t))continue;let r=iy(t);if(r!=null)return r}return null}const cy=10*1e3;function ly(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 uy(e,t){if(!(t<60))return e*3600/t}function dy(e,t,n,r){let i=r-t;if(i<50||i>cy)return;let a=n-e;if(!(a<=0))return a*1e3/i}function fy(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=dy(t.input,t.atMs,n.input,n.atMs),i=dy(t.output,t.atMs,n.output,n.atMs),a=dy(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 py(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>cy)continue;let o=dy(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function my(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function hy(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`,()=>my(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function gy(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,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}`,i);let n=[],r=new Set;for(let t of Zr(e.root)){if(t.when)for(let e of Ov(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of Ov(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of _y(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of Ov(e.template))n.push(t)}}}return i}function _y(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 vy(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function yy(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 by(e,t,n,r,i,a){let o=e=>vy(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Bn(`${e}: ${String(t)}`)):Promise.resolve(z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,yy(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>ay(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=Cy(l);_.push(...y.failures);let b=hy(a);_.push(...b.failures);let x=v(u),S=v(d),C=v(f),w=v(p),ee=v(m),T=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let te=e.rate_limits?.five_hour,ne=e.rate_limits?.seven_day,re=te?ly(te.used_percentage,te.resets_at,18e6,s):void 0,E=ne?ly(ne.used_percentage,ne.resets_at,6048e5,s):void 0,D=x?.session.cost,ie=w?.sessionDuration,ae=o(`burn`)&&D!=null&&ie!=null?uy(D,ie):void 0,oe=v(g),se=oe===void 0?void 0:fy(oe),ce=oe===void 0?void 0:py(oe),le=se!==void 0||ce!==void 0?{...se,...ce!==void 0&&{history:ce}}:void 0,ue=Sy(process.env.HOME??process.env.USERPROFILE),de=e.workspace?{...e.workspace,current_dir:Sy(e.workspace.current_dir)??``,project_dir:Sy(e.workspace.project_dir)??``}:e.workspace,fe=x===void 0?void 0:xy({cost:x.session.cost,tokens:x.session.tokens}),O=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},pe=w===void 0?void 0:xy({lastResponseTime:w.lastResponseTime,responseTime:w.responseTime,sessionDuration:w.sessionDuration,messageCount:w.messageCount,linesAdded:w.linesAdded,linesRemoved:w.linesRemoved});return{...e,...de!==void 0&&{workspace:de},...ue!==void 0&&{home:ue},...y.git!==void 0&&{git:y.git},...ee!==void 0&&{tmux:{session:ee}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...fe!==void 0&&{session:fe},...O!==void 0&&{today:O},...ae!==void 0&&{burn:{costPerHour:ae}},...le!==void 0&&{speed:le},...o(`block`)&&te!==void 0&&{block:{nativeUtilization:te.used_percentage,resetsAt:te.resets_at,...re!==void 0&&{etaMinutes:re}}},...ne!==void 0&&{weekly:{percentage:ne.used_percentage,resetsAt:ne.resets_at,...E!==void 0&&{etaMinutes:E}}},...T!==void 0&&{cache:{expiresAt:T}},...C!==void 0&&{context:{totalTokens:C.totalTokens,contextLeft:C.contextLeftPercentage}},...pe!==void 0&&{metrics:pe}}}function xy(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 Sy(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Cy(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const wy=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,Ty=`{{ \$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 (${wy}) (basename .project_dir) (ne (${wy}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,Ey={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},Dy=(e,t)=>`{{ fg (color "${Ey[e]}") ${t} }}`,Oy=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,ky=`{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} ({{ \$first := true }}{{ if gt .git.staged 0 }}${Dy(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${Dy(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${Dy(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${Dy(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,Ay=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${Dy(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Dy(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${Dy(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+ky+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${Dy(`stash`,`(printf "⧇ %v" .git.stash)`)}{{ end }} {{ if eq .git.status "conflicts" }}{{ fg (color "error") "⚠" }}{{ else }}{{ if eq .git.status "dirty" }}{{ fg (color "warning") "●" }}{{ else }}{{ fg (color "success") "✓" }}{{ end }}{{ end }}`;function jy(e,t){return`{{ if ge (round ${e}) ${t} }}error{{ else }}{{ if ge (round ${e}) 50 }}warning{{ else }}panel{{ end }}{{ end }}`}function My(e){return`{{ if ge (round ${e}) 50 }}button-color-foreground{{ else }}foreground{{ end }}`}function Ny(e,t,n){return`{{ if lt ${e} 0 }}panel{{ else }}{{ if lt ${e} ${n} }}error{{ else }}{{ if lt ${e} ${t} }}warning{{ else }}panel{{ end }}{{ end }}{{ end }}`}function Py(e,t){return`{{ if lt ${e} 0 }}foreground{{ else }}{{ if lt ${e} ${t} }}button-color-foreground{{ else }}foreground{{ end }}{{ end }}`}const Fy={globals:{palette:`tokyo-night`},variables:{current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},version:{kind:`input`,path:`version`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"style.effective":{kind:`input`,path:`style.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"hue.step":{kind:`literal`,value:14},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.repoUrl":{kind:`input`,path:`git.repoUrl`,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.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},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"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},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},activeStyle:{kind:`state`,key:`style`,default:``}},segments:{directory:{template:Ty,bg:`surface`,fg:`foreground`},model:{template:`✱ {{ formatModelName .model.display_name }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{template:`⌗{{ trunc 8 .session.id }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{template:`◈ v{{ .version }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{template:`tmux:{{ .tmux.session | default "none" }}`,bg:`surface-active`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{template:Ay,bg:`surface-active`,fg:Oy,when:`{{ ne .git.branch "" }}`},gitaculous:{template:`(git){{ if ne .git.repoName "" }} {{ .git.repoName }}{{ end }}{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} {{ if gt .git.staged 0 }}${Dy(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${Dy(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${Dy(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${Dy(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${Dy(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Dy(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${Dy(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${Dy(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,bg:`surface-active`,fg:Oy,when:`{{ ne .git.branch "" }}`},gitPr:{template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,bg:`surface-active`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,bg:`surface`,fg:`foreground`},session:{template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},today:{template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},block:{template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .block.resetsAt) }})`,bg:jy(`.block.nativeUtilization`,`.block.budget.warningThreshold`),fg:My(`.block.nativeUtilization`),when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .weekly.resetsAt) }})`,bg:jy(`.weekly.percentage`,`.weekly.budget.warningThreshold`),fg:My(`.weekly.percentage`),when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:Ny(`.block.etaMinutes`,`.burn.eta.warnMinutes`,`.burn.eta.errorMinutes`),fg:Py(`.block.etaMinutes`,`.burn.eta.warnMinutes`),when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,bg:`panel`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{template:`⚡ {{ sparkline .speed.history 24 }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,bg:`surface`,fg:`{{ if le (minutesUntilReset .cache.expiresAt) 8 }}error{{ else }}{{ if le (minutesUntilReset .cache.expiresAt) 20 }}warning{{ else }}foreground{{ end }}{{ end }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ if le .context.contextLeft 20 }}error{{ else }}{{ if le .context.contextLeft 40 }}warning{{ else }}surface-active{{ end }}{{ end }}`,fg:`{{ if le .context.contextLeft 40 }}button-color-foreground{{ else }}foreground{{ end }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{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 }} `,bg:`panel`,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},styleControl:{template:`✦ {{ if .activeStyle }}{{ .activeStyle }}{{ else }}(default){{ end }} {{ menu "applyStyle" }} 📌{{ menu "applyStyleForever" (dict "key" "pickersForever") }} {{ action "resetStyle" "↺" }}`,bg:`surface`,fg:`foreground`},themeControl:{template:`🎨 {{ .theme.effective }} {{ menu "applyTheme" (dict "key" "pickers") }} 📌{{ menu "applyThemeForever" (dict "key" "pickersForever") }} {{ action "resetTheme" "↺" }}`,bg:`surface`,fg:`foreground`},lookControl:{template:`◐ {{ .look.effective }} {{ menu "applyLook" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyLookForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetLook" "↺" }}`,bg:`surface`,fg:`foreground`},presetControl:{template:`▦ {{ .preset.effective }} {{ menu "applyPreset" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyPresetForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetPreset" "↺" }}`,bg:`surface`,fg:`foreground`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" }} {{ action "resetCharset" "↺" }}`,bg:`surface`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" }} {{ action "resetColorCompat" "↺" }}`,bg:`surface`,fg:`foreground`},wrapToggleControl:{template:`{{ action "toggleWrapForever" "wrap: on" "wrap: off" }} {{ action "resetAutoWrap" "↺" }}`,bg:`surface`,fg:`foreground`},paddingControl:{template:`{{ action "paddingDownForever" "◀" }} padding {{ .padding.effective }} {{ action "paddingUpForever" "▶" }} {{ action "resetPadding" "↺" }}`,bg:`surface`,fg:`foreground`},directoryPaletteControl:{template:`🎨 directory {{ menu "applyDirectoryPaletteForever" }} {{ action "resetDirectoryPalette" "↺" }}`,bg:`surface`,fg:`foreground`}},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:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ settings`,direction:`horizontal`,children:[`themeControl`,`lookControl`,`presetControl`,`styleControl`,`charsetControl`,`colorCompatControl`,`wrapToggleControl`,`paddingControl`,`directoryPaletteControl`]}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}]},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyStyle:{set:`style`,from:`styles`},applyTheme:{set:`theme`,from:`themes`},applyLook:{set:`look`,from:`looks`},applyPreset:{set:`preset`,from:`presets`},applyThemeForever:{persist:`palette`,from:`themes`},resetTheme:{reset:`palette`},applyStyleForever:{persist:`style`,from:`styles`},resetStyle:{reset:`style`},applyLookForever:{persist:`look`,from:`looks`},resetLook:{reset:`look`},applyPresetForever:{persist:`preset`,from:`presets`},resetPreset:{reset:`preset`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},toggleWrapForever:{persist:`autoWrap`,cycle:[`true`,`false`]},resetAutoWrap:{reset:`autoWrap`},paddingDownForever:{persist:`padding`,min:0,max:16,by:-1},paddingUpForever:{persist:`padding`,min:0,max:16,by:1},resetPadding:{reset:`padding`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{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}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`},{kind:`segment`,name:`presetControl`}]},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:`segment`,name:`toolbar`},{kind:`segment`,name:`presetControl`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{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`}]}]}}},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,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 }}`}},Iy=new Set([Fy.globals.palette,...Object.values(Fy.segments).map(e=>e.palette)].filter(e=>e!==void 0)),Ly=sl($v(`<default>`,JSON.stringify(Fy),Iy),Fy);function Ry(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 zy(e){return typeof e==`string`?e:String(e)}function By(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 Vy(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")`)}const Hy=/^(?:(?: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,Uy=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function Wy(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(Hy);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(Uy);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 Gy(e){let t=e.match(Uy);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 Ky(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 qy(e){return e.toLocaleString()}const Jy=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],Yy=Jy.length;function Xy(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*(Yy-1));o+=Jy[t]}return o}function Zy(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}const Qy=xc(),$y=[...Tc];function eb(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>Ky(e),argTypes:[`string`]},int:{fn:e=>By(e),argTypes:[`value`]},string:{fn:e=>zy(e),argTypes:[`value`]},bool:{fn:e=>Vy(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>Qy,argTypes:[]},styles:{fn:()=>$y,argTypes:[]},sparkline:{fn:(e,t)=>Xy(Zy(e),t),argTypes:[`string`,`int`]}}}function tb(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>qy(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>Wy(e),argTypes:[`string`]},shortenModelName:{fn:e=>Gy(e),argTypes:[`string`]}}}function nb(e,t=()=>new Date){return of({fromString:e=>new Vo(e),toString:e=>e.plain,clock:t,missingKey:`error`,funcs:{...Xp(),...og(),...Im(),...ih(),...Hp(t),...Mf(),...um(),...gc(),...eb(),...tb(t),...e??{}}})}function rb(e){return ib(e,new Set(e.names()),``)}function ib(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.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return ib(e,t,a)}})}function ab(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function ob(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]}"`)}}async function sb(e){let t=await ye({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`});return t.ok?{stdout:t.stdout,exitCode:t.exitCode??0}:{stdout:t.stdout,exitCode:t.exitCode??1}}async function cb(e,t,n){let r;try{r=await ee(e,`utf8`)}catch{return{error:`file unreadable: ${e}`}}if(n!==void 0){let t=new RegExp(n).exec(r);return t?.[1]?{content:t[1].replace(/\n/g,` `)}:{error:`regex no-match in "${e}"`}}return t===`first-line`?{content:(r.split(`
105
- `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const lb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],ub=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],db=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],fb=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function pb(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>lb[e.getMonth()]],[`Monday`,e=>db[e.getDay()]],[`Jan`,e=>ub[e.getMonth()]],[`Mon`,e=>fb[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 mb={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function hb(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=mb[t];try{return yb(r,e)}catch{return bb(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Vn(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Vn(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Vn(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Vn(e.stashCount,0)}}var gb=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.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}},_b=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:E(()=>{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&&(re(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())re(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function vb(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function yb(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`?zy(e):t===`number`?By(e):Vy(e)}function bb(e){return e===`number`?0:e===`boolean`?!1:``}var xb=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new gb;ttlMgr=new _b;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=nb();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new _r({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Ry(t),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){let r=ab(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=rb(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return pb(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,pb(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=mb[t.field],r=t.varDefault===void 0?bb(n):yb(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe: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,hb(t,n,i,this.defaultEmptyValue))})})},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})}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(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=vb(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,yb(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`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.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 e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,X.reaction)(()=>{let t=rb(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,X.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await sb(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await cb(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,yb(this.defaultEmptyValue,t))}catch{this.store.setBox(e,bb(t))}}defaultFor(e){try{return yb(this.defaultEmptyValue,e)}catch{return bb(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})}};const Sb={unicode:{},ascii:{glyph:`>`}},Cb={unicode:{},ascii:{left:`(`,right:`)`}};function wb(e,t,n){switch(e){case`capsule`:return new Jo(Cb[t]);case`plain`:return new Yo(n===void 0?{}:{separator:n});case`powerline`:return new qo(Sb[t]);default:return e}}function Tb(e){switch(e){case`powerline`:return 1;case`capsule`:return 2;case`plain`:return 0;default:return e}}function Eb(e,t){if(e.length===0)return``;let n=wb(t.style,t.charset,t.separator);if(t.wrap&&Number.isFinite(t.width)){let r=Qo(new us([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
106
- `)?r.slice(0,-1):r}return Qo(new Ho([...e],n),{colorSystem:t.colorCompatibility})}const Db=new Map,Ob=new Map;function kb(e){let t=vc(e),n=Db.get(t);if(n!==void 0)return n;let r=io(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return Db.set(t,r),r}function Ab(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Ob.get(n);if(r!==void 0)return r;let i=_o(e,t);return Ob.set(n,i),i}function jb(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=Mb(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=Mb([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function Mb(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>Nb(e,t)):e,r=Vo.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function Nb(e,t){let n=e.copy();return n.style=t.add(e.style),n}function Pb(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function Fb(e,t){let n=Vo.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function Ib(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=Fb(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var Lb=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Rb(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=zb(r,a),c=s===void 0?void 0:Bb(n,s,`bg`);o.bg=c;let l=zb(i,a),u=l===void 0?void 0:Bb(n,l,`fg`);return new J({bgcolor:c===void 0?void 0:q.fromRgba(c),color:u===void 0?void 0:q.fromRgba(u)})}function zb(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Bb(e,t,n){try{return Ra(e,t)}catch(e){throw e instanceof Fa?new Lb(t,n,e.message):e}}const Vb=new Map([[`palette`,`theme.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function Hb(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,Ub(e,a,o,n,r));return i}function Ub(e,t,n,r,i){if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...wv(n.from,i)]}:`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=Vb.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...wv(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...wv(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:Wb(e,n.copy,t)}:`open`in n?{kind:`open`,target:Wb(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function Wb(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function Gb(e,t){return e.has(t)?zy(e.read(t)):``}function Kb(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function qb(e,t,n){let r=new Vo(e,{style:new J({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function Jb(e,t){return Math.max(e.members.indexOf(Gb(t,e.stateVar)),0)}function Yb(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=Gb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=Gb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=Gb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(Jb(e,r)+1)%e.members.length];return{effect:{verb:wt,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:Tt,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:Et,args:[Kb(e.text,rb(r))]},active:!1};case`open`:return{effect:{verb:Dt,args:[Kb(e.target,rb(r))]},active:!1};case`persist-literal`:{let t=Gb(r,e.stateVar);return{effect:{verb:At,args:[i,e.key,e.value]},active:t===e.value}}case`persist-option`:{let a=n??t,o=Gb(r,e.stateVar);return{effect:{verb:At,args:[i,e.key,a]},active:o===a}}case`persist-cycle`:{let t=e.members[(Jb(e,r)+1)%e.members.length];return{effect:{verb:At,args:[i,e.key,t]},active:!1}}case`persist-bounded`:return{effect:{verb:jt,args:[i,e.key,String(e.by)]},active:!1};case`reset`:return{effect:{verb:Mt,args:[i,e.key]},active:!1};case`undo`:return{effect:{verb:Pt,args:[i]},active:!1};case`redo`:return{effect:{verb:j,args:[i]},active:!1};case`layout-op`:return{effect:{verb:Nt,args:[i,e.key,kg(e.op)]},active:!1};case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effect:{verb:Nt,args:[i,e.key,kg(r)]},active:!1}}}}function Xb(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`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[Jb(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 Zb(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}=Xb(e,r,t,i),{effect:s,active:c}=Yb(r,a,o,i,Gb(i,`session.id`));return qb(a,It([s]),c)}function Qb(e){return{action:{fn:(t,...n)=>Zb(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function $b(e){return new Vo(e).cellLength}function ex(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 tx(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Vo(` `)),n.push(t);let r=Vo.fromFragments(n);return r.noWrap=t,r.end=``,r}function nx(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 rx(e,t){let n=e.compiled.get(t);if(!n||n.kind!==`set-option`&&n.kind!==`persist-option`&&n.kind!==`layout-op-option`)throw Error(`picker 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 ${n?`a ${n.kind} action`:`no such action`}`);return n}function ix(e,t,n,r,i,a){let o=rx(a,e),s=a.store,c=Gb(s,`session.id`),l=`stateVar`in o?Gb(s,o.stateVar):void 0,u=o.options.map($b),d=i?Math.max(1,By(s.read(`term.cols`))-Tb(a.stripStyle)-2*a.padding):1/0,f=$b(`✕`)+1,p=$b(`←`)+1+$b(`→`)+1,m=ex(u,d,f),h=m.length>1?ex(u,d,f+p):m,g=parseInt(Gb(s,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>It([{verb:wt,args:[c,t.key,String(e)]}]),b=n.flatMap(([e,t])=>[e,t]),x=It([{verb:wt,args:[c,...b]}]),S=r?[{verb:wt,args:[c,...b]}]:[],C=e=>{if(o.kind===`persist-option`)return It([{verb:At,args:[c,o.key,e]},...S]);if(o.kind===`layout-op-option`){let t=kg({op:`insert`,segment:e,anchor:o.anchor,relation:o.relation});return It([{verb:Nt,args:[c,o.key,t]},...S])}return It([{verb:wt,args:[c,o.key,e,...r?b:[]]}])},w=[qb(`✕`,x,!1)];_>0&&w.push(qb(`←`,y(_-1),!1));for(let e of v){let t=o.options[e];w.push(qb(t,C(t),t===l))}return _<h.length-1&&w.push(qb(`→`,y(_+1),!1)),tx(w,i)}function ax(e){return{picker:{fn:(t,n,r,i)=>{let a=nx(e,n,`set-int`,`an int action ({ set, int: true })`);return ix(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const ox=Symbol(`cc-candybar.menuDrop`);function sx(e){return e.flatMap(e=>e[ox]??[])}function cx(e,t,n){let r=n.activeSegment.current;if(r===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let i=n.action,a=ug(r.segName,e,t.key),o=fg(a),s=lg(e),c=Gb(i.store,a)===s,l=Gb(i.store,`session.id`),u=qb(c?`▾`:`▸`,It([{verb:wt,args:[l,a,c?zt:s,o,`0`]}]),!1);return u[ox]=c?[ix(e,{key:o,stateVar:o},[[a,zt],[o,`0`]],t.closeOnPick,t.paged,i)]:[],u}function lx(e){return{menu:{fn:(t,n)=>cx(t,pg(n??{}),e),argTypes:[`string`,`dict`],returnType:`T`}}}function ux(){return{current:null}}function dx(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 fx(e){let t={fn:(()=>{let t=dx(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:[],returnType:`string`};return{...hc(()=>dx(e,`color`).palette),bgOf:t}}function px(e){let t=[],n=[];for(let r of e){if(!r.contains(`
103
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:Z(e.source,[`layout`])}),t.root!==void 0&&(n.root=yu(e,`root`,t.root)),t.actions!==void 0&&(n.actions=B_(e,t.actions)),t.looks!==void 0&&(n.looks=Cv(e,t.looks)),t.presets!==void 0&&(n.presets=Tv(e,t.presets)),t.helpers!==void 0&&(n.helpers=Ev(e,t.helpers)),Au(e,n),Dg(e,n),Fg(e,n),ou(e,n,i_,`the global settings menu`),n}const ly=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`helpers`]),uy=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function dy(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 fy(e){let t=await py(e);return t.kind===`ok`?R(Math.floor((t.value+36e5)/1e3)):t}async function py(e){for(let t of[65536,1048576]){let n=await Or(e,t);if(n.kind!==`ok`)return n;let r=my(n.value.buf,n.value.fromStart);if(r!=null)return R(r);if(n.value.fromStart)return z}return z}function my(e,t){let n=e.toString(`utf8`).split(`
104
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!uy.test(t))continue;let r=dy(t);if(r!=null)return r}return null}const hy=10*1e3;function gy(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 _y(e,t){if(!(t<60))return e*3600/t}function vy(e,t,n,r){let i=r-t;if(i<50||i>hy)return;let a=n-e;if(!(a<=0))return a*1e3/i}function yy(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=vy(t.input,t.atMs,n.input,n.atMs),i=vy(t.output,t.atMs,n.output,n.atMs),a=vy(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 by(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>hy)continue;let o=vy(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function xy(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function Sy(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`,()=>xy(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function Cy(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,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}`,i);let n=[],r=new Set;for(let t of Zr(e.root)){if(t.when)for(let e of Fv(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of Fv(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of wy(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of Fv(e.template))n.push(t)}}}return i}function wy(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 Ty(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Ey(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 Dy(e,t,n,r,i,a){let o=e=>Ty(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Bn(`${e}: ${String(t)}`)):Promise.resolve(z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Ey(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>fy(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=Ay(l);_.push(...y.failures);let b=Sy(a);_.push(...b.failures);let x=v(u),S=v(d),C=v(f),w=v(p),ee=v(m),T=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let te=e.rate_limits?.five_hour,ne=e.rate_limits?.seven_day,re=te?gy(te.used_percentage,te.resets_at,18e6,s):void 0,E=ne?gy(ne.used_percentage,ne.resets_at,6048e5,s):void 0,D=x?.session.cost,ie=w?.sessionDuration,ae=o(`burn`)&&D!=null&&ie!=null?_y(D,ie):void 0,oe=v(g),se=oe===void 0?void 0:yy(oe),ce=oe===void 0?void 0:by(oe),le=se!==void 0||ce!==void 0?{...se,...ce!==void 0&&{history:ce}}:void 0,ue=ky(process.env.HOME??process.env.USERPROFILE),de=e.workspace?{...e.workspace,current_dir:ky(e.workspace.current_dir)??``,project_dir:ky(e.workspace.project_dir)??``}:e.workspace,fe=x===void 0?void 0:Oy({cost:x.session.cost,tokens:x.session.tokens}),O=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},pe=w===void 0?void 0:Oy({lastResponseTime:w.lastResponseTime,responseTime:w.responseTime,sessionDuration:w.sessionDuration,messageCount:w.messageCount,linesAdded:w.linesAdded,linesRemoved:w.linesRemoved});return{...e,...de!==void 0&&{workspace:de},...ue!==void 0&&{home:ue},...y.git!==void 0&&{git:y.git},...ee!==void 0&&{tmux:{session:ee}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...fe!==void 0&&{session:fe},...O!==void 0&&{today:O},...ae!==void 0&&{burn:{costPerHour:ae}},...le!==void 0&&{speed:le},...o(`block`)&&te!==void 0&&{block:{nativeUtilization:te.used_percentage,resetsAt:te.resets_at,...re!==void 0&&{etaMinutes:re}}},...ne!==void 0&&{weekly:{percentage:ne.used_percentage,resetsAt:ne.resets_at,...E!==void 0&&{etaMinutes:E}}},...T!==void 0&&{cache:{expiresAt:T}},...C!==void 0&&{context:{totalTokens:C.totalTokens,contextLeft:C.contextLeftPercentage}},...pe!==void 0&&{metrics:pe}}}function Oy(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 ky(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Ay(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const jy=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,My=`{{ \$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 (${jy}) (basename .project_dir) (ne (${jy}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,Ny={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},Py=(e,t)=>`{{ fg (color "${Ny[e]}") ${t} }}`,Fy=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,Iy=`{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} ({{ \$first := true }}{{ if gt .git.staged 0 }}${Py(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${Py(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${Py(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${Py(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,Ly=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${Py(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Py(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${Py(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+Iy+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${Py(`stash`,`(printf "⧇ %v" .git.stash)`)}{{ end }} {{ if eq .git.status "conflicts" }}{{ fg (color "error") "⚠" }}{{ else }}{{ if eq .git.status "dirty" }}{{ fg (color "warning") "●" }}{{ else }}{{ fg (color "success") "✓" }}{{ end }}{{ end }}`;function Ry(e,t){return`{{ if ge (round ${e}) ${t} }}error{{ else }}{{ if ge (round ${e}) 50 }}warning{{ else }}panel{{ end }}{{ end }}`}function zy(e){return`{{ if ge (round ${e}) 50 }}button-color-foreground{{ else }}foreground{{ end }}`}function By(e,t,n){return`{{ if lt ${e} 0 }}panel{{ else }}{{ if lt ${e} ${n} }}error{{ else }}{{ if lt ${e} ${t} }}warning{{ else }}panel{{ end }}{{ end }}{{ end }}`}function Vy(e,t){return`{{ if lt ${e} 0 }}foreground{{ else }}{{ if lt ${e} ${t} }}button-color-foreground{{ else }}foreground{{ end }}{{ end }}`}const Hy={globals:{palette:`tokyo-night`},variables:{current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},version:{kind:`input`,path:`version`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"style.effective":{kind:`input`,path:`style.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"hue.step":{kind:`literal`,value:14},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.repoUrl":{kind:`input`,path:`git.repoUrl`,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.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},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"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},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},activeStyle:{kind:`state`,key:`style`,default:``}},segments:{directory:{template:My,bg:`surface`,fg:`foreground`},model:{template:`✱ {{ formatModelName .model.display_name }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{template:`⌗{{ trunc 8 .session.id }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{template:`◈ v{{ .version }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{template:`tmux:{{ .tmux.session | default "none" }}`,bg:`surface-active`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{template:Ly,bg:`surface-active`,fg:Fy,when:`{{ ne .git.branch "" }}`},gitaculous:{template:`(git){{ if ne .git.repoName "" }} {{ .git.repoName }}{{ end }}{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} {{ if gt .git.staged 0 }}${Py(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${Py(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${Py(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${Py(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${Py(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Py(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${Py(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${Py(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,bg:`surface-active`,fg:Fy,when:`{{ ne .git.branch "" }}`},gitPr:{template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,bg:`surface-active`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,bg:`surface`,fg:`foreground`},session:{template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},today:{template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},block:{template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .block.resetsAt) }})`,bg:Ry(`.block.nativeUtilization`,`.block.budget.warningThreshold`),fg:zy(`.block.nativeUtilization`),when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .weekly.resetsAt) }})`,bg:Ry(`.weekly.percentage`,`.weekly.budget.warningThreshold`),fg:zy(`.weekly.percentage`),when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:By(`.block.etaMinutes`,`.burn.eta.warnMinutes`,`.burn.eta.errorMinutes`),fg:Vy(`.block.etaMinutes`,`.burn.eta.warnMinutes`),when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,bg:`panel`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{template:`⚡ {{ sparkline .speed.history 24 }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,bg:`surface`,fg:`{{ if le (minutesUntilReset .cache.expiresAt) 8 }}error{{ else }}{{ if le (minutesUntilReset .cache.expiresAt) 20 }}warning{{ else }}foreground{{ end }}{{ end }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ if le .context.contextLeft 20 }}error{{ else }}{{ if le .context.contextLeft 40 }}warning{{ else }}surface-active{{ end }}{{ end }}`,fg:`{{ if le .context.contextLeft 40 }}button-color-foreground{{ else }}foreground{{ end }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{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 }} `,bg:`panel`,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},styleControl:{template:`✦ {{ if .activeStyle }}{{ .activeStyle }}{{ else }}(default){{ end }} {{ menu "applyStyle" }} 📌{{ menu "applyStyleForever" (dict "key" "pickersForever") }} {{ action "resetStyle" "↺" }}`,bg:`surface`,fg:`foreground`},themeControl:{template:`🎨 {{ .theme.effective }} {{ menu "applyTheme" (dict "key" "pickers") }} 📌{{ menu "applyThemeForever" (dict "key" "pickersForever") }} {{ action "resetTheme" "↺" }}`,bg:`surface`,fg:`foreground`},lookControl:{template:`◐ {{ .look.effective }} {{ menu "applyLook" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyLookForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetLook" "↺" }}`,bg:`surface`,fg:`foreground`},presetControl:{template:`▦ {{ .preset.effective }} {{ menu "applyPreset" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyPresetForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetPreset" "↺" }}`,bg:`surface`,fg:`foreground`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" }} {{ action "resetCharset" "↺" }}`,bg:`surface`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" }} {{ action "resetColorCompat" "↺" }}`,bg:`surface`,fg:`foreground`},wrapToggleControl:{template:`{{ action "toggleWrapForever" "wrap: on" "wrap: off" }} {{ action "resetAutoWrap" "↺" }}`,bg:`surface`,fg:`foreground`},paddingControl:{template:`{{ action "paddingDownForever" "◀" }} padding {{ .padding.effective }} {{ action "paddingUpForever" "▶" }} {{ action "resetPadding" "↺" }}`,bg:`surface`,fg:`foreground`},directoryPaletteControl:{template:`🎨 directory {{ menu "applyDirectoryPaletteForever" }} {{ action "resetDirectoryPalette" "↺" }}`,bg:`surface`,fg:`foreground`}},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:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ settings`,direction:`horizontal`,children:[`themeControl`,`lookControl`,`presetControl`,`styleControl`,`charsetControl`,`colorCompatControl`,`wrapToggleControl`,`paddingControl`,`directoryPaletteControl`]}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}]},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyStyle:{set:`style`,from:`styles`},applyTheme:{set:`theme`,from:`themes`},applyLook:{set:`look`,from:`looks`},applyPreset:{set:`preset`,from:`presets`},applyThemeForever:{persist:`palette`,from:`themes`},resetTheme:{reset:`palette`},applyStyleForever:{persist:`style`,from:`styles`},resetStyle:{reset:`style`},applyLookForever:{persist:`look`,from:`looks`},resetLook:{reset:`look`},applyPresetForever:{persist:`preset`,from:`presets`},resetPreset:{reset:`preset`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},toggleWrapForever:{persist:`autoWrap`,cycle:[...jc]},resetAutoWrap:{reset:`autoWrap`},paddingDownForever:{persist:`padding`,...Mc,by:-1},paddingUpForever:{persist:`padding`,...Mc,by:1},resetPadding:{reset:`padding`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{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}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`},{kind:`segment`,name:`presetControl`}]},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:`segment`,name:`toolbar`},{kind:`segment`,name:`presetControl`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{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`}]}]}}},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,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 }}`}},Uy=new Set([Hy.globals.palette,...Object.values(Hy.segments).map(e=>e.palette)].filter(e=>e!==void 0)),Wy=ml(oy(`<default>`,JSON.stringify(Hy),Uy),Hy);function Gy(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 Ky(e){return typeof e==`string`?e:String(e)}function qy(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 Jy(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")`)}const Yy=/^(?:(?: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,Xy=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function Zy(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(Yy);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(Xy);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 Qy(e){let t=e.match(Xy);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 $y(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 eb(e){return e.toLocaleString()}const tb=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],nb=tb.length;function rb(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*(nb-1));o+=tb[t]}return o}function ib(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}const ab=Sc(),ob=[...Ec];function sb(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>$y(e),argTypes:[`string`]},int:{fn:e=>qy(e),argTypes:[`value`]},string:{fn:e=>Ky(e),argTypes:[`value`]},bool:{fn:e=>Jy(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>ab,argTypes:[]},styles:{fn:()=>ob,argTypes:[]},sparkline:{fn:(e,t)=>rb(ib(e),t),argTypes:[`string`,`int`]}}}function cb(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>eb(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>Zy(e),argTypes:[`string`]},shortenModelName:{fn:e=>Qy(e),argTypes:[`string`]}}}function lb(e,t=()=>new Date){return pf({fromString:e=>new Vo(e),toString:e=>e.plain,clock:t,missingKey:`error`,funcs:{...rm(),...pg(),...Um(),...dh(),...Yp(t),...zf(),..._m(),...gc(),...sb(),...cb(t),...e??{}}})}function ub(e){return db(e,new Set(e.names()),``)}function db(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.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return db(e,t,a)}})}function fb(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function pb(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]}"`)}}async function mb(e){let t=await ye({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`});return t.ok?{stdout:t.stdout,exitCode:t.exitCode??0}:{stdout:t.stdout,exitCode:t.exitCode??1}}async function hb(e,t,n){let r;try{r=await ee(e,`utf8`)}catch{return{error:`file unreadable: ${e}`}}if(n!==void 0){let t=new RegExp(n).exec(r);return t?.[1]?{content:t[1].replace(/\n/g,` `)}:{error:`regex no-match in "${e}"`}}return t===`first-line`?{content:(r.split(`
105
+ `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const gb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],_b=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],vb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],yb=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function bb(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>gb[e.getMonth()]],[`Monday`,e=>vb[e.getDay()]],[`Jan`,e=>_b[e.getMonth()]],[`Mon`,e=>yb[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 xb={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Sb(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=xb[t];try{return Eb(r,e)}catch{return Db(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Vn(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Vn(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Vn(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Vn(e.stashCount,0)}}var Cb=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.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}},wb=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:E(()=>{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&&(re(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())re(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Tb(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Eb(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`?Ky(e):t===`number`?qy(e):Jy(e)}function Db(e){return e===`number`?0:e===`boolean`?!1:``}var Ob=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new Cb;ttlMgr=new wb;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=lb();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new _r({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Gy(t),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){let r=fb(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=ub(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return bb(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,bb(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=xb[t.field],r=t.varDefault===void 0?Db(n):Eb(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe: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,Sb(t,n,i,this.defaultEmptyValue))})})},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})}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(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Tb(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Eb(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`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.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 e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,X.reaction)(()=>{let t=ub(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,X.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await mb(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await hb(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,Eb(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Db(t))}}defaultFor(e){try{return Eb(this.defaultEmptyValue,e)}catch{return Db(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})}};const kb={unicode:{},ascii:{glyph:`>`}},Ab={unicode:{},ascii:{left:`(`,right:`)`}};function jb(e,t,n){switch(e){case`capsule`:return new Jo(Ab[t]);case`plain`:return new Yo(n===void 0?{}:{separator:n});case`powerline`:return new qo(kb[t]);default:return e}}function Mb(e){switch(e){case`powerline`:return 1;case`capsule`:return 2;case`plain`:return 0;default:return e}}function Nb(e,t){if(e.length===0)return``;let n=jb(t.style,t.charset,t.separator);if(t.wrap&&Number.isFinite(t.width)){let r=Qo(new us([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
106
+ `)?r.slice(0,-1):r}return Qo(new Ho([...e],n),{colorSystem:t.colorCompatibility})}const Pb=new Map,Fb=new Map;function Ib(e){let t=vc(e),n=Pb.get(t);if(n!==void 0)return n;let r=io(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return Pb.set(t,r),r}function Lb(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Fb.get(n);if(r!==void 0)return r;let i=_o(e,t);return Fb.set(n,i),i}function Rb(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=zb(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=zb([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function zb(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>Bb(e,t)):e,r=Vo.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function Bb(e,t){let n=e.copy();return n.style=t.add(e.style),n}function Vb(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function Hb(e,t){let n=Vo.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function Ub(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=Hb(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var Wb=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Gb(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=Kb(r,a),c=s===void 0?void 0:qb(n,s,`bg`);o.bg=c;let l=Kb(i,a),u=l===void 0?void 0:qb(n,l,`fg`);return new J({bgcolor:c===void 0?void 0:q.fromRgba(c),color:u===void 0?void 0:q.fromRgba(u)})}function Kb(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function qb(e,t,n){try{return Ra(e,t)}catch(e){throw e instanceof Fa?new Wb(t,n,e.message):e}}const Jb=new Map([[`palette`,`theme.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function Yb(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,Xb(e,a,o,n,r));return i}function Xb(e,t,n,r,i){if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...jv(n.from,i)]}:`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=Jb.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...jv(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...jv(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:Zb(e,n.copy,t)}:`open`in n?{kind:`open`,target:Zb(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function Zb(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function Qb(e,t){return e.has(t)?Ky(e.read(t)):``}function $b(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function ex(e,t,n){let r=new Vo(e,{style:new J({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function tx(e,t){return Math.max(e.members.indexOf(Qb(t,e.stateVar)),0)}function nx(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=Qb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=Qb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=Qb(r,e.stateVar);return{effect:{verb:wt,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(tx(e,r)+1)%e.members.length];return{effect:{verb:wt,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:Tt,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:Et,args:[$b(e.text,ub(r))]},active:!1};case`open`:return{effect:{verb:Dt,args:[$b(e.target,ub(r))]},active:!1};case`persist-literal`:{let t=Qb(r,e.stateVar);return{effect:{verb:At,args:[i,e.key,e.value]},active:t===e.value}}case`persist-option`:{let a=n??t,o=Qb(r,e.stateVar);return{effect:{verb:At,args:[i,e.key,a]},active:o===a}}case`persist-cycle`:{let t=e.members[(tx(e,r)+1)%e.members.length];return{effect:{verb:At,args:[i,e.key,t]},active:!1}}case`persist-bounded`:return{effect:{verb:jt,args:[i,e.key,String(e.by)]},active:!1};case`reset`:return{effect:{verb:Mt,args:[i,e.key]},active:!1};case`undo`:return{effect:{verb:Pt,args:[i]},active:!1};case`redo`:return{effect:{verb:j,args:[i]},active:!1};case`layout-op`:return{effect:{verb:Nt,args:[i,e.key,Ig(e.op)]},active:!1};case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effect:{verb:Nt,args:[i,e.key,Ig(r)]},active:!1}}}}function rx(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`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[tx(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 ix(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}=rx(e,r,t,i),{effect:s,active:c}=nx(r,a,o,i,Qb(i,`session.id`));return ex(a,It([s]),c)}function ax(e){return{action:{fn:(t,...n)=>ix(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function ox(e){return new Vo(e).cellLength}function sx(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 cx(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Vo(` `)),n.push(t);let r=Vo.fromFragments(n);return r.noWrap=t,r.end=``,r}function lx(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 ux(e,t){let n=e.compiled.get(t);if(!n||n.kind!==`set-option`&&n.kind!==`persist-option`&&n.kind!==`layout-op-option`)throw Error(`picker 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 ${n?`a ${n.kind} action`:`no such action`}`);return n}function dx(e,t,n,r,i,a){let o=ux(a,e),s=a.store,c=Qb(s,`session.id`),l=`stateVar`in o?Qb(s,o.stateVar):void 0,u=o.options.map(ox),d=i?Math.max(1,qy(s.read(`term.cols`))-Mb(a.stripStyle)-2*a.padding):1/0,f=ox(`✕`)+1,p=ox(`←`)+1+ox(`→`)+1,m=sx(u,d,f),h=m.length>1?sx(u,d,f+p):m,g=parseInt(Qb(s,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>It([{verb:wt,args:[c,t.key,String(e)]}]),b=n.flatMap(([e,t])=>[e,t]),x=It([{verb:wt,args:[c,...b]}]),S=r?[{verb:wt,args:[c,...b]}]:[],C=e=>{if(o.kind===`persist-option`)return It([{verb:At,args:[c,o.key,e]},...S]);if(o.kind===`layout-op-option`){let t=Ig({op:`insert`,segment:e,anchor:o.anchor,relation:o.relation});return It([{verb:Nt,args:[c,o.key,t]},...S])}return It([{verb:wt,args:[c,o.key,e,...r?b:[]]}])},w=[ex(`✕`,x,!1)];_>0&&w.push(ex(`←`,y(_-1),!1));for(let e of v){let t=o.options[e];w.push(ex(t,C(t),t===l))}return _<h.length-1&&w.push(ex(`→`,y(_+1),!1)),cx(w,i)}function fx(e){return{picker:{fn:(t,n,r,i)=>{let a=lx(e,n,`set-int`,`an int action ({ set, int: true })`);return dx(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const px=Symbol(`cc-candybar.menuDrop`);function mx(e){return e.flatMap(e=>e[px]??[])}function hx(e,t,n){let r=n.activeSegment.current;if(r===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let i=n.action,a=_g(r.segName,e,t.key),o=yg(a),s=gg(e),c=Qb(i.store,a)===s,l=Qb(i.store,`session.id`),u=ex(c?`▾`:`▸`,It([{verb:wt,args:[l,a,c?zt:s,o,`0`]}]),!1);return u[px]=c?[dx(e,{key:o,stateVar:o},[[a,zt],[o,`0`]],t.closeOnPick,t.paged,i)]:[],u}function gx(e){return{menu:{fn:(t,n)=>hx(t,bg(n??{}),e),argTypes:[`string`,`dict`],returnType:`T`}}}function _x(){return{current:null}}function vx(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 yx(e){let t={fn:(()=>{let t=vx(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:[],returnType:`string`};return{...hc(()=>vx(e,`color`).palette),bgOf:t}}function bx(e){let t=[],n=[];for(let r of e){if(!r.contains(`
107
107
  `)){n.push(r);continue}let e=r.split(`
108
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function mx(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const hx={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return mx(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name}},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,a=t.nextHueShift();if(!t.visible)return[];try{if(!Pb(i.when,t.scope))return[];let n=i.palette===void 0?t.look:Ea,o=Ab(i.palette??t.basePalette,{...n,hueShift:n.hueShift+a}),s=t.enterSegment(e.name,o,i.bg,i.fg),c=i.template.evaluate(t.scope),l=t.exitSegment(c),u=l.length>0?t.focusTint(s):s,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=px(jb(c,u)).map(e=>Ib(e,d)),p=l.map(e=>Ib(jb([e],u),d)),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),m}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new Vo(`⚠ ${e.name}: ${r}`)]]}}}};function gx(e){return hx[e]}function _x(e){if(`ttl`in e)return{kind:`ttl`,durationMs:ob(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 vx(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);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,regex:n.regex,cache:_x(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:_x(n.cache),varDefault:n.default});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?ob(n.cache.ttl):void 0,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 yx(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=`{{ define "${r}" }}${i}{{ end }}`;try{e.parse(t)}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}n+=t}return n}function bx(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=ux(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=Rg(e.presets),l=new Map([...Sv(e),...b_(e)]),u=nb({...Qb(i),...ax(i),...lx(o),...fx(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=yx(u,e.helpers),f=e=>u.parse(d+e),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.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`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=Hb(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{vx(t,n,i,r)}catch(e){m.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{vx(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[t]={when:n.when===void 0?void 0:e(n.when,`when`),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`),palette:n.palette===void 0?void 0:kb(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),compileChild:_};return gx(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=Vg(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function xx(e){let t=e.bgcolor;return t===void 0?e:new J({bgcolor:q.fromRgba(Ga(t.getTruecolor(),1)),color:e.color})}function Sx(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=Ea,preset:f=Ig}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=rb(n),m=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,h=Number.isFinite(m)?m:0;l?.clear();let g={value:0},_=()=>{let e=g.value*h;return g.value+=1,e},v=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},y=(e,n,r,i)=>Rb(t.activeSegment,e,n,r,i,p),b=e=>(t.activeSegment.current=null,sx(e)),x=(e,t)=>{let n={scope:p,basePalette:a,look:d,visible:t&&Pb(e.when,p),padding:o.padding,nextHueShift:_,perSegmentSink:l,onSegmentError:u,enterSegment:y,exitSegment:b,focusTint:xx,lookupSegment:v,renderChild:x};return gx(e.kind).render(e,n)},S=t.roots.get(f);if(S===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Ig}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return x(S,!0).map(e=>Eb(e,o)).join(`
109
- `)}const Cx=/^-?\d+$/;function wx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Tx(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 Ex(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Cx.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 Dx(e,t,n){return r=>r?Cx.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 Ox(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=>!Cx.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,seed:wx(r[0].seed,t,i)}}return{kind:`int`}}function kx(e){return e===`config`?`set-config`:`set-state`}function Ax(e,t,n){return t.kind===`int`?Ex(`menu page "${e}"`):t.kind===`range`?Dx(t.min,t.max,`${n} stepper "${e}"`):Tx(t.allowed,`${n} "${e}"`,kx(n))}function jx(e,t,n){return Ax(e,Ox(e,t,n),n)}function Mx(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:Ox(e,n,t)}))}function Nx(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=jx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:jx(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=jx(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=Ox(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Px=xc(),Fx=new Set(Px),Ix=new Set(Tc),Lx=e=>e?Fx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Px.join(`, `)})`}:{ok:!1,reason:`theme name is required`},Rx=e=>e?Ix.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Tc.join(`, `)})`}:{ok:!1,reason:`style name is required`},zx=new Set([`1`,`true`]),Bx=new Set([`0`,`false`]),Vx=Nx({style:Rx,theme:Lx,"toolbar-expanded":e=>zx.has(e)?{ok:!0,value:`1`}:Bx.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function Hx(){return Vx.listKeys()}function Ux(e,t){return Vx.register(e,t)}function Wx(e,t){return Vx.validate(e,t)}function Gx(e){return Vx.rangeParamsFor(e)}function Kx(e,t,n){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:wv(e.from,n)}}]:`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,seed:wx(t.get(e.set),e.min,e.max)}}]:[]}function qx(e){let t=new Set(Vx.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function Jx(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}return t}function Yx(e){let t=Jx(e),n=Sv(e);return qx(Object.values(e.actions).flatMap(e=>Kx(e,t,n)))}function Xx(e){return Mx(Yx(e))}const Zx=(e,t)=>O(t),Qx={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,colorCompatibility:`string`},$x=new Set([`1`,`true`]),eS=new Set([`0`,`false`,``]);function tS(e,t){let n=Xg(e);if(n===null)throw Error(`coercePersistValue: "${e}" is not a valid persist target`);if(n.scope===`segment-palette`||n.scope===`preset-root-ops`)return t;let r=Qx[n.field];if(r===`string`)return t;if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`coercePersistValue: "${e}" expects a number, got "${t}"`);return n}if($x.has(t))return!0;if(eS.has(t))return!1;throw Error(`coercePersistValue: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function nS(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[t,n]of Object.entries(e)){let e=Xg(t);if(e===null)return!1;let r=e.scope===`globals`?Qx[e.field]:`string`;if(r===`number`&&typeof n!=`number`||r===`boolean`&&typeof n!=`boolean`||r===`string`&&typeof n!=`string`)return!1}return!0}function rS(e,t){let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);return nS(e)?e:(t(`warn`,`config-overrides load: unexpected shape, starting empty`),{})}catch{return t(`warn`,`config-overrides load: corrupt JSON, starting empty`),{}}}function iS(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))vl(n)&&(t[n]=r);return t}function aS(e){let t=Object.create(null);for(let[n,r]of Object.entries(e)){let e=Xg(n);e?.scope===`segment-palette`&&typeof r==`string`&&(t[e.segment]=r)}return t}function oS(e,t){let n=Object.create(null);for(let[r,i]of Object.entries(e)){let e=Xg(r);if(!(e?.scope!==`preset-root-ops`||typeof i!=`string`)){try{let t=JSON.parse(i);if(Array.isArray(t)&&t.every(e=>typeof e==`string`)){n[e.preset]=t;continue}}catch{}t(`warn`,`config-overrides: "${r}" is not a valid op-token list, dropping`)}}return n}function sS(e,t=Zx){return iS(rS(e,t))}function cS(e,t=Zx){let n=rS(e,t);return{globals:iS(n),segmentPalette:aS(n),presetRootOps:oS(n,t)}}function lS(e,t,n,i){try{r.mkdirSync(c.dirname(e),{recursive:!0});let t=`${e}.tmp`;r.writeFileSync(t,JSON.stringify(n),{mode:384}),r.chmodSync(t,384),r.renameSync(t,e)}catch(e){let n=`${t} write failed: ${e.message}`;throw i(`error`,n),Error(n)}}function uS(e,t,n){lS(e,`config-overrides`,t,n)}function dS(e,t,n,r){let i=rS(e,r),a=i[t];if(n===void 0){if(!(t in i))return a;let n={...i};delete n[t],uS(e,n,r)}else uS(e,{...i,[t]:n},r);return a}function fS(e,t,n,r=Zx){CS(e,{key:t,from:dS(e,t,n,r)??null,to:n},r)}function pS(e,t,n=Zx){t in rS(e,n)&&CS(e,{key:t,from:dS(e,t,void 0,n)??null,to:null},n)}function mS(e,t,n,r){dS(e,t,n===null?void 0:n,r)}const hS={past:[],future:[]};function gS(e){return c.join(c.dirname(e),`config-overrides-history.json`)}function _S(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function vS(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.key==`string`&&_S(t.from)&&_S(t.to)}function yS(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.past)&&t.past.every(vS)&&Array.isArray(t.future)&&t.future.every(vS)}function bS(e,t){let n=gS(e),i;try{i=r.readFileSync(n,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides-history read failed (${n}); starting empty`),hS}try{let e=JSON.parse(i);return yS(e)?e:(t(`warn`,`config-overrides-history load: unexpected shape, starting empty`),hS)}catch{return t(`warn`,`config-overrides-history load: corrupt JSON, starting empty`),hS}}function xS(e,t,n){lS(gS(e),`config-overrides-history`,t,n)}function SS(e,t,n){let r=[...e,t];return r.length>n?r.slice(r.length-n):r}function CS(e,t,n){xS(e,{past:SS(bS(e,n).past,t,50),future:[]},n)}function wS(e,t=Zx){let n=bS(e,t),r=n.past[n.past.length-1];return r===void 0?null:(mS(e,r.key,r.from,t),xS(e,{past:n.past.slice(0,-1),future:SS(n.future,r,50)},t),r)}function TS(e,t=Zx){let n=bS(e,t),r=n.future[n.future.length-1];return r===void 0?null:(mS(e,r.key,r.to,t),xS(e,{past:SS(n.past,r,50),future:n.future.slice(0,-1)},t),r)}const ES=Nx({},`config`);function DS(){return ES.listKeys()}function OS(e,t){return ES.validate(e,t)}function kS(e){return ES.rangeParamsFor(e)}function AS(e,t,n){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:wv(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[kg({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[kg({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:wv(e.insertSegmentFrom,n).map(t=>kg({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:wx(t.get(e.persist),e.min,e.max)}}]:[]}function jS(e){let t=new Map;for(let[n,r]of Object.entries(e.globals))vl(n)&&typeof r==`number`&&t.set(n,r);return t}function MS(e){let t=new Set;for(let n of Object.values(e.actions)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=Xg(e);r?.scope===`preset-root-ops`&&t.add(r.preset)}return[...t].map(e=>({key:Yg(e),spec:{kind:`allow-list`,allowed:[]}}))}function NS(e){let t=jS(e),n=new Map([...Sv(e),...b_(e)]);return[...MS(e),...Object.values(e.actions).flatMap(e=>AS(e,t,n))]}function PS(e){return Mx(NS(e),`config`)}function FS(e,t){return ES.register(e,t)}var IS=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,RS(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){RS(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},LS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,X.computed)(()=>{let e=n();return RS(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function RS(e,t,n,r){let i=Ry(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var zS=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new IS(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new LS(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function BS(e,t,n){return e+`\0`+t+`\0`+(n??``)}var VS=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=BS(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=Yv(e.projectDir,e.cwd,e.configFile);e.lastWarning=Xv(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof Ac||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
108
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function xx(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const Sx={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return xx(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name}},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,a=t.nextHueShift();if(!t.visible)return[];try{if(!Vb(i.when,t.scope))return[];let n=i.palette===void 0?t.look:Ea,o=Lb(i.palette??t.basePalette,{...n,hueShift:n.hueShift+a}),s=t.enterSegment(e.name,o,i.bg,i.fg),c=i.template.evaluate(t.scope),l=t.exitSegment(c),u=l.length>0?t.focusTint(s):s,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=bx(Rb(c,u)).map(e=>Ub(e,d)),p=l.map(e=>Ub(Rb([e],u),d)),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),m}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new Vo(`⚠ ${e.name}: ${r}`)]]}}}};function Cx(e){return Sx[e]}function wx(e){if(`ttl`in e)return{kind:`ttl`,durationMs:pb(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 Tx(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);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,regex:n.regex,cache:wx(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:wx(n.cache),varDefault:n.default});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?pb(n.cache.ttl):void 0,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 Ex(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=`{{ define "${r}" }}${i}{{ end }}`;try{e.parse(t)}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}n+=t}return n}function Dx(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=_x(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=Gg(e.presets),l=new Map([...kv(e),...D_(e)]),u=lb({...ax(i),...fx(i),...gx(o),...yx(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=Ex(u,e.helpers),f=e=>u.parse(d+e),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.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`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=Yb(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{Tx(t,n,i,r)}catch(e){m.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{Tx(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[t]={when:n.when===void 0?void 0:e(n.when,`when`),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`),palette:n.palette===void 0?void 0:Ib(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),compileChild:_};return Cx(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=Jg(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function Ox(e){let t=e.bgcolor;return t===void 0?e:new J({bgcolor:q.fromRgba(Ga(t.getTruecolor(),1)),color:e.color})}function kx(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=Ea,preset:f=Ug}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=ub(n),m=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,h=Number.isFinite(m)?m:0;l?.clear();let g={value:0},_=()=>{let e=g.value*h;return g.value+=1,e},v=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},y=(e,n,r,i)=>Gb(t.activeSegment,e,n,r,i,p),b=e=>(t.activeSegment.current=null,mx(e)),x=(e,t)=>{let n={scope:p,basePalette:a,look:d,visible:t&&Vb(e.when,p),padding:o.padding,nextHueShift:_,perSegmentSink:l,onSegmentError:u,enterSegment:y,exitSegment:b,focusTint:Ox,lookupSegment:v,renderChild:x};return Cx(e.kind).render(e,n)},S=t.roots.get(f);if(S===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Ug}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return x(S,!0).map(e=>Nb(e,o)).join(`
109
+ `)}const Ax=/^-?\d+$/;function jx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Mx(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 Nx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Ax.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 Px(e,t,n){return r=>r?Ax.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 Fx(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=>!Ax.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,seed:jx(r[0].seed,t,i)}}return{kind:`int`}}function Ix(e){return e===`config`?`set-config`:`set-state`}function Lx(e,t,n){return t.kind===`int`?Nx(`menu page "${e}"`):t.kind===`range`?Px(t.min,t.max,`${n} stepper "${e}"`):Mx(t.allowed,`${n} "${e}"`,Ix(n))}function Rx(e,t,n){return Lx(e,Fx(e,t,n),n)}function zx(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:Fx(e,n,t)}))}function Bx(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=Rx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Rx(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=Rx(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=Fx(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Vx=Sc(),Hx=new Set(Vx),Ux=new Set(Ec),Wx=e=>e?Hx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Vx.join(`, `)})`}:{ok:!1,reason:`theme name is required`},Gx=e=>e?Ux.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Ec.join(`, `)})`}:{ok:!1,reason:`style name is required`},Kx=new Set([`1`,`true`]),qx=new Set([`0`,`false`]),Jx=Bx({style:Gx,theme:Wx,"toolbar-expanded":e=>Kx.has(e)?{ok:!0,value:`1`}:qx.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function Yx(){return Jx.listKeys()}function Xx(e,t){return Jx.register(e,t)}function Zx(e,t){return Jx.validate(e,t)}function Qx(e){return Jx.rangeParamsFor(e)}function $x(e,t,n){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:jv(e.from,n)}}]:`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,seed:jx(t.get(e.set),e.min,e.max)}}]:[]}function eS(e){let t=new Set(Jx.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function tS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}return t}function nS(e){let t=tS(e),n=kv(e);return eS(Object.values(e.actions).flatMap(e=>$x(e,t,n)))}function rS(e){return zx(nS(e))}const iS=(e,t)=>O(t),aS={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,colorCompatibility:`string`},oS=new Set([`1`,`true`]),sS=new Set([`0`,`false`,``]);function cS(e,t){let n=r_(e);if(n===null)throw Error(`coercePersistValue: "${e}" is not a valid persist target`);if(n.scope===`segment-palette`||n.scope===`preset-root-ops`)return t;let r=aS[n.field];if(r===`string`)return t;if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`coercePersistValue: "${e}" expects a number, got "${t}"`);return n}if(oS.has(t))return!0;if(sS.has(t))return!1;throw Error(`coercePersistValue: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function lS(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[t,n]of Object.entries(e)){let e=r_(t);if(e===null)return!1;let r=e.scope===`globals`?aS[e.field]:`string`;if(r===`number`&&typeof n!=`number`||r===`boolean`&&typeof n!=`boolean`||r===`string`&&typeof n!=`string`)return!1}return!0}function uS(e,t){let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);return lS(e)?e:(t(`warn`,`config-overrides load: unexpected shape, starting empty`),{})}catch{return t(`warn`,`config-overrides load: corrupt JSON, starting empty`),{}}}function dS(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))Tl(n)&&(t[n]=r);return t}function fS(e){let t=Object.create(null);for(let[n,r]of Object.entries(e)){let e=r_(n);e?.scope===`segment-palette`&&typeof r==`string`&&(t[e.segment]=r)}return t}function pS(e,t){let n=Object.create(null);for(let[r,i]of Object.entries(e)){let e=r_(r);if(!(e?.scope!==`preset-root-ops`||typeof i!=`string`)){try{let t=JSON.parse(i);if(Array.isArray(t)&&t.every(e=>typeof e==`string`)){n[e.preset]=t;continue}}catch{}t(`warn`,`config-overrides: "${r}" is not a valid op-token list, dropping`)}}return n}function mS(e,t=iS){return dS(uS(e,t))}function hS(e,t=iS){let n=uS(e,t);return{globals:dS(n),segmentPalette:fS(n),presetRootOps:pS(n,t)}}function gS(e,t,n,i){try{r.mkdirSync(c.dirname(e),{recursive:!0});let t=`${e}.tmp`;r.writeFileSync(t,JSON.stringify(n),{mode:384}),r.chmodSync(t,384),r.renameSync(t,e)}catch(e){let n=`${t} write failed: ${e.message}`;throw i(`error`,n),Error(n)}}function _S(e,t,n){gS(e,`config-overrides`,t,n)}function vS(e,t,n,r){let i=uS(e,r),a=i[t];if(n===void 0){if(!(t in i))return a;let n={...i};delete n[t],_S(e,n,r)}else _S(e,{...i,[t]:n},r);return a}function yS(e,t,n,r=iS){AS(e,{key:t,from:vS(e,t,n,r)??null,to:n},r)}function bS(e,t,n=iS){t in uS(e,n)&&AS(e,{key:t,from:vS(e,t,void 0,n)??null,to:null},n)}function xS(e,t,n,r){vS(e,t,n===null?void 0:n,r)}const SS={past:[],future:[]};function CS(e){return c.join(c.dirname(e),`config-overrides-history.json`)}function wS(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function TS(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.key==`string`&&wS(t.from)&&wS(t.to)}function ES(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.past)&&t.past.every(TS)&&Array.isArray(t.future)&&t.future.every(TS)}function DS(e,t){let n=CS(e),i;try{i=r.readFileSync(n,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides-history read failed (${n}); starting empty`),SS}try{let e=JSON.parse(i);return ES(e)?e:(t(`warn`,`config-overrides-history load: unexpected shape, starting empty`),SS)}catch{return t(`warn`,`config-overrides-history load: corrupt JSON, starting empty`),SS}}function OS(e,t,n){gS(CS(e),`config-overrides-history`,t,n)}function kS(e,t,n){let r=[...e,t];return r.length>n?r.slice(r.length-n):r}function AS(e,t,n){OS(e,{past:kS(DS(e,n).past,t,50),future:[]},n)}function jS(e,t=iS){let n=DS(e,t),r=n.past[n.past.length-1];return r===void 0?null:(xS(e,r.key,r.from,t),OS(e,{past:n.past.slice(0,-1),future:kS(n.future,r,50)},t),r)}function MS(e,t=iS){let n=DS(e,t),r=n.future[n.future.length-1];return r===void 0?null:(xS(e,r.key,r.to,t),OS(e,{past:kS(n.past,r,50),future:n.future.slice(0,-1)},t),r)}const NS=Bx({},`config`);function PS(){return NS.listKeys()}function FS(e,t){return NS.validate(e,t)}function IS(e){return NS.rangeParamsFor(e)}function LS(e,t,n){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:jv(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Ig({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Ig({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:jv(e.insertSegmentFrom,n).map(t=>Ig({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:jx(t.get(e.persist),e.min,e.max)}}]:[]}function RS(e){let t=new Map;for(let[n,r]of Object.entries(e.globals))Tl(n)&&typeof r==`number`&&t.set(n,r);return t}function zS(e){let t=new Set;for(let n of Object.values(e.actions)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=r_(e);r?.scope===`preset-root-ops`&&t.add(r.preset)}return[...t].map(e=>({key:n_(e),spec:{kind:`allow-list`,allowed:[]}}))}function BS(e){let t=RS(e),n=new Map([...kv(e),...D_(e)]);return[...zS(e),...Object.values(e.actions).flatMap(e=>LS(e,t,n))]}function VS(e){return zx(BS(e),`config`)}function HS(e,t){return NS.register(e,t)}var US=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,GS(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){GS(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},WS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,X.computed)(()=>{let e=n();return GS(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function GS(e,t,n,r){let i=Gy(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var KS=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new US(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new WS(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function qS(e,t,n){return e+`\0`+t+`\0`+(n??``)}var JS=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=qS(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=ny(e.projectDir,e.cwd,e.configFile);e.lastWarning=ry(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof Lc||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
110
110
  `);e.lastWarning=e.lastWarning?e.lastWarning+`
111
- `+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=Zv(t,Ly),i=cS(Me(),L),a=cl(sl({globals:Ug(i.globals,n.presets)},n),i.segmentPalette),o=Wg(i.presetRootOps,n.presets),s=Qv(Kg(a,o),t??`<default>`,r),c=new zS,l=new xb(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=bx(s,l,{cwd:e.cwd});for(let{key:e,spec:t}of Xx(s))d.push(Ux(e,t));for(let{key:e,spec:t}of PS(s))d.push(FS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:gy(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,presetRootOps:o}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let n=[...Jv(e.projectDir,e.cwd,e.configFile),Me()],i=new Map;for(let e of n){let t=c.dirname(e);if(!r.existsSync(t))continue;let n=c.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(n)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),o=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(o,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){L(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const HS=16384;var US=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<HS){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%HS}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: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},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const WS=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function GS(e){let t=e.rssLimitBytes??WS,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=c.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),KS(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function KS(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function qS(e,t,n={}){let i=Ee();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:L,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>D.writeHeapSnapshot(e),listSnapshots:()=>{try{return r.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}const JS={load:()=>({}),save:()=>{},flush:()=>{}};function YS(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var XS=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=JS,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=YS(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,X.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,X.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const ZS=(e,t)=>O(t);function QS(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 $S=class{timer=null;pending=null;constructor(e,t=500,n=ZS){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 QS(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(c.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}`)}}},$=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function eC(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function tC(e){return nC(()=>decodeURIComponent(e))}function nC(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function rC(e,t){let n=be({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 iC=(e,t)=>rC(tC(e),t),aC=(e,t)=>{let n=be({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,tC(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`})`)}},oC=(e,t)=>rC(tC(e),t),sC=(e,t)=>rC(tC(e),t),cC=(e,t)=>{let n=eC(tC(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},lC=(e,t)=>{let[n=``,...r]=nC(()=>M(e)),i=eC(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${Hx().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: ${Hx().join(`, `)})`);let a=[];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=Wx(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},uC=/^-?\d+$/;function dC(e,t,n){return e>n?t:e<t?n:e}const fC=(e,t)=>{let[n=``,r=``,i=``]=nC(()=>M(e)),a=eC(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!uC.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=Gx(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${Hx().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&uC.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=dC(l+o,s.min,s.max),d=Wx(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)};function pC(e){if(!vl(e))throw Error(`step-config: "${e}" validated as a bounded config-writable key but is not a Globals field — registration/loader invariant broken`)}const mC=(e,t)=>{let[n=``,r=``,i=``]=nC(()=>M(e)),a=eC(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${DS().join(`, `)})`);let o=OS(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=tS(r,o.value);fS(Me(),r,s,t.dlog),t.dlog(`info`,`set-config: ${r}=${o.value} (session=${a})`)},hC=(e,t)=>{let[n=``,r=``,i=``]=nC(()=>M(e)),a=eC(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!uC.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=kS(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${DS().join(`, `)})`);pC(r);let c=sS(Me(),t.dlog)[r],l=typeof c==`number`?Math.max(s.min,Math.min(s.max,c)):s.seed,u=dC(l+o,s.min,s.max),d=OS(r,String(u));if(!d.ok)throw new $(`step-config: ${d.reason}`);let f=tS(r,d.value);fS(Me(),r,f,t.dlog),t.dlog(`info`,`step-config: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},gC=(e,t)=>{let[n=``,r=``]=nC(()=>M(e)),i=eC(n);if(!r||!DS().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${DS().join(`, `)})`);pS(Me(),r,t.dlog),t.dlog(`info`,`reset-config: ${r} (session=${i})`)},_C=(e,t)=>{let[n=``,r=``,i=``]=nC(()=>M(e)),a=eC(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${DS().join(`, `)})`);let o=OS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Xg(r);if(s===null||s.scope!==`preset-root-ops`)throw new $(`apply-layout-op: "${r}" is not a "presets.<name>.rootOps" target`);let c=cS(Me(),t.dlog).presetRootOps[s.preset]??[],l=JSON.stringify([...c,o.value]);fS(Me(),r,l,t.dlog),t.dlog(`info`,`apply-layout-op: ${r} += ${o.value} (session=${a})`)},vC=(e,t)=>{let[n=``]=nC(()=>M(e)),r=eC(n),i=wS(Me(),t.dlog);if(i===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i.key} (session=${r})`)},yC=(e,t)=>{let[n=``]=nC(()=>M(e)),r=eC(n),i=TS(Me(),t.dlog);if(i===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i.key} (session=${r})`)},bC=`config-override`,xC=new Map([[Et,iC],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=eC(nC(()=>decodeURIComponent(e.slice(0,n)))),i=nC(()=>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,bC),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,bC,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Dt,aC],[wt,lC],[Tt,fC],[At,mC],[jt,hC],[Mt,gC],[Nt,_C],[Pt,vC],[j,yC],[Ot,oC],[kt,sC],[`toolbar-toggle`,cC]]),SC=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Lt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`set-config`||a===`step-config`||a===`reset-config`||a===`apply-layout-op`||a===`undo`||a===`redo`||a===`toolbar-toggle`)){let e=M(o);e.length>0&&e[0]&&(i=e[0])}let e=xC.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(`
112
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},CC=new Map([...xC,[Ct,SC]]);Object.freeze([...CC.keys()]);const wC=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`]),TC=[[`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`]];function EC(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of TC){let i=DC(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))wC.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function DC(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 OC(e,t){switch(e){case`vars`:return{what:e,vars:kC(t)};case`segments`:return{what:e,segments:NC(t)};case`config`:return{what:e,config:IC(t)}}}function kC(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=jC(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:AC(r.lastUpdatedMs())})}return o}function AC(e){return e===null?null:Math.max(0,Date.now()-e)}function jC(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,MC(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}`,MC(i));return t}function MC(e){return e.kind}function NC(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=PC(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:FC(t.template,i),lastRender:r.get(e)??null})}return o}function PC(e){let t=[],n=new Set;for(let r of Zr(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 FC(e,t){let n=new Set;for(let r of Ov(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function IC(e){return e===null?null:e.config}const LC=[`vars`,`segments`,`config`];function RC(e){return typeof e==`string`&&LC.includes(e)}function zC(e){return Math.max(1,e-2)}var BC=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 O(`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);O(`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{O(`Calculating context tokens from transcript: ${e}`);let n=await Nr(e);if(n.length===0)return O(`No entries in transcript`),z;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,O(`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 O(`Most recent main chain context: ${n} tokens (limit: ${t})`),R({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),z}catch(e){return Bn(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return R(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function VC(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var HC=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(VC(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}async foldMetrics(e,t){let n=this.state.get(e),r=xr(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await Lr(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(VC(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Bn(`metrics (${e}): ${n.reason}`):R({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(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})}};const UC=new Map;function WC(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var GC=class{async getSessionId(){if(!process.env.TMUX_PANE)return z;let e=WC(process.env.TMUX),t=UC.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await ye({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?R(n.stdout.trim()):z:Bn(`tmux display-message: ${n.reason}`);return UC.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function KC(e){return e<32||e===127||e>=128&&e<=159}function qC(e,t){let n=``;for(let t of e)n+=KC(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const JC=`\x1B[38;2;255;255;255m`,YC=`\x1B[48;2;200;40;40m`,XC=`\x1B[0m`,ZC=new US;ve(ZC.launchStats);const QC=new ur({counters:ZC,logger:L}),$C=new _r({watchers:QC,logger:L}),ew=new Yr,tw=new XS,nw=new BC,rw=new HC,iw=new GC,aw=new VS({gitService:$C,sessionState:tw,watchers:QC});let ow=null,sw=null;function cw(){t.on(`uncaughtException`,e=>{L(`error`,`uncaughtException: ${e.stack||e.message}`),yw(1)}),t.on(`unhandledRejection`,e=>{L(`error`,`unhandledRejection: ${String(e)}`),yw(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{L(`info`,`received ${e}, shutting down`),yw(0)});ow=F(t.pid);let e=Nn(Fn(ow));if(!e.decision.allow){L(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),yw(1);return}sw=e.registryPath,r.mkdirSync(Ee(),{recursive:!0}),ke(De()),tw.useStorage(new $S(je(),500,L)),En({anchor:Tn(t.env),isAlive:Dn,onOrphaned:e=>{L(`info`,`parent watchdog: ${e}; shutting down`),yw(0)}}),lw(g.createServer({allowHalfOpen:!1},e=>{bw(e)}),De(),!1)}function lw(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){L(`error`,`server error: ${i.message}`),yw(1);return}if(r){L(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}uw(e,n)}),e.listen(n,()=>dw(n))}function uw(e,n){let i=hn(P(A(n)),(e,t)=>Cn(e,t,{readStartTime:Sn,pidAlive:Dn}));if(i.kind===`attach-and-exit`){L(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}L(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){L(`error`,`cannot unlink stale socket ${n}: ${e.message}`),yw(1);return}}lw(e,n,!0)}function dw(e){let n=vn(e);if(n.kind!==`present`){L(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),yw(0);return}gw(e);try{r.chmodSync(e,384)}catch(e){L(`warn`,`chmod socket failed: ${e.message}`)}L(`info`,`daemon up: pid=${t.pid} v=3 sock=${e}`),ft(),pw(),hw(),fw(e,n.identity)}function fw(e,n){xn({bound:n,myPid:t.pid,readIdentity:()=>vn(e),readLease:()=>P(A(e)),shutdown:e=>yw(e),log:L}).arm()}function pw(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(y(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{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){L(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),yw(0);return}}catch(e){L(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let mw=null;function hw(){mw=GS(qS(ZC.startedAt.getTime(),e=>yw(e))),mw.arm()}function gw(e){let n=gn(A(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:ow});n!==null&&L(`warn`,`lease write failed: ${n}`)}let _w=0,vw=!1;function yw(e){if(!vw){vw=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{$C.close()}catch(e){L(`warn`,`gitService close failed: ${e.message}`)}try{ew.close()}catch(e){L(`warn`,`usageStore close failed: ${e.message}`)}try{QC.closeAll()}catch(e){L(`warn`,`watcherRegistry close failed: ${e.message}`)}try{tw.flush()}catch(e){L(`warn`,`sessionState flush failed: ${e.message}`)}_n(Ae(),t.pid),sw!==null&&Pn(sw,t.pid,jn,e=>r.unlinkSync(e)),zn(),t.exit(e)}}function bw(e){_w++,ZC.inFlight=_w;let t=!1,n=(n,r)=>{if(t){r!==null&&L(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>yw(r);try{e.end(Ue(n),i)}catch(e){L(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{ZC.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=We(e=>{Sw(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{L(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{L(`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=>{L(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),_w=Math.max(0,_w-1),ZC.inFlight=_w})}const xw=e=>({resp:e,exitAfterFlush:null});async function Sw(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return xw({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?L(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):L(`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 xw({ok:!0,stats:ZC.snapshot({gitCache:$C.getStats(),usageCache:ew.getStats(),renderCacheSize:aw.size,watchersActive:QC.size(),nextRestartReason:mw?.describeNextRestart()??null})});if(e.kind===`render`){ZC.requestsTotal++;let t=Date.now();try{let{report:n}=EC(e.hookData);for(let e of n.unknownTopLevelFields)L(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return ZC.requestsErrored++,L(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),xw({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Tw(e.args),s=e.hookData.session_id,c=tw.get(s,`config-override`)??a,l=aw.getOrCreate(i,e.cwd,c),u=Re(e),d=u.termCols,f=zC(d??120),p={...kw,width:f},m=``;if(l.state!==null){let t=zg(tw.get(e.hookData.session_id,`preset`),l.state.config.globals.preset,l.state.config.presets),n=Hg(l.state.config,t),r={preset:t,presetCustomized:Gg(l.state.presetRootOps,t),theme:yc(tw.get(e.hookData.session_id,`theme`),n.palette),look:Cc(tw.get(e.hookData.session_id,`look`),n.look,l.state.config.looks),style:Dc(tw.get(e.hookData.session_id,`style`),n.style),autoWrap:n.autoWrap??!0,padding:n.padding??1,charset:n.charset??`unicode`,colorCompatibility:n.colorCompatibility??`truecolor`},i=await by(e.hookData,Nw,e.cwd,l.state.neededInputPaths,r,u),a=kb(r.theme);p.style=r.style,p.wrap=r.autoWrap,p.padding=r.padding,p.charset=r.charset,p.colorCompatibility=r.colorCompatibility,m=Sx(l.state.config,l.state.compiled,l.state.store,l.state.registry,i,a,p,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:wc(l.state.config.looks,r.look),preset:r.preset})}let h=tw.get(e.hookData.session_id,`click.error`);h&&tw.clear(e.hookData.session_id,`click.error`);let g=[o,l.lastError,h].filter(Boolean).join(`
113
- `)||null,_=Dw(m,g,l.lastWarning),v=Date.now()-t,y=$C.getStats(),b=ew.getStats();return L(`info`,`render sid=${e.hookData.session_id??`?`} took=${v}ms termCols=${d??`?`} width=${f} git=${y.size}/${y.hits}h/${y.misses}m usage=${b.size}/${b.hits}h/${b.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),xw({ok:!0,output:_+`
114
- `})}catch(e){throw ZC.requestsErrored++,e}}if(e.kind===`click`)return xw(await Pw(e.verb,e.value));if(e.kind===`debug`){if(!RC(e.what))return xw({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${LC.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=aw.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Mw(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):jw};return xw({ok:!0,debug:OC(e.what,n)})}return xw({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const Cw=`\x1B]8;;`,ww=`\x1B]8;;\x1B\\`;function Tw(e){let{values:t,tokens:n}=b({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}`))],i=t.config;return{configFile:i===void 0?void 0:qv(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function Ew(e,t,n,r){let i=It([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>qC(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${Cw}${i}\\${n}${r} ⚠ ${a[0]} ${XC}${ww}`,...a.slice(1).map(e=>`${Cw}${i}\\${n}${r} ${e} ${XC}${ww}`)].join(`
115
- `)}function Dw(e,t,n){let r=[];if(t&&r.push(Ew(Ot,t,YC,JC)),n&&r.push(Ew(kt,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
116
- `);return e?`${i}\n${e}`:i}const Ow={sessionState:tw,dlog:L},kw={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},Aw={...kw,width:1/0},jw=new Map;function Mw(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Eb(a,{...Aw,charset:t,colorCompatibility:n}));return r}const Nw={gitProvider:$C,usageStore:ew,contextProvider:nw,metricsProvider:rw,tmuxService:iw,log:L,clock:()=>new Date};function Pw(e,t){let n=CC.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Ow),{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 Fw={connectMs:200,budgetMs:500};async function Iw(e){let n=e.includes(`--json`),r=await Lw();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Qe(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
117
- `);return}t.stdout.write(Vw(r.value))}function Lw(){return Ke({kind:`stats`},Fw,e=>`stats`in e?e.stats:void 0)}function Rw(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function zw(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function Bw(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 Vw(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(` startedAt ${e.startedAt}`),t.push(` uptime ${Bw(e.uptimeSec)}`),t.push(` rss ${Rw(e.rssBytes)}`),t.push(` heapUsed ${Rw(e.heapUsedBytes)}`),t.push(` heapTotal ${Rw(e.heapTotalBytes)}`),t.push(` external ${Rw(e.externalBytes)}`),t.push(` arrayBuffers ${Rw(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 ${zw(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 ${zw(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(`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(`
111
+ `+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=iy(t,Wy),i=hS(Me(),L),a=hl(ml({globals:Xg(i.globals,n.presets)},n),i.segmentPalette),o=Zg(i.presetRootOps,n.presets),s=ay($g(a,o),t??`<default>`,r),c=new KS,l=new Ob(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=Dx(s,l,{cwd:e.cwd});for(let{key:e,spec:t}of rS(s))d.push(Xx(e,t));for(let{key:e,spec:t}of VS(s))d.push(HS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:Cy(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,presetRootOps:o}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let n=[...ty(e.projectDir,e.cwd,e.configFile),Me()],i=new Map;for(let e of n){let t=c.dirname(e);if(!r.existsSync(t))continue;let n=c.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(n)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),o=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(o,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){L(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const YS=16384;var XS=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<YS){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%YS}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: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},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const ZS=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function QS(e){let t=e.rssLimitBytes??ZS,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=c.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),$S(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function $S(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function eC(e,t,n={}){let i=Ee();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:L,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>D.writeHeapSnapshot(e),listSnapshots:()=>{try{return r.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}const tC={load:()=>({}),save:()=>{},flush:()=>{}};function nC(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var rC=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=tC,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=nC(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,X.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,X.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const iC=(e,t)=>O(t);function aC(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 oC=class{timer=null;pending=null;constructor(e,t=500,n=iC){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 aC(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(c.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}`)}}},$=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function sC(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function cC(e){return lC(()=>decodeURIComponent(e))}function lC(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function uC(e,t){let n=be({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 dC=(e,t)=>uC(cC(e),t),fC=(e,t)=>{let n=be({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,cC(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`})`)}},pC=(e,t)=>uC(cC(e),t),mC=(e,t)=>uC(cC(e),t),hC=(e,t)=>{let n=sC(cC(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},gC=(e,t)=>{let[n=``,...r]=lC(()=>M(e)),i=sC(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${Yx().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: ${Yx().join(`, `)})`);let a=[];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=Zx(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},_C=/^-?\d+$/;function vC(e,t,n){return e>n?t:e<t?n:e}const yC=(e,t)=>{let[n=``,r=``,i=``]=lC(()=>M(e)),a=sC(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!_C.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=Qx(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${Yx().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&_C.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=vC(l+o,s.min,s.max),d=Zx(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)};function bC(e){if(!Tl(e))throw Error(`step-config: "${e}" validated as a bounded config-writable key but is not a Globals field — registration/loader invariant broken`)}const xC=(e,t)=>{let[n=``,r=``,i=``]=lC(()=>M(e)),a=sC(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${PS().join(`, `)})`);let o=FS(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=cS(r,o.value);yS(Me(),r,s,t.dlog),t.dlog(`info`,`set-config: ${r}=${o.value} (session=${a})`)},SC=(e,t)=>{let[n=``,r=``,i=``]=lC(()=>M(e)),a=sC(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!_C.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=IS(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${PS().join(`, `)})`);bC(r);let c=mS(Me(),t.dlog)[r],l=typeof c==`number`?Math.max(s.min,Math.min(s.max,c)):s.seed,u=vC(l+o,s.min,s.max),d=FS(r,String(u));if(!d.ok)throw new $(`step-config: ${d.reason}`);let f=cS(r,d.value);yS(Me(),r,f,t.dlog),t.dlog(`info`,`step-config: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},CC=(e,t)=>{let[n=``,r=``]=lC(()=>M(e)),i=sC(n);if(!r||!PS().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${PS().join(`, `)})`);bS(Me(),r,t.dlog),t.dlog(`info`,`reset-config: ${r} (session=${i})`)},wC=(e,t)=>{let[n=``,r=``,i=``]=lC(()=>M(e)),a=sC(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${PS().join(`, `)})`);let o=FS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=r_(r);if(s===null||s.scope!==`preset-root-ops`)throw new $(`apply-layout-op: "${r}" is not a "presets.<name>.rootOps" target`);let c=hS(Me(),t.dlog).presetRootOps[s.preset]??[],l=JSON.stringify([...c,o.value]);yS(Me(),r,l,t.dlog),t.dlog(`info`,`apply-layout-op: ${r} += ${o.value} (session=${a})`)},TC=(e,t)=>{let[n=``]=lC(()=>M(e)),r=sC(n),i=jS(Me(),t.dlog);if(i===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i.key} (session=${r})`)},EC=(e,t)=>{let[n=``]=lC(()=>M(e)),r=sC(n),i=MS(Me(),t.dlog);if(i===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i.key} (session=${r})`)},DC=`config-override`,OC=new Map([[Et,dC],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=sC(lC(()=>decodeURIComponent(e.slice(0,n)))),i=lC(()=>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,DC),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,DC,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Dt,fC],[wt,gC],[Tt,yC],[At,xC],[jt,SC],[Mt,CC],[Nt,wC],[Pt,TC],[j,EC],[Ot,pC],[kt,mC],[`toolbar-toggle`,hC]]),kC=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Lt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`set-config`||a===`step-config`||a===`reset-config`||a===`apply-layout-op`||a===`undo`||a===`redo`||a===`toolbar-toggle`)){let e=M(o);e.length>0&&e[0]&&(i=e[0])}let e=OC.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(`
112
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},AC=new Map([...OC,[Ct,kC]]);Object.freeze([...AC.keys()]);const jC=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`]),MC=[[`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`]];function NC(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of MC){let i=PC(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))jC.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function PC(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 FC(e,t){switch(e){case`vars`:return{what:e,vars:IC(t)};case`segments`:return{what:e,segments:BC(t)};case`config`:return{what:e,config:UC(t)}}}function IC(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=RC(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:LC(r.lastUpdatedMs())})}return o}function LC(e){return e===null?null:Math.max(0,Date.now()-e)}function RC(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,zC(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}`,zC(i));return t}function zC(e){return e.kind}function BC(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=VC(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:HC(t.template,i),lastRender:r.get(e)??null})}return o}function VC(e){let t=[],n=new Set;for(let r of Zr(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 HC(e,t){let n=new Set;for(let r of Fv(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function UC(e){return e===null?null:e.config}const WC=[`vars`,`segments`,`config`];function GC(e){return typeof e==`string`&&WC.includes(e)}function KC(e){return Math.max(1,e-2)}var qC=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 O(`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);O(`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{O(`Calculating context tokens from transcript: ${e}`);let n=await Nr(e);if(n.length===0)return O(`No entries in transcript`),z;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,O(`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 O(`Most recent main chain context: ${n} tokens (limit: ${t})`),R({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),z}catch(e){return Bn(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return R(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function JC(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var YC=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(JC(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}async foldMetrics(e,t){let n=this.state.get(e),r=xr(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await Lr(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(JC(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Bn(`metrics (${e}): ${n.reason}`):R({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(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})}};const XC=new Map;function ZC(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var QC=class{async getSessionId(){if(!process.env.TMUX_PANE)return z;let e=ZC(process.env.TMUX),t=XC.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await ye({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?R(n.stdout.trim()):z:Bn(`tmux display-message: ${n.reason}`);return XC.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function $C(e){return e<32||e===127||e>=128&&e<=159}function ew(e,t){let n=``;for(let t of e)n+=$C(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const tw=`\x1B[38;2;255;255;255m`,nw=`\x1B[48;2;200;40;40m`,rw=`\x1B[0m`,iw=new XS;ve(iw.launchStats);const aw=new ur({counters:iw,logger:L}),ow=new _r({watchers:aw,logger:L}),sw=new Yr,cw=new rC,lw=new qC,uw=new YC,dw=new QC,fw=new JS({gitService:ow,sessionState:cw,watchers:aw});let pw=null,mw=null;function hw(){t.on(`uncaughtException`,e=>{L(`error`,`uncaughtException: ${e.stack||e.message}`),Ew(1)}),t.on(`unhandledRejection`,e=>{L(`error`,`unhandledRejection: ${String(e)}`),Ew(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{L(`info`,`received ${e}, shutting down`),Ew(0)});pw=F(t.pid);let e=Nn(Fn(pw));if(!e.decision.allow){L(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Ew(1);return}mw=e.registryPath,r.mkdirSync(Ee(),{recursive:!0}),ke(De()),cw.useStorage(new oC(je(),500,L)),En({anchor:Tn(t.env),isAlive:Dn,onOrphaned:e=>{L(`info`,`parent watchdog: ${e}; shutting down`),Ew(0)}}),gw(g.createServer({allowHalfOpen:!1},e=>{Dw(e)}),De(),!1)}function gw(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){L(`error`,`server error: ${i.message}`),Ew(1);return}if(r){L(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}_w(e,n)}),e.listen(n,()=>vw(n))}function _w(e,n){let i=hn(P(A(n)),(e,t)=>Cn(e,t,{readStartTime:Sn,pidAlive:Dn}));if(i.kind===`attach-and-exit`){L(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}L(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){L(`error`,`cannot unlink stale socket ${n}: ${e.message}`),Ew(1);return}}gw(e,n,!0)}function vw(e){let n=vn(e);if(n.kind!==`present`){L(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Ew(0);return}Cw(e);try{r.chmodSync(e,384)}catch(e){L(`warn`,`chmod socket failed: ${e.message}`)}L(`info`,`daemon up: pid=${t.pid} v=3 sock=${e}`),ft(),bw(),Sw(),yw(e,n.identity)}function yw(e,n){xn({bound:n,myPid:t.pid,readIdentity:()=>vn(e),readLease:()=>P(A(e)),shutdown:e=>Ew(e),log:L}).arm()}function bw(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(y(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{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){L(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),Ew(0);return}}catch(e){L(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let xw=null;function Sw(){xw=QS(eC(iw.startedAt.getTime(),e=>Ew(e))),xw.arm()}function Cw(e){let n=gn(A(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:pw});n!==null&&L(`warn`,`lease write failed: ${n}`)}let ww=0,Tw=!1;function Ew(e){if(!Tw){Tw=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{ow.close()}catch(e){L(`warn`,`gitService close failed: ${e.message}`)}try{sw.close()}catch(e){L(`warn`,`usageStore close failed: ${e.message}`)}try{aw.closeAll()}catch(e){L(`warn`,`watcherRegistry close failed: ${e.message}`)}try{cw.flush()}catch(e){L(`warn`,`sessionState flush failed: ${e.message}`)}_n(Ae(),t.pid),mw!==null&&Pn(mw,t.pid,jn,e=>r.unlinkSync(e)),zn(),t.exit(e)}}function Dw(e){ww++,iw.inFlight=ww;let t=!1,n=(n,r)=>{if(t){r!==null&&L(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>Ew(r);try{e.end(Ue(n),i)}catch(e){L(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{iw.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=We(e=>{kw(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{L(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{L(`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=>{L(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),ww=Math.max(0,ww-1),iw.inFlight=ww})}const Ow=e=>({resp:e,exitAfterFlush:null});async function kw(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Ow({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?L(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):L(`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 Ow({ok:!0,stats:iw.snapshot({gitCache:ow.getStats(),usageCache:sw.getStats(),renderCacheSize:fw.size,watchersActive:aw.size(),nextRestartReason:xw?.describeNextRestart()??null})});if(e.kind===`render`){iw.requestsTotal++;let t=Date.now();try{let{report:n}=NC(e.hookData);for(let e of n.unknownTopLevelFields)L(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return iw.requestsErrored++,L(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Ow({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Mw(e.args),s=e.hookData.session_id,c=cw.get(s,`config-override`)??a,l=fw.getOrCreate(i,e.cwd,c),u=Re(e),d=u.termCols,f=KC(d??120),p={...Iw,width:f},m=``;if(l.state!==null){let t=Kg(cw.get(e.hookData.session_id,`preset`),l.state.config.globals.preset,l.state.config.presets),n=Yg(l.state.config,t),r={preset:t,presetCustomized:Qg(l.state.presetRootOps,t),theme:bc(cw.get(e.hookData.session_id,`theme`),n.palette),look:wc(cw.get(e.hookData.session_id,`look`),n.look,l.state.config.looks),style:Oc(cw.get(e.hookData.session_id,`style`),n.style),autoWrap:Fc(cw.get(e.hookData.session_id,`autoWrap`),n.autoWrap),padding:Ic(cw.get(e.hookData.session_id,`padding`),n.padding),charset:n.charset??`unicode`,colorCompatibility:n.colorCompatibility??`truecolor`},i=await Dy(e.hookData,Bw,e.cwd,l.state.neededInputPaths,r,u),a=Ib(r.theme);p.style=r.style,p.wrap=r.autoWrap,p.padding=r.padding,p.charset=r.charset,p.colorCompatibility=r.colorCompatibility,m=kx(l.state.config,l.state.compiled,l.state.store,l.state.registry,i,a,p,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:Tc(l.state.config.looks,r.look),preset:r.preset})}let h=cw.get(e.hookData.session_id,`click.error`);h&&cw.clear(e.hookData.session_id,`click.error`);let g=[o,l.lastError,h].filter(Boolean).join(`
113
+ `)||null,_=Pw(m,g,l.lastWarning),v=Date.now()-t,y=ow.getStats(),b=sw.getStats();return L(`info`,`render sid=${e.hookData.session_id??`?`} took=${v}ms termCols=${d??`?`} width=${f} git=${y.size}/${y.hits}h/${y.misses}m usage=${b.size}/${b.hits}h/${b.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),Ow({ok:!0,output:_+`
114
+ `})}catch(e){throw iw.requestsErrored++,e}}if(e.kind===`click`)return Ow(await Vw(e.verb,e.value));if(e.kind===`debug`){if(!GC(e.what))return Ow({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${WC.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=fw.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?zw(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):Rw};return Ow({ok:!0,debug:FC(e.what,n)})}return Ow({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const Aw=`\x1B]8;;`,jw=`\x1B]8;;\x1B\\`;function Mw(e){let{values:t,tokens:n}=b({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}`))],i=t.config;return{configFile:i===void 0?void 0:ey(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function Nw(e,t,n,r){let i=It([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>ew(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${Aw}${i}\\${n}${r} ⚠ ${a[0]} ${rw}${jw}`,...a.slice(1).map(e=>`${Aw}${i}\\${n}${r} ${e} ${rw}${jw}`)].join(`
115
+ `)}function Pw(e,t,n){let r=[];if(t&&r.push(Nw(Ot,t,nw,tw)),n&&r.push(Nw(kt,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
116
+ `);return e?`${i}\n${e}`:i}const Fw={sessionState:cw,dlog:L},Iw={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},Lw={...Iw,width:1/0},Rw=new Map;function zw(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Nb(a,{...Lw,charset:t,colorCompatibility:n}));return r}const Bw={gitProvider:ow,usageStore:sw,contextProvider:lw,metricsProvider:uw,tmuxService:dw,log:L,clock:()=>new Date};function Vw(e,t){let n=AC.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Fw),{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 Hw={connectMs:200,budgetMs:500};async function Uw(e){let n=e.includes(`--json`),r=await Ww();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Qe(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
117
+ `);return}t.stdout.write(Jw(r.value))}function Ww(){return Ke({kind:`stats`},Hw,e=>`stats`in e?e.stats:void 0)}function Gw(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function Kw(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function qw(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 Jw(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(` startedAt ${e.startedAt}`),t.push(` uptime ${qw(e.uptimeSec)}`),t.push(` rss ${Gw(e.rssBytes)}`),t.push(` heapUsed ${Gw(e.heapUsedBytes)}`),t.push(` heapTotal ${Gw(e.heapTotalBytes)}`),t.push(` external ${Gw(e.externalBytes)}`),t.push(` arrayBuffers ${Gw(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 ${Kw(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 ${Kw(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(`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(`
118
118
  `)+`
119
- `}const Hw={connectMs:200,budgetMs:500};async function Uw(e,n){let r=n.includes(`--json`),i=await Ww(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Qe(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
120
- `);return}t.stdout.write(Gw(i.value))}function Ww(e){return Ke({kind:`debug`,what:e},Hw,e=>`debug`in e?e.debug:void 0)}function Gw(e){switch(e.what){case`vars`:return Kw(e.vars);case`segments`:return qw(e.segments);case`config`:return Jw(e.config);default:return e}}function Kw(e){if(e.length===0)return`no variables (DSL not active)
121
- `;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);for(let i of e){let e=i.ageMs===null?``:` ${Xw(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${Yw(i.value)}${e}${a}`)}return t.join(`
119
+ `}const Yw={connectMs:200,budgetMs:500};async function Xw(e,n){let r=n.includes(`--json`),i=await Zw(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Qe(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
120
+ `);return}t.stdout.write(Qw(i.value))}function Zw(e){return Ke({kind:`debug`,what:e},Yw,e=>`debug`in e?e.debug:void 0)}function Qw(e){switch(e.what){case`vars`:return $w(e.vars);case`segments`:return eT(e.segments);case`config`:return tT(e.config);default:return e}}function $w(e){if(e.length===0)return`no variables (DSL not active)
121
+ `;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);for(let i of e){let e=i.ageMs===null?``:` ${rT(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${nT(i.value)}${e}${a}`)}return t.join(`
122
122
  `)+`
123
- `}function qw(e){if(e.length===0)return`no segments (DSL not active)
123
+ `}function eT(e){if(e.length===0)return`no segments (DSL not active)
124
124
  `;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
125
125
  `)+`
126
- `}function Jw(e){return e===null?`config: DSL not active
126
+ `}function tT(e){return e===null?`config: DSL not active
127
127
  `:JSON.stringify(e,null,2)+`
128
- `}function Yw(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Xw(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Zw(){let e=$w();return e===null?null:r.readFileSync(e,`utf-8`)}function Qw(){let e;try{e=Zw()}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 $w(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function eT(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},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:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function tT(e,n=t.cwd()){let i=e===void 0?Yv(n,n):c.resolve(qv(e));if(e!==void 0&&i!==null){let e;try{e=r.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let a=[],o=Xv(n,n);o!==null&&a.push(o);try{return{kind:`clean`,configPath:i,warnings:a,rendered:nT(i,n,a)}}catch(e){let t=e;return i!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===i&&typeof t.message==`string`?{kind:`unreadable`,path:i,message:t.message}:{kind:`fatal`,configPath:i,message:e instanceof Ac||e instanceof Error?e.message:String(e),warnings:a}}}function nT(e,t,n){let{config:r,source:i}=Zv(e,Ly),a=Qv(r,e??`<default>`,i),o=new zS,s=new xb(o,a.globals.default_empty_value??``,void 0,new XS);try{let e=bx(a,s,{cwd:t});n.push(...e.loadWarnings),Xx(a);let r=zg(null,a.globals.preset,a.presets),i=Hg(a,r),c={preset:r,presetCustomized:!1,theme:yc(null,i.palette),look:Cc(null,i.look,a.looks),style:Dc(null,i.style),autoWrap:i.autoWrap??!0,padding:i.padding??1,charset:i.charset??`unicode`,colorCompatibility:i.colorCompatibility??`truecolor`},l=t=>{let n=new Map;return{rendered:Sx(a,e,o,s,eT(t),kb(t.theme),{style:t.style,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:wc(a.looks,t.look),preset:t.preset}),segmentErrors:n}},u=l(c),d=l({...c,presetCustomized:!0}),f=[...[...u.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...d.segmentErrors].filter(([e])=>!u.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(f.length>0)throw Error(`config renders with ${f.length} segment error${f.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+f.map(e=>` ${e}`).join(`
129
- `));return u.rendered}finally{s.dispose()}}function rT(e){return e.map(e=>`warning: ${e}\n`).join(``)}function iT(e){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`,stderr:rT(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:rT(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}function aT(e){(e.length>1||e[0]===``)&&(t.stderr.write(`check: expected at most one non-empty path
128
+ `}function nT(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function rT(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function iT(){let e=oT();return e===null?null:r.readFileSync(e,`utf-8`)}function aT(){let e;try{e=iT()}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 oT(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function sT(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},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:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function cT(e,n=t.cwd()){let i=e===void 0?ny(n,n):c.resolve(ey(e));if(e!==void 0&&i!==null){let e;try{e=r.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let a=[],o=ry(n,n);o!==null&&a.push(o);try{return{kind:`clean`,configPath:i,warnings:a,rendered:lT(i,n,a)}}catch(e){let t=e;return i!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===i&&typeof t.message==`string`?{kind:`unreadable`,path:i,message:t.message}:{kind:`fatal`,configPath:i,message:e instanceof Lc||e instanceof Error?e.message:String(e),warnings:a}}}function lT(e,t,n){let{config:r,source:i}=iy(e,Wy),a=ay(r,e??`<default>`,i),o=new KS,s=new Ob(o,a.globals.default_empty_value??``,void 0,new rC);try{let e=Dx(a,s,{cwd:t});n.push(...e.loadWarnings),rS(a);let r=Kg(null,a.globals.preset,a.presets),i=Yg(a,r),c={preset:r,presetCustomized:!1,theme:bc(null,i.palette),look:wc(null,i.look,a.looks),style:Oc(null,i.style),autoWrap:Fc(null,i.autoWrap),padding:Ic(null,i.padding),charset:i.charset??`unicode`,colorCompatibility:i.colorCompatibility??`truecolor`},l=t=>{let n=new Map;return{rendered:kx(a,e,o,s,sT(t),Ib(t.theme),{style:t.style,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:Tc(a.looks,t.look),preset:t.preset}),segmentErrors:n}},u=l(c),d=l({...c,presetCustomized:!0}),f=[...[...u.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...d.segmentErrors].filter(([e])=>!u.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(f.length>0)throw Error(`config renders with ${f.length} segment error${f.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+f.map(e=>` ${e}`).join(`
129
+ `));return u.rendered}finally{s.dispose()}}function uT(e){return e.map(e=>`warning: ${e}\n`).join(``)}function dT(e){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`,stderr:uT(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:uT(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}function fT(e){(e.length>1||e[0]===``)&&(t.stderr.write(`check: expected at most one non-empty path
130
130
  Usage: cc-candybar check [config-file]
131
- `),t.exit(2));let n=iT(tT(e[0]));t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}const oT=`${YC}${JC}`;function sT(e){return`${oT}⚠ cc-candybar: ${cT(e)}${XC}\n`}function cT(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: ${qC(e.message,60)}`;case`render_failed`:return`render failed: ${qC(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${qC(e.message,60)}`}}function lT(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
132
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:sT(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function uT(){let e=t.env.COLUMNS;if(e){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}let n=t.stderr.columns;if(n&&n>0)return n}const dT=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function fT(){return dT.some(e=>(t.env[e]??``)!==``)}function pT(){console.log(`
131
+ `),t.exit(2));let n=dT(cT(e[0]));t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}const pT=`${nw}${tw}`;function mT(e){return`${pT}⚠ cc-candybar: ${hT(e)}${rw}\n`}function hT(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: ${ew(e.message,60)}`;case`render_failed`:return`render failed: ${ew(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${ew(e.message,60)}`}}function gT(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
132
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:mT(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function _T(){let e=t.env.COLUMNS;if(e){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}let n=t.stderr.columns;if(n&&n>0)return n}const vT=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function yT(){return vT.some(e=>(t.env[e]??``)!==``)}function bT(){console.log(`
133
133
  cc-candybar - Beautiful powerline statusline for Claude Code
134
134
 
135
135
  Usage: cc-candybar [options]
@@ -179,7 +179,7 @@ Config tooling:
179
179
  config [--json] The effective merged config. (All three query the
180
180
  running daemon; none spawn one.)
181
181
 
182
- `)}async function mT(){try{(t.argv.includes(`--help`)||t.argv.includes(`-h`))&&(pT(),t.exit(0));let e=t.argv[2];if(e===`install`&&(pn(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(cn(),t.exit(0)),e===`url-handle`){await un(t.argv[3]);return}if(e===`daemon`){cw();return}if(e===`daemon-stats`&&(await Iw(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){aT(t.argv.slice(3));return}if(e===`schema`){Qw();return}RC(e)&&(await Uw(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
182
+ `)}async function xT(){try{(t.argv.includes(`--help`)||t.argv.includes(`-h`))&&(bT(),t.exit(0));let e=t.argv[2];if(e===`install`&&(pn(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(cn(),t.exit(0)),e===`url-handle`){await un(t.argv[3]);return}if(e===`daemon`){hw();return}if(e===`daemon-stats`&&(await Uw(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){fT(t.argv.slice(3));return}if(e===`schema`){aT();return}GC(e)&&(await Xw(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
183
183
 
184
184
  cc-candybar is designed to be used as a Claude Code statusLine command.
185
185
  It reads hook data from stdin and outputs formatted statusline.
@@ -195,4 +195,4 @@ Add to ~/.claude/settings.json:
195
195
  Run with --help for more options.
196
196
 
197
197
  To test output manually:
198
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),pT(),t.exit(1));let i=lT(await nt(r,t.argv,t.cwd(),{termCols:uT(),ssh:fT()}));i.debug!==null&&O(i.debug),i.kick&&it(),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)}}mT();export{};
198
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),bT(),t.exit(1));let i=gT(await nt(r,t.argv,t.cwd(),{termCols:_T(),ssh:yT()}));i.debug!==null&&O(i.debug),i.kick&&it(),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)}}xT();export{};