@promptctl/cc-candybar 1.10.0 → 1.11.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 +36 -36
- package/package.json +5 -5
- package/schema/cc-candybar.schema.json +6 -0
- package/src/config/dsl-types.ts +10 -1
- package/src/config/loader/globals.ts +5 -1
- package/src/daemon/server.ts +24 -2
- package/src/demo/dsl.ts +2 -0
- package/src/render/strip.ts +56 -14
- package/src/themes/policy.ts +17 -0
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import e from"node:process";import{json as t}from"node:stream/consumers";import n,{createReadStream as r,existsSync as i,watch as a}from"node:fs";import o,{basename as s,dirname as c,join as l}from"node:path";import u,{homedir as d}from"node:os";import{spawn as f,spawnSync as p}from"node:child_process";import m from"node:net";import{URL as h,URLSearchParams as g,fileURLToPath as _}from"node:url";import{parseArgs as v}from"node:util";import{get as y}from"node:https";import{createHash as b}from"node:crypto";import{setTimeout as x}from"node:timers/promises";import{open as S,readFile as C,readdir as ee,stat as te}from"node:fs/promises";import{createInterface as w}from"node:readline";import{clearInterval as ne,setInterval as re}from"node:timers";import ie from"node:v8";var T=Object.create,E=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,oe=Object.getOwnPropertyNames,se=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),le=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=oe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ce.call(e,s)&&s!==n&&E(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ae(t,s))||r.enumerable});return e},ue=(e,t,n)=>(n=e==null?{}:T(se(e)),le(t||!e||!e.__esModule?E(n,`default`,{value:e,enumerable:!0}):n,e));function O(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const de={"click.pbcopy":1e3,"click.open":1e3},fe=new Map;function pe(e){let t=de[e];if(t===void 0)return{allowed:!0};let n=fe.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 me(e){fe.set(e,Date.now())}function he(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 ge=null;function k(e){ge=e}async function _e(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();return ge?.onStart(e.category),new Promise(t=>{let r;try{r=f(e.bin,e.args??[],{cwd:e.cwd,env:e.env,stdio:[`pipe`,`pipe`,`pipe`]})}catch(r){ge?.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),ge?.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 ve(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();ge?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=p(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`});ge?.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 ge?.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 ye(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();ge?.onStart(e.category);let r=be(e);return ge?.onEnd(e.category,Date.now()-n),r}function be(e){let t;try{t=f(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 xe(e){let t=process.env[e];return t&&t.length>0?t:void 0}function Se(){let e=xe(`XDG_STATE_HOME`)??o.join(u.homedir(),`.local`,`state`);return o.join(e,`cc-candybar`)}function Ce(){let e=xe(`XDG_CACHE_HOME`)??o.join(u.homedir(),`.cache`);return o.join(e,`cc-candybar`)}function we(){return Se()}function Te(){let e=process.env.CC_CANDYBAR_SOCKET;if(e)return e;let t=u.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${t}`,`socket`)}function Ee(e){let t=o.dirname(e);n.mkdirSync(t,{recursive:!0,mode:448});let r=n.lstatSync(t);if(r.isSymbolicLink())throw Error(`socket parent is a symlink: ${t}`);if(!r.isDirectory())throw Error(`socket parent is not a directory: ${t}`);let i=u.userInfo().uid;if(typeof i==`number`&&r.uid!==i)throw Error(`socket parent is not owned by uid ${i}: ${t} (owner uid=${r.uid})`);if(r.mode&63)throw Error(`socket parent has unsafe permissions: ${t} (mode=${(r.mode&511).toString(8)}, expected 0700)`);try{if(n.lstatSync(e).isSymbolicLink())throw Error(`socket path is a symlink: ${e}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function De(){return o.join(Se(),`pid`)}function Oe(){return o.join(Se(),`session-state.json`)}function ke(){return o.join(Se(),`spawn.lock`)}function A(){return o.join(Se(),`daemon.log`)}const Ae=1e4;function je(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Ae?Ae:t}var Me=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Ne(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Pe(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 Me(`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 Me(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Fe(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=Pe(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(Ne(t))})}async function Ie(e,t,n){let r=null;try{r=await Ve(Te(),t.connectMs);let i=await Fe(r,{v:3,...e},t.budgetMs);return ze(e.kind,i,n)}catch(e){return Be(e)}finally{r&&r.destroy()}}function Le(e,t){return typeof e==`string`?e:t}function Re(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ze(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=Le(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Re(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 Be(e){if(e instanceof Me||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 Ve(e,t){return new Promise((n,r)=>{let i=m.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 He(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 Ue={connectMs:50,budgetMs:150},We={connectMs:50,budgetMs:200};function Ge(e){let t=e.output;return typeof t==`string`?t:void 0}function Ke(e,t,n,r){return Ie({kind:`render`,hookData:e,args:t,cwd:n,termCols:r},Ue,Ge)}function qe(e,t){return Ie({kind:`click`,verb:e,value:t},We,Ge)}function Je(t={}){if(tt()!==null)return;let n=t.spawn??nt,r=Qe();if(r.kind===`contended`){let t=Ye();t!==null&&t>2e3&&(e.stderr.write(`cc-candybar: spawn-lock held ${t}ms (likely crashed holder) — spawning unlocked\n`),Xe(n));return}if(r.kind===`error`){e.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Xe(n);return}try{Xe(n)}finally{et()}}function Ye(){try{let e=n.statSync(ke());return Date.now()-e.mtimeMs}catch{return null}}function Xe(t){try{t()||e.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
3
|
-
`)}catch(t){e.stderr.write(`cc-candybar: daemon spawn failed: ${t.message}\n`)}}let Ze=null;function Qe(){let t=ke();for(let r=0;r<2;r++){try{let r=n.openSync(t,`wx`,384);try{n.writeSync(r,JSON.stringify({pid:e.pid,ts:Date.now()}))}catch{}return Ze={fd:r,path:t},{kind:`held`}}catch(e){let n=e.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${t}): ${n??e.message}`}}if(!$e(t))return{kind:`contended`};try{n.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function $e(e){try{let t=n.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function et(){if(!Ze)return;let{fd:e,path:t}=Ze;Ze=null;try{n.closeSync(e)}catch{}try{n.unlinkSync(t)}catch{}}function tt(){try{return n.mkdirSync(we(),{recursive:!0}),null}catch(e){return`mkdir ${we()}: ${e.message}`}}function nt(){let t=e.execPath,n=e.argv[1];return n?ye({bin:t,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const rt=`cc-candybar`,it=`dispatch`,at=`set-state`,ot=`step-state`,st=`copy`,ct=`open-vscode`,lt=`show-config-error`,ut=`show-config-warning`;function dt(e){return e.map(encodeURIComponent).join(`/`)}function ft(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function pt(e){return`${rt}://${it}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${dt(e.args)}`)}`).join(`&`)}`}function mt(e){return new g(e).getAll(`e`).map(ht)}function ht(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const gt=`@promptctl/cc-candybar`,_t=`CCCandybarURLHandler`,vt=[];function yt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function bt(e){return[`pnpm`,`dlx`,`${gt}@1.
|
|
3
|
+
`)}catch(t){e.stderr.write(`cc-candybar: daemon spawn failed: ${t.message}\n`)}}let Ze=null;function Qe(){let t=ke();for(let r=0;r<2;r++){try{let r=n.openSync(t,`wx`,384);try{n.writeSync(r,JSON.stringify({pid:e.pid,ts:Date.now()}))}catch{}return Ze={fd:r,path:t},{kind:`held`}}catch(e){let n=e.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${t}): ${n??e.message}`}}if(!$e(t))return{kind:`contended`};try{n.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function $e(e){try{let t=n.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function et(){if(!Ze)return;let{fd:e,path:t}=Ze;Ze=null;try{n.closeSync(e)}catch{}try{n.unlinkSync(t)}catch{}}function tt(){try{return n.mkdirSync(we(),{recursive:!0}),null}catch(e){return`mkdir ${we()}: ${e.message}`}}function nt(){let t=e.execPath,n=e.argv[1];return n?ye({bin:t,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const rt=`cc-candybar`,it=`dispatch`,at=`set-state`,ot=`step-state`,st=`copy`,ct=`open-vscode`,lt=`show-config-error`,ut=`show-config-warning`;function dt(e){return e.map(encodeURIComponent).join(`/`)}function ft(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function pt(e){return`${rt}://${it}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${dt(e.args)}`)}`).join(`&`)}`}function mt(e){return new g(e).getAll(`e`).map(ht)}function ht(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const gt=`@promptctl/cc-candybar`,_t=`CCCandybarURLHandler`,vt=[];function yt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function bt(e){return[`pnpm`,`dlx`,`${gt}@1.11.0`,...e.map(yt)].join(` `)}function xt(){return o.join(u.homedir(),`Applications`,`${_t}.app`)}function St(){return o.join(u.homedir(),`.claude`,`settings.json`)}function Ct(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function wt(){return o.join(u.homedir(),`Library`,`Application Support`,`CCCandybar`)}function Tt(){return o.join(wt(),`url-handler.mjs`)}function Et(e,t,n){let r=e.replace(/"/g,`\\"`),i=t.replace(/"/g,`\\"`);return[`on open location L`,`\tdo shell script "NODE_PATH='${n.replace(/"/g,`\\"`)}' '${r}' '${i}' url-handle " & quoted form of L`,`end open location`].join(`
|
|
4
4
|
`)}function Dt(e){if(!e)throw Error(`install-url-handler: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:o.resolve(o.dirname(e),`..`,`dist`,`index.mjs`)}function Ot(){let e=Dt(process.argv[1]);if(!n.existsSync(e))throw Error(`install-url-handler: bundled dist not found at ${e}. Reinstall the package.`);n.mkdirSync(wt(),{recursive:!0});let t=Tt();return n.copyFileSync(e,t),t}function kt(){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>${rt}</string>`,` </array>`,` </dict>`,`</array>`].join(`
|
|
5
5
|
`)}]}function At(){Ct();let e=Ot();process.stdout.write(`Copied dist to ${e}\n`);let t=Dt(process.argv[1]),r=o.join(o.dirname(t),`..`,`node_modules`);if(!n.existsSync(r))throw Error(`install-url-handler: node_modules not found at ${r}. Install deps first.`);let i=xt();n.mkdirSync(o.dirname(i),{recursive:!0}),n.existsSync(i)&&n.rmSync(i,{recursive:!0,force:!0}),process.stdout.write(`Building ${i}\n`);let a=ve({bin:`/usr/bin/osacompile`,args:[`-o`,i,`-e`,Et(process.execPath,e,r)],category:`install.osacompile`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`osacompile failed (${a.reason})`);let s=o.join(i,`Contents`,`Info.plist`);for(let{key:e}of kt())ve({bin:`/usr/bin/plutil`,args:[`-remove`,e,s],category:`install.plutil`});for(let{key:e,xml:t}of kt()){let n=ve({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,s],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${rt}:// with Launch Services\n`);let c=ve({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,i],category:`install.lsregister`});if(!c.ok)throw process.stderr.write(c.stderr),Error(`lsregister failed (${c.reason})`);process.stdout.write(`✓ ${_t}.app installed and registered.\n`),process.stdout.write(` Test: open '${rt}://hello-world' && pbpaste\n`)}function jt(e,t=rt){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:st,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Mt(e){e||(process.stderr.write(`url-handle: missing URL argument.
|
|
6
6
|
`),process.exit(1));let t;try{t=jt(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await qe(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(Je(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Nt(n)+`
|
|
@@ -78,54 +78,54 @@ Use 'override' annotation for methods overridden by subclass.`)}}var $i=aa(0),ea
|
|
|
78
78
|
`)),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(`
|
|
79
79
|
`)),h.push(new Y(Rr(``,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=Vr(s,Lr(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]=zr(s,u),f=Rr(d,u),p=n&&c>=0?H(s.slice(0,c)):-1;if(p>=0&&p<u){let[t,n]=zr(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(`
|
|
80
80
|
`),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:Lr(a),isContinuation:!1});else for(let t=0;t<e.length;t++){let n=e[t];r.push({content:n.content,valueStart:Lr(a+n.start),isContinuation:t>0})}}else r.push({content:o,valueStart:Lr(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 K.fromRgba(t)}}})();var To=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},Eo=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=$a,r=[],i,a=[],o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C,ee,te;return class extends n{static{let w=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],ee=[X.action],te=[X.action],Eo(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:w},a,o),Eo(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:w},c,l),Eo(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:w},d,f),Eo(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:w},m,h),Eo(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:w},_,v),Eo(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:w},b,x),Eo(this,null,S,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:w},null,r),Eo(this,null,C,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:w},null,r),Eo(this,null,ee,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:w},null,r),Eo(this,null,te,{kind:`method`,name:`handleFocus`,static:!1,private:!1,access:{has:e=>`handleFocus`in e,get:e=>e.handleFocus},metadata:w},null,r),w&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:w})}id=To(this,r);focusable=!0;#e=To(this,a,void 0);get options(){return this.#e}set options(e){this.#e=e}#t=(To(this,o),To(this,c,void 0));get selectedIndex(){return this.#t}set selectedIndex(e){this.#t=e}#n=(To(this,l),To(this,d,!1));get expanded(){return this.#n}set expanded(e){this.#n=e}#r=(To(this,f),To(this,m,void 0));get highlightedIndex(){return this.#r}set highlightedIndex(e){this.#r=e}#i=(To(this,h),To(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=(To(this,v),To(this,b,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}constructor(e){super(),To(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??Yi}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 Rr(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]=zr(this.filter,U(n));return Rr(` `+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(`
|
|
81
|
-
`)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${Rr(`(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=` ${Rr(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 K.fromRgba(t)}}})();var Do=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},Oo=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=$a,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],ee=[],te,w,ne,re;return class extends a{static{let ie=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)],te=[X.action],w=[X.action],ne=[X.action],re=[X.action],Oo(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:ie},c,l),Oo(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:ie},d,f),Oo(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:ie},m,h),Oo(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:ie},_,v),Oo(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:ie},b,x),Oo(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:ie},C,ee),Oo(this,null,te,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:ie},null,o),Oo(this,null,w,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:ie},null,o),Oo(this,null,ne,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:ie},null,o),Oo(this,null,re,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:ie},null,o),ie&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:ie})}id=Do(this,o);focusable=!0;#e=Do(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Do(this,l),Do(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Do(this,f),Do(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Do(this,h),Do(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Do(this,v),Do(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Do(this,x),Do(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Do(this,ee),!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=ko(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??Yi}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=ko(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 K.fromRgba(t)}}})();function ko(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 Ao(e,t){if(!(e instanceof Ca))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 jo(e){return{fn:(t=>Ao(t,e)),argTypes:[`liftable`],returnType:`T`}}function Mo(){let e={};for(let t of Object.keys(mi))e[t]=jo(new J({color:K.parse(t)}));return e}const No={fn:((e,t)=>{if(!Number.isInteger(e)||e<0||e>255)throw RangeError(`color index ${e} is out of range (0-255)`);return Ao(t,new J({color:K.fromAnsi(e)}))}),argTypes:[`int`,`liftable`],returnType:`T`},Po=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/,Fo={fn:((e,t)=>{if(!Po.test(e))throw RangeError(`hex expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return Ao(t,new J({color:K.parse(e)}))}),argTypes:[`string`,`liftable`],returnType:`T`},Io={fn:((e,t,n,r)=>Ao(r,new J({color:K.fromRgb(e,t,n)}))),argTypes:[`int`,`int`,`int`,`liftable`],returnType:`T`},Lo={fn:((e,t)=>Ao(t,new J({bgcolor:K.parse(e)}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ro(e,t){return new J({[e]:t})}function zo(){let e={};for(let t of ra)e[t]=jo(Ro(t,!0)),e[`not_${t}`]=jo(Ro(t,!1));for(let[t,n]of Object.entries(aa))e[t]=jo(Ro(n,!0));return e}const Bo={fn:((e,t)=>Ao(t,J.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Vo={fn:((e,t)=>Ao(t,new J({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ho(){return{...Mo(),color:No,hex:Fo,rgb:Io,on:Lo,...zo(),link:Vo,style:Bo}}const Uo=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;function Wo(e){if(!Uo.test(e))throw RangeError(`palette background expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return K.parse(e).getTruecolor()}function Go(e,t,n,r){let i=e.resolve(t,n===void 0?void 0:{against:n});if(i===null){let e=n===void 0?`; for specs with alpha or auto-contrast, use paletteOver`:``;throw Error(`palette spec ${JSON.stringify(t)} did not resolve — check the spec string is valid and the variable exists${e}`)}return Ao(r,new J({color:K.fromRgba(i)}))}const Ko=/^[A-Za-z_][A-Za-z0-9_]*$/;function qo(e){let t={};for(let n of e.palette.vars.keys()){if(!Ko.test(n))continue;let r=n;t[r]={fn:(t=>Go(e,r,void 0,t)),argTypes:[`liftable`],returnType:`T`}}return t}function Jo(e){return{fn:((t,n)=>Go(e,t,void 0,n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Yo(e){return{fn:((t,n,r)=>Go(e,t,Wo(n),r)),argTypes:[`string`,`string`,`liftable`],returnType:`T`}}function Xo(e){return{fn:((t,n)=>Go(e,`auto`,Wo(t),n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Zo(e){return{...qo(e),palette:Jo(e),paletteOver:Yo(e),auto:Xo(e)}}function Qo(){return Ho()}new J({color:`red`,dim:!0});const $o={dark:`textual-dark`,light:`textual-light`};function es(e){return $o[e]??e}function ts(e,t){return e??t??`textual-dark`}function ns(){return Object.keys($o)}function rs(){return[...Bi(),...ns()]}const is=[`powerline`,`capsule`,`plain`];function as(e){return is.includes(e)}function os(e,t){let n=e??t??`powerline`;return as(n)?n:`powerline`}var ss=class extends Error{file;issues;constructor(e,t){super(us(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function Q(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=cs(e,n,i);if(t===-1)return r===void 0?void 0:ls(e,r);n=t,r=t}return r===void 0?void 0:ls(e,r)}function cs(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 ls(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function us(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(`
|
|
82
|
-
`)}function ds(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),r])}),null)}function fs(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),`default`])});return}return i}}function ps(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),r])});return}return i}}function ms(e,t,n){let r=ps(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:Q(e.source,[...t.split(`.`),`palette`])});return}return r}}function hs(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 ${vs(a)}`,line:Q(e.source,[...t.split(`.`),r])});return}return a}}function gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _s(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function vs(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function ys(e,t,n,r){return gs(r)?(xs(e,n,r,t.noun,new Set(Object.keys(t.fields))),bs(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${_s(r)}`,line:Q(e.source,n.split(`.`))}),null)}function bs(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 xs(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:Q(e.source,[...t.split(`.`),a])})}function Ss(e,t,n,r){if(!gs(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${_s(r)}`,line:Q(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:Q(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:Q(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:Q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Cs(e,t,n,r){if(!gs(r))return e.issues.push({path:n,message:`${n} must be an object, got ${_s(r)}`,line:Q(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${_s(i)}`,line:Q(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:Q(e.source,[...n.split(`.`),t.tag])}),null)}function ws(e){return(...t)=>e()(...t)}function Ts(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:Q(n.source,o.split(`.`))}),null}return a}}function Es(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ps(e,t,r,n)}}function Ds(){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 ${_s(i)}`,line:Q(e.source,[n])});return}return i}}}}function Os(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 ${vs(o)}`,line:Q(e.source,[i])});return}return o}}}}function ks(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ms(e,t,r)}}function As(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>ds(e,t,r,n)??void 0}}function js(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>hs(t,n,i,r,e)}}function Ms(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 Ns(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Ps(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Fs(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function Is(e,t=Yn){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??{}},helpers:{...t.helpers,...e.helpers??{}}}}const Ls={noun:`globals key`,fields:{default_bg:Es(),default_fg:Es(),default_empty_value:Es(),default_separator:Es(),default_truncate_marker:Es(),palette:ks(),style:js(is),autoWrap:Ds(),padding:Os({min:0,max:16})}};function Rs(e,t){return t===void 0?{}:ys(e,Ls,`globals`,t)??{}}function zs(e,t,n,r){return n.cache===void 0?(In.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${B.join(`, `)})`,line:Q(e.source,t.split(`.`))}),null):Gs(e,`${t}.cache`,n.cache)}function Bs(e,t,n){if(n.cache!==void 0)return Gs(e,`${t}.cache`,n.cache)??void 0}function Vs(e){return{required:!0,json:Js(),parse:(t,n,r,i)=>zs(t,n,i,e)??void 0}}function Hs(){return{required:!1,json:Js(),parse:(e,t,n,r)=>Bs(e,t,r)}}function Us(e,t,n){return e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))}),null}const Ws={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Xs(n)?{ttl:n}:Us(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${vs(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:Us(e,t,`cache.watch_file must be a non-empty path string, got ${vs(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}:Us(e,t,`cache.depends_on must be an array of variable-name strings, got ${vs(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Us(e,t,`cache.key must be a non-empty template string, got ${vs(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Us(e,t,`cache.never must be the literal boolean true, got ${vs(n)}`)}}};function Gs(e,t,n){return Ss(e,Ws,t,n)}const Ks={noun:`time-variable cache`,arms:{ttl:Ws.arms.ttl}};function qs(){return{required:!1,json:Fs(Ks),parse:(e,t,n,r)=>r.cache===void 0?void 0:Ss(e,Ks,`${t}.cache`,r.cache)??void 0}}function Js(){return Fs(Ws)}const Ys=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Xs(e){return Ys.test(e)}function Zs(e,t,n){if(n===void 0)return{};if(!gs(n))return e.issues.push({path:t,message:`${t} must be an object, got ${_s(n)}`,line:Q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Cs(e,dc,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Qs(){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 ${_s(i)}`,line:Q(e.source,t.split(`.`))});return}return i}}}function $s(){return{required:!0,json:{enum:[...Fn]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Fn.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Fn.join(`, `)}, got ${JSON.stringify(i)}`,line:Q(e.source,[...t.split(`.`),`field`])});return}return i}}}function ec(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return fs(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const tc={value:Qs(),default:Es()},nc={path:As(),type:js([`string`,`number`,`boolean`]),default:ec()},rc={name:As(),default:Es()},ic={path:As(),readMode:js([`whole`,`first-line`]),regex:Es(),cache:Vs(`file`),default:Es()},ac={command:As(),regex:Es(),cache:Vs(`shell`),default:Es()},oc={template:As(),cache:Hs(),default:Es()},sc={layout:As(),cache:qs(),default:Es()},cc={field:$s(),cache:Vs(`git`),default:Es()},lc={key:As(),default:Es()};function uc(e,t){return{json:Ns(Ms(t),`kind`,e),parse:(n,r,i)=>{let a=bs(n,t,r,i);return a===null?null:{kind:e,...a}}}}const dc={tag:`kind`,noun:`source kind`,arms:{literal:uc(`literal`,tc),input:uc(`input`,nc),env:uc(`env`,rc),file:uc(`file`,ic),shell:uc(`shell`,ac),template:uc(`template`,oc),time:uc(`time`,sc),git:uc(`git`,cc),state:uc(`state`,lc)}};function fc(){return Ps(dc)}function pc(){return{type:`object`,additionalProperties:fc()}}function mc(e,t){if(t===void 0)return{};if(!gs(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${_s(t)}`,line:Q(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=ys(e,_c,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function hc(){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 ${vs(i)}`,line:Q(e.source,[...t.split(`.`),n])})}}}}function gc(){return{required:!1,json:pc(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Zs(e,`${t}.${n}`,i)}}}const _c={noun:`segment key`,fields:{template:As(),width:hc(),justify:js(Ln),truncate:js(Rn),bg:Es(),fg:Es(),when:Es(),palette:ks(),vars:gc()}},vc={kind:`container`,direction:`vertical`,children:[]};function yc(e){return{required:!0,json:{const:e},parse:()=>e}}function bc(){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 ${vs(i)}`,line:Q(e.source,[`root`])}),``)}}}function xc(){return{required:!0,json:{enum:[...Mn]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Mn.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Mn.join(`, `)} (got ${JSON.stringify(i)})`,line:Q(e.source,[`root`])}),`vertical`)}}}function Sc(e){return{required:!0,json:{type:`array`,items:{$ref:`#/definitions/LayoutNode`}},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 ${_s(a)}`,line:Q(t.source,[`root`])}),[])}}}const Cc={noun:`layout-node key`,fields:{kind:yc(`segment`),name:bc(),when:Es()}},wc={noun:`layout-node key`,fields:{kind:yc(`container`),direction:xc(),children:Sc(ws(()=>kc)),when:Es()}};function Tc(){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 ${vs(i)}`,line:Q(e.source,[`root`])}),``)}}}const Ec={noun:`layout-node key`,fields:{seg:Tc(),when:Es()}},Dc={noun:`layout-node key`,fields:{h:Sc(ws(()=>kc)),when:Es()}},Oc={noun:`layout-node key`,fields:{v:Sc(ws(()=>kc)),when:Es()}},kc=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:Q(e.source,[`root`])}),vc):{kind:`segment`,name:n};if(!gs(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 ${_s(n)}`,line:Q(e.source,[`root`])}),vc;if(n.kind===`container`)return ys(e,wc,t,n)??vc;if(n.kind===`segment`)return ys(e,Cc,t,n)??vc;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
81
|
+
`)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${Rr(`(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=` ${Rr(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 K.fromRgba(t)}}})();var Do=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},Oo=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=$a,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],ee=[],te,w,ne,re;return class extends a{static{let ie=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)],te=[X.action],w=[X.action],ne=[X.action],re=[X.action],Oo(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:ie},c,l),Oo(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:ie},d,f),Oo(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:ie},m,h),Oo(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:ie},_,v),Oo(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:ie},b,x),Oo(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:ie},C,ee),Oo(this,null,te,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:ie},null,o),Oo(this,null,w,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:ie},null,o),Oo(this,null,ne,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:ie},null,o),Oo(this,null,re,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:ie},null,o),ie&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:ie})}id=Do(this,o);focusable=!0;#e=Do(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Do(this,l),Do(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Do(this,f),Do(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Do(this,h),Do(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Do(this,v),Do(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Do(this,x),Do(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Do(this,ee),!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=ko(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??Yi}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=ko(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 K.fromRgba(t)}}})();function ko(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 Ao(e,t){if(!(e instanceof Ca))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 jo(e){return{fn:(t=>Ao(t,e)),argTypes:[`liftable`],returnType:`T`}}function Mo(){let e={};for(let t of Object.keys(mi))e[t]=jo(new J({color:K.parse(t)}));return e}const No={fn:((e,t)=>{if(!Number.isInteger(e)||e<0||e>255)throw RangeError(`color index ${e} is out of range (0-255)`);return Ao(t,new J({color:K.fromAnsi(e)}))}),argTypes:[`int`,`liftable`],returnType:`T`},Po=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/,Fo={fn:((e,t)=>{if(!Po.test(e))throw RangeError(`hex expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return Ao(t,new J({color:K.parse(e)}))}),argTypes:[`string`,`liftable`],returnType:`T`},Io={fn:((e,t,n,r)=>Ao(r,new J({color:K.fromRgb(e,t,n)}))),argTypes:[`int`,`int`,`int`,`liftable`],returnType:`T`},Lo={fn:((e,t)=>Ao(t,new J({bgcolor:K.parse(e)}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ro(e,t){return new J({[e]:t})}function zo(){let e={};for(let t of ra)e[t]=jo(Ro(t,!0)),e[`not_${t}`]=jo(Ro(t,!1));for(let[t,n]of Object.entries(aa))e[t]=jo(Ro(n,!0));return e}const Bo={fn:((e,t)=>Ao(t,J.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Vo={fn:((e,t)=>Ao(t,new J({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ho(){return{...Mo(),color:No,hex:Fo,rgb:Io,on:Lo,...zo(),link:Vo,style:Bo}}const Uo=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;function Wo(e){if(!Uo.test(e))throw RangeError(`palette background expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return K.parse(e).getTruecolor()}function Go(e,t,n,r){let i=e.resolve(t,n===void 0?void 0:{against:n});if(i===null){let e=n===void 0?`; for specs with alpha or auto-contrast, use paletteOver`:``;throw Error(`palette spec ${JSON.stringify(t)} did not resolve — check the spec string is valid and the variable exists${e}`)}return Ao(r,new J({color:K.fromRgba(i)}))}const Ko=/^[A-Za-z_][A-Za-z0-9_]*$/;function qo(e){let t={};for(let n of e.palette.vars.keys()){if(!Ko.test(n))continue;let r=n;t[r]={fn:(t=>Go(e,r,void 0,t)),argTypes:[`liftable`],returnType:`T`}}return t}function Jo(e){return{fn:((t,n)=>Go(e,t,void 0,n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Yo(e){return{fn:((t,n,r)=>Go(e,t,Wo(n),r)),argTypes:[`string`,`string`,`liftable`],returnType:`T`}}function Xo(e){return{fn:((t,n)=>Go(e,`auto`,Wo(t),n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Zo(e){return{...qo(e),palette:Jo(e),paletteOver:Yo(e),auto:Xo(e)}}function Qo(){return Ho()}new J({color:`red`,dim:!0});const $o={dark:`textual-dark`,light:`textual-light`};function es(e){return $o[e]??e}function ts(e,t){return e??t??`textual-dark`}function ns(){return Object.keys($o)}function rs(){return[...Bi(),...ns()]}const is=[`powerline`,`capsule`,`plain`];function as(e){return is.includes(e)}function os(e,t){let n=e??t??`powerline`;return as(n)?n:`powerline`}const ss=[`unicode`,`ascii`];var cs=class extends Error{file;issues;constructor(e,t){super(ds(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function Q(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=ls(e,n,i);if(t===-1)return r===void 0?void 0:us(e,r);n=t,r=t}return r===void 0?void 0:us(e,r)}function ls(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 us(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function ds(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(`
|
|
82
|
+
`)}function fs(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 ${vs(i)}`,line:Q(e.source,[...t.split(`.`),r])}),null)}function ps(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 ${vs(i)}`,line:Q(e.source,[...t.split(`.`),`default`])});return}return i}}function ms(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 ${vs(i)}`,line:Q(e.source,[...t.split(`.`),r])});return}return i}}function hs(e,t,n){let r=ms(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:Q(e.source,[...t.split(`.`),`palette`])});return}return r}}function gs(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 ${ys(a)}`,line:Q(e.source,[...t.split(`.`),r])});return}return a}}function _s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vs(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ys(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function bs(e,t,n,r){return _s(r)?(Ss(e,n,r,t.noun,new Set(Object.keys(t.fields))),xs(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${vs(r)}`,line:Q(e.source,n.split(`.`))}),null)}function xs(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 Ss(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:Q(e.source,[...t.split(`.`),a])})}function Cs(e,t,n,r){if(!_s(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${vs(r)}`,line:Q(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:Q(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:Q(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:Q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function ws(e,t,n,r){if(!_s(r))return e.issues.push({path:n,message:`${n} must be an object, got ${vs(r)}`,line:Q(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${vs(i)}`,line:Q(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:Q(e.source,[...n.split(`.`),t.tag])}),null)}function Ts(e){return(...t)=>e()(...t)}function Es(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:Q(n.source,o.split(`.`))}),null}return a}}function Ds(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ms(e,t,r,n)}}function Os(){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 ${vs(i)}`,line:Q(e.source,[n])});return}return i}}}}function ks(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 ${ys(o)}`,line:Q(e.source,[i])});return}return o}}}}function As(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>hs(e,t,r)}}function js(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>fs(e,t,r,n)??void 0}}function Ms(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>gs(t,n,i,r,e)}}function Ns(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 Ps(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Fs(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Is(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function Ls(e,t=Yn){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??{}},helpers:{...t.helpers,...e.helpers??{}}}}const Rs={noun:`globals key`,fields:{default_bg:Ds(),default_fg:Ds(),default_empty_value:Ds(),default_separator:Ds(),default_truncate_marker:Ds(),palette:As(),style:Ms(is),autoWrap:Os(),padding:ks({min:0,max:16}),charset:Ms(ss)}};function zs(e,t){return t===void 0?{}:bs(e,Rs,`globals`,t)??{}}function Bs(e,t,n,r){return n.cache===void 0?(In.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${B.join(`, `)})`,line:Q(e.source,t.split(`.`))}),null):Ks(e,`${t}.cache`,n.cache)}function Vs(e,t,n){if(n.cache!==void 0)return Ks(e,`${t}.cache`,n.cache)??void 0}function Hs(e){return{required:!0,json:Ys(),parse:(t,n,r,i)=>Bs(t,n,i,e)??void 0}}function Us(){return{required:!1,json:Ys(),parse:(e,t,n,r)=>Vs(e,t,r)}}function Ws(e,t,n){return e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))}),null}const Gs={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Zs(n)?{ttl:n}:Ws(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${ys(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:Ws(e,t,`cache.watch_file must be a non-empty path string, got ${ys(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}:Ws(e,t,`cache.depends_on must be an array of variable-name strings, got ${ys(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Ws(e,t,`cache.key must be a non-empty template string, got ${ys(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Ws(e,t,`cache.never must be the literal boolean true, got ${ys(n)}`)}}};function Ks(e,t,n){return Cs(e,Gs,t,n)}const qs={noun:`time-variable cache`,arms:{ttl:Gs.arms.ttl}};function Js(){return{required:!1,json:Is(qs),parse:(e,t,n,r)=>r.cache===void 0?void 0:Cs(e,qs,`${t}.cache`,r.cache)??void 0}}function Ys(){return Is(Gs)}const Xs=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Zs(e){return Xs.test(e)}function Qs(e,t,n){if(n===void 0)return{};if(!_s(n))return e.issues.push({path:t,message:`${t} must be an object, got ${vs(n)}`,line:Q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=ws(e,fc,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function $s(){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 ${vs(i)}`,line:Q(e.source,t.split(`.`))});return}return i}}}function ec(){return{required:!0,json:{enum:[...Fn]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Fn.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Fn.join(`, `)}, got ${JSON.stringify(i)}`,line:Q(e.source,[...t.split(`.`),`field`])});return}return i}}}function tc(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return ps(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const nc={value:$s(),default:Ds()},rc={path:js(),type:Ms([`string`,`number`,`boolean`]),default:tc()},ic={name:js(),default:Ds()},ac={path:js(),readMode:Ms([`whole`,`first-line`]),regex:Ds(),cache:Hs(`file`),default:Ds()},oc={command:js(),regex:Ds(),cache:Hs(`shell`),default:Ds()},sc={template:js(),cache:Us(),default:Ds()},cc={layout:js(),cache:Js(),default:Ds()},lc={field:ec(),cache:Hs(`git`),default:Ds()},uc={key:js(),default:Ds()};function dc(e,t){return{json:Ps(Ns(t),`kind`,e),parse:(n,r,i)=>{let a=xs(n,t,r,i);return a===null?null:{kind:e,...a}}}}const fc={tag:`kind`,noun:`source kind`,arms:{literal:dc(`literal`,nc),input:dc(`input`,rc),env:dc(`env`,ic),file:dc(`file`,ac),shell:dc(`shell`,oc),template:dc(`template`,sc),time:dc(`time`,cc),git:dc(`git`,lc),state:dc(`state`,uc)}};function pc(){return Fs(fc)}function mc(){return{type:`object`,additionalProperties:pc()}}function hc(e,t){if(t===void 0)return{};if(!_s(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${vs(t)}`,line:Q(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=bs(e,vc,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function gc(){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 ${ys(i)}`,line:Q(e.source,[...t.split(`.`),n])})}}}}function _c(){return{required:!1,json:mc(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Qs(e,`${t}.${n}`,i)}}}const vc={noun:`segment key`,fields:{template:js(),width:gc(),justify:Ms(Ln),truncate:Ms(Rn),bg:Ds(),fg:Ds(),when:Ds(),palette:As(),vars:_c()}},yc={kind:`container`,direction:`vertical`,children:[]};function bc(e){return{required:!0,json:{const:e},parse:()=>e}}function xc(){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 ${ys(i)}`,line:Q(e.source,[`root`])}),``)}}}function Sc(){return{required:!0,json:{enum:[...Mn]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Mn.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Mn.join(`, `)} (got ${JSON.stringify(i)})`,line:Q(e.source,[`root`])}),`vertical`)}}}function Cc(e){return{required:!0,json:{type:`array`,items:{$ref:`#/definitions/LayoutNode`}},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 ${vs(a)}`,line:Q(t.source,[`root`])}),[])}}}const wc={noun:`layout-node key`,fields:{kind:bc(`segment`),name:xc(),when:Ds()}},Tc={noun:`layout-node key`,fields:{kind:bc(`container`),direction:Sc(),children:Cc(Ts(()=>Ac)),when:Ds()}};function Ec(){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 ${ys(i)}`,line:Q(e.source,[`root`])}),``)}}}const Dc={noun:`layout-node key`,fields:{seg:Ec(),when:Ds()}},Oc={noun:`layout-node key`,fields:{h:Cc(Ts(()=>Ac)),when:Ds()}},kc={noun:`layout-node key`,fields:{v:Cc(Ts(()=>Ac)),when:Ds()}},Ac=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:Q(e.source,[`root`])}),yc):{kind:`segment`,name:n};if(!_s(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 ${vs(n)}`,line:Q(e.source,[`root`])}),yc;if(n.kind===`container`)return bs(e,Tc,t,n)??yc;if(n.kind===`segment`)return bs(e,wc,t,n)??yc;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
83
83
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
84
|
-
New: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`root`])}),
|
|
84
|
+
New: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`root`])}),yc;if(n.kind===`group`){let r=bs(e,Lc,t,n);return r===null?yc:(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}),zc(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:Q(e.source,[`root`])}),yc}if(a){let r=bs(e,Dc,t,n);return r===null?yc:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=bs(e,Oc,t,n);return r===null?yc:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when}}}if(i){let r=bs(e,kc,t,n);return r===null?yc:{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:Q(e.source,[`root`])}),yc},jc=`groups.`,Mc=`closed`,Nc=/^[A-Za-z_][A-Za-z0-9_]*$/;function Pc(){return{required:!0,json:{type:`string`,pattern:Nc.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Nc.test(i)||i===Mc){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 "${Mc}", got ${ys(i)}`,line:Q(e.source,[`root`])});return}return i}}}function Fc(){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 ${ys(i)}`,line:Q(e.source,[`root`])});return}return i}}}}function Ic(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=fs(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:Q(e.source,[...t.split(`.`),n])});return}return i}}}}const Lc={noun:`layout-node key`,fields:{kind:bc(`group`),name:Pc(),label:Ic(),open:Os(),direction:Ms(Mn),key:Fc(),bg:Ds(),fg:Ds(),when:Ds(),children:Cc(Ts(()=>Ac))}};function Rc(e){return e.key??`groups.`+e.name}function zc(e){let t=jc+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 Bc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Vc(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,[`root`])})}function Hc(e,t){let n=e.groups;if(n.length===0)return;for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`groups.`)&&Vc(e,`${n}.${r}`,`"${r}" is in the reserved "${jc}" namespace (synthesized by group nodes) — rename it`);let r=new Set;for(let t of n)r.has(t.name)&&Vc(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}.`)&&Rc(t)===Rc(r)&&Vc(e,t.path,`group "${t.name}" shares key "${Rc(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=Rc(t);if(i.has(n)||i.set(n,Mc),t.open===!0){let r=i.get(n);r!==Mc&&Vc(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=jc+e.name,r=Rc(e),c=Bc(e.label),l=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,u=` `.repeat(l);a[t]={kind:`state`,key:r,default:i.get(r)},o[t]={set:r,cycle:[Mc,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 Uc=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?Xc(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Wc=class extends Uc{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Gc=class extends Uc{name=`EvalError`;kind=`EvalError`},Kc=class extends Gc{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Zc(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},qc=class extends Gc{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}},Jc=class extends Gc{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Yc=class extends Gc{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Xc(e,t){let n=e.split(`
|
|
85
85
|
`),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(`
|
|
86
|
-
`)}function
|
|
86
|
+
`)}function Zc(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Qc(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 Qc(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 $c(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const el=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`]]),tl={left:`{{`,right:`}}`};var nl=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=tl){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 Wc(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&&rl(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);rl(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);rl(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(;rl(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`;rl(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&&(al(e)||il(e)&&al(this.src[this.offset+1]??``)||e===`.`&&al(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&ul(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===`
|
|
87
87
|
`)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===`
|
|
88
|
-
`)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(
|
|
88
|
+
`)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(il(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);ol(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);sl(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);cl(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;al(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);al(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),il(this.src[this.offset]??``)&&this.advanceBy(1);al(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return ol(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);dl(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&ul(this.src[this.offset+1]??``);)for(this.advanceBy(1);dl(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),!ul(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;dl(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&ul(this.src[this.offset+1]??``);)for(this.advanceBy(1);dl(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(;dl(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=el.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===`
|
|
89
89
|
`)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
|
|
90
|
-
`?(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
|
|
91
|
-
`}function
|
|
92
|
-
`;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 Uc(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function wl(e,t,n){let r=Cl(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Uc(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function Tl(e,t){if(t(e)!==!1)for(let n of El(e))Tl(n,t)}function El(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return Qc(e)}}const Dl=Symbol(`go-template-js.MISSING`);function Ol(e,t){if(e==null)return Dl;if(e instanceof Map)return e.has(t)?e.get(t):Dl;if(Array.isArray(e))return Dl;if(typeof e==`object`){let n=e;return t in n?n[t]:Dl}return Dl}function kl(e,t){let n=e;for(let e of t){if(n===Dl)return Dl;n=Ol(n,e)}return n}function Al(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)=>Al(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)||!Al(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=>Al(e[n],t[n])):!1}return!1}const jl=new WeakSet;function Ml(e){return jl.add(e),e}function Nl(e){return jl.has(e)}function Pl(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 Fl(e){return{eq:{fn:(e,...t)=>t.some(t=>Rl(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!Rl(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>zl(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>zl(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>zl(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>zl(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>Bl(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Vl(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)=>Wl(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Wl(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>$l(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>ql(Wl(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>Xl(Wl(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>Ql(Wl(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!Pl(e),argTypes:[`truthy`]}}}function Il(){return{and:Ml({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Pl(t))return t;return t}}),or:Ml({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Pl(t))return t;return t}})}}function Ll(e){return{...Fl(e),...Il()}}function Rl(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Al(e,t)}function zl(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 Bl(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Vl(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${Hl(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 ${Hl(t)}`);return e[t]}throw Error(`index: cannot index ${Hl(e)}`)}function Hl(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Ul(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 Wl(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+=Gl(a,t),r=o}return n}function Gl(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Kl={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function ql(e){return e.replace(/[\0"'&<>]/g,e=>Kl[e]??e)}const Jl={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Yl=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Xl(e){let t=``;for(let n of e){let e=Jl[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Yl.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Zl=new TextEncoder;function Ql(e){let t=``,n=Zl.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 $l(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+=eu(c??``,l,u,n),a=s+1}return r}function eu(e,t,n,r){switch(e){case`s`:return typeof n==`string`?tu(t,n):tu(t,Gl(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Ul(n)}=${Gl(n,r)})`:tu(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return tu(t,nu(n));case`q`:return tu(t,JSON.stringify(Gl(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Ul(n)}=${Gl(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return tu(t,Number(n).toFixed(i))}case`t`:return tu(t,Pl(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 tu(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Ul(n)}=${Gl(n,r)})`:typeof n==`bigint`?tu(t,n.toString(16)):tu(t,Math.trunc(n).toString(16));default:return`%!${e}(${Ul(n)}=${Gl(n,r)})`}}function tu(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 nu(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(nu).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${nu(e)}:${nu(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(nu).join(` `)}}`:String(e)}function ru(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function iu(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function au(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 ou(e,t,n){e.vars.set(t,n)}const su=new Set([`default`,`zero`,`error`]);function cu(e){if(e===void 0)return`default`;if(su.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${lu(e)}`)}function lu(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 uu(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${lu(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${lu(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${lu(e.right)}`);return{left:e.left,right:e.right}}}const du=Object.freeze({kind:`break`}),fu=Object.freeze({kind:`continue`}),pu={kind:`none`};let mu;(class e{source;_evaluate;_referencedFunctions;_referencedCalls;constructor(e,t,n,r){this.source=e,this._evaluate=t,this._referencedFunctions=n,this._referencedCalls=r}static{mu=(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 hu(e){let t=new Set,n=e=>{Tl(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}function gu(e){let t=[],n=e=>{Tl(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];n===void 0||n.type!==`Identifier`||t.push({name:n.ident,args:e.args.slice(1).map(e=>e.type===`String`?e.value:null)})})};n(e.root);for(let t of e.defines.values())n(t);return t}var _u=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??Eu,this.missingKey=cu(e.missingKey),this.delims=uu(e.delims),this.funcs={...Ll(this.toString),...e.funcs??{}}}parse(e){let t=dl(e,this.delims);return mu(t.source,e=>this.evalParsed(t,e),hu(t),gu(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=ru(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 du;case`Continue`:throw fu;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 Wc(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Qc(e)}}evalIf(e,t,n){Pl(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(Pl(r)){let i=iu(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=Pu(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=iu(t,o);if(i.length===1)ou(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;ou(a,e,r),ou(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===fu)continue;throw e}}}catch(e){if(e===du)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Wc(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=iu(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=iu(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 Wc(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,pu);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)ou(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 Wc(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Wc(`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 Gc(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Nl(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)}Su(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 Kc?new Kc(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof Jc?new Jc(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 Lu(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 Gc(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return Su(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 Wc(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=kl(e,t);if(i!==Dl)return i;if(this.missingKey===`error`)throw new qc(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=au(t,i);if(!a.found)throw new Wc(`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(vu(e)));return}if(e instanceof Map){t.out.push(this.fromString(yu(e)));return}t.out.push(e)}};function vu(e){return`[${e.map(bu).join(` `)}]`}function yu(e){let t=[];for(let[n,r]of e)t.push(`${bu(n)}:${bu(r)}`);return`map[${t.join(` `)}]`}function bu(e){return e==null?`<nil>`:Array.isArray(e)?vu(e):e instanceof Map?yu(e):String(e)}function xu(e){return new _u(e)}function Su(e,t,n,r,i,a=Eu,o,s=Tu){let c=Cu(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!wu(o,d,a))throw new Kc(e,t+1,Mu(o),Nu(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(!ku(n[l],d))throw new Kc(e,t+1,`${Mu(`ordered`)} of the same kind as ${Nu(n[l])}`,Nu(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!Au(n[u],d))throw new Kc(e,t+1,`${Mu(`comparable`)} of the same kind as ${Nu(n[u])}`,Nu(d),r,{source:i})}}}function Cu(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 wu(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 Du(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||Du(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||Du(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||Du(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 Ou(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function Tu(e){return e}function Eu(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new Kc(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Nu(e),{line:0,column:0,offset:0})}function Du(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 Ou(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function ku(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Au(e,t){let n=ju(e),r=ju(t);return n===`nil`||r===`nil`?!0:n===r}function ju(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 Mu(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 Nu(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Pu(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?Fu([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Fu(Object.entries(e)):[]}function Fu(e){return[...e].sort((e,t)=>Iu(e[0],t[0]))}function Iu(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 Lu(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 Ru(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function zu(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 Bu(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 Vu(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=Bu(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 Hu(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Bu(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 Uu(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 Wu(e){return JSON.stringify(e)??`null`}function Gu(e){return typeof e==`string`?e:nu(e)}function Ku(e){return e.map(Gu)}function qu(){return{atoi:{fn:e=>Ru(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Vu(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>Hu(e),argTypes:[`value`]},float64:{fn:e=>zu(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Gu(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>Ku(e),argTypes:[`list`]},toDecimal:{fn:e=>Uu(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>Wu(e),argTypes:[`serializable`],returnType:`string`}}}const Ju={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Yu(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*Ju[a],n=n.slice(e[0].length)}return t?-r:r}function Xu(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Ju.us?`${Math.floor(n)}ns`:n<Ju.ms?Zu(n,Ju.us,3,`µs`):n<Ju.s?Zu(n,Ju.ms,6,`ms`):Qu(n),t?`-${r}`:r}function Zu(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 Qu(e){let t=Math.floor(e/Ju.h);e-=t*Ju.h;let n=Math.floor(e/Ju.m);e-=n*Ju.m;let r=Math.floor(e/Ju.s),i=e-r*Ju.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 $u(e){return e*Ju.s}function ed(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 td(e,t){let n=t().getTime()-ed(e).getTime();return Xu(Math.round(n/1e3)*1e9)}const nd=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],rd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],id=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],ad=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function od(e){return e<10?`0${e}`:String(e)}function sd(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function cd(e){return e<10?` ${e}`:String(e)}function ld(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${od(Math.floor(n/60))}${od(n%60)}`}function ud(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${od(Math.floor(n/60))}:${od(n%60)}`}function dd(e){return`${e>=0?`+`:`-`}${od(Math.floor(Math.abs(e)/60))}`}function fd(e){return e===0?`Z`:ld(e)}function pd(e){return e===0?`Z`:ud(e)}function md(e){return e===0?`Z`:dd(e)}function hd(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const gd=[[`.000000000`,e=>`.${hd(e.ms,9,!1)}`],[`.999999999`,e=>{let t=hd(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${hd(e.ms,6,!1)}`],[`.999999`,e=>{let t=hd(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${sd(e.ms)}`],[`.999`,e=>{let t=sd(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>nd[e.month-1]??`January`],[`Monday`,e=>id[e.weekday]??`Monday`],[`Z07:00`,e=>pd(e.offsetMinutes)],[`-07:00`,e=>ud(e.offsetMinutes)],[`Z0700`,e=>fd(e.offsetMinutes)],[`-0700`,e=>ld(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>rd[e.month-1]??`Jan`],[`Mon`,e=>ad[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>dd(e.offsetMinutes)],[`Z07`,e=>md(e.offsetMinutes)],[`15`,e=>od(e.hour)],[`01`,e=>od(e.month)],[`02`,e=>od(e.day)],[`_2`,e=>cd(e.day)],[`03`,e=>od(e.hour12)],[`04`,e=>od(e.minute)],[`05`,e=>od(e.second)],[`06`,e=>od(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 _d(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of gd)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const vd={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function yd(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const bd=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function xd(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=yd(new Intl.DateTimeFormat(`en-US`,{...vd,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=yd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=Sd(yd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=bd.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 Sd(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 Cd(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function wd(e,t){return _d(e,xd(ed(t),Cd()))}function Td(e,t,n){return _d(e,xd(ed(t),n))}function Ed(e,t){let n=ed(t),r=Yu(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function Dd(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Xu($u(t))}return typeof e==`bigint`?Xu($u(Number(e))):typeof e==`number`?Xu($u(e)):`0s`}const Od=36e11*24*365,kd=36e11*24*30,Ad=36e11*24,jd=36e11,Md=6e10,Nd=1e9;function Pd(e){let t=Yu(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>Od?`${Math.floor(n/Od)}y`:n>kd?`${Math.floor(n/kd)}mo`:n>Ad?`${Math.floor(n/Ad)}d`:n>jd?`${Math.floor(n/jd)}h`:n>Md?`${Math.floor(n/Md)}m`:n>Nd?`${Math.floor(n/Nd)}s`:`0s`}function Fd(e){let t=xd(ed(e),Cd());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Id(e,t){let n=xd(ed(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Ld(e){return e()}const Rd=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],zd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Bd(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Vd(e,t,n){return[e.slice(t,t+n),t+n]}function Hd(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 Ud(e,t){for(let[n,r]of Rd.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function Wd(e,t){for(let[n,r]of zd.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Gd(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function Kd(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function qd(e,t){if(e[t]===` `){let[n,r]=Hd(e,t+1,1,1);return[n,r]}return Hd(e,t,1,2)}function Jd(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=Hd(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=Hd(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=Hd(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Yd(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]=Hd(e,t+1,2,2);return[n*r*60,i]}return Jd(e,t,n)}function Xd(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 Zd(e,t,n){let[r,i]=Vd(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function Qd(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Ud(t,n);return i.month=e,[r,i]}case`Monday`:return[Gd(t,n),i];case`Jan`:{let[e,r]=Wd(t,n);return i.month=e,[r,i]}case`Mon`:return[Kd(t,n),i];case`2006`:{let[e,r]=Hd(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=Hd(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=Hd(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=Hd(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=qd(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=Hd(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=Hd(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=Hd(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=Hd(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=Hd(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=Hd(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=Hd(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=Hd(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=Hd(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[Xd(t,n),i];case`-0700`:{let[e,r]=Jd(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=Jd(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=Hd(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Yd(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Yd(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Yd(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]=Zd(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]=Zd(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]=Zd(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 $d=`.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 ef(e,t){let n=0,r=0,i=Bd();for(;n<e.length;){let a=!1;for(let o of $d)if(e.startsWith(o,n)){let[e,s]=Qd(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 tf(e,t){return ef(e,t)}function nf(e){return String(Math.floor(ed(e).getTime()/1e3))}function rf(e=()=>new Date){return{now:{fn:()=>Ld(e),argTypes:[]},date:{fn:(e,t)=>wd(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>Td(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>Ed(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>Fd(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>Id(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>Dd(e),argTypes:[`value`]},durationRound:{fn:e=>Pd(e),argTypes:[`value`]},toDate:{fn:(e,t)=>tf(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>td(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>nf(e),argTypes:[`value`]}}}function af(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 of(...e){for(let t of e)if(!af(t))return t}function sf(e,t){return af(t)?e:t}function cf(e){return JSON.parse(e)}function lf(e,t,n){return Pl(n)?e:t}function uf(e){return JSON.stringify(e)??`null`}function df(e){return JSON.stringify(e,null,2)??`null`}function ff(){return{default:{fn:(e,t)=>sf(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>af(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>of(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>lf(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>cf(e),argTypes:[`string`]},toJson:{fn:e=>uf(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>df(e),argTypes:[`serializable`],returnType:`string`}}}function pf(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function mf(e,t){return e[t]}function hf(e,t){return t in e}function gf(e){return Object.keys(e)}function _f(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 vf(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function yf(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 bf(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function xf(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function Sf(e,t,n){return e[t]=n,e}function Cf(e,t){return delete e[t],e}function wf(e){return Object.values(e)}function Tf(){return{dict:{fn:(...e)=>pf(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>mf(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>Sf(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>Cf(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>gf(e),argTypes:[`dict`]},values:{fn:e=>wf(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>xf(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>bf(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>yf(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>hf(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>_f(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>vf(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 Ef(...e){for(let t of e)if(af(t))return!1;return!0}function Df(...e){for(let t of e)if(!af(t))return!0;return!1}function Of(e,t){return[...e,t]}function kf(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 Af(e){return e.filter(e=>!af(e))}function jf(...e){let t=[];for(let n of e)t.push(...n);return t}const Mf={line:0,column:0,offset:0};function Nf(e,t,n,r){return new Kc(e,t,n,r,Mf)}function Pf(...e){if(e.length<3)throw Nf(`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(!If(t))throw Nf(`dig`,e.length-1,`dict`,Lf(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Nf(`dig`,e,`string`,Lf(r[e]));return Ff(t,n,r,e.length)}function Ff(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(!If(a))throw Nf(`dig`,r-1,`dict at intermediate key`,Lf(a));return Ff(a,t,n.slice(1),r)}function If(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Lf(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Rf(e){return e[0]}function zf(e,t){return t.some(t=>Al(t,e))}function Bf(e){return e.slice(0,-1)}function Vf(e){return e[e.length-1]}function Hf(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Uf(...e){return e}function Wf(e,t){return[t,...e]}function Gf(e){return e.slice(1)}function Kf(e){return[...e].reverse()}function qf(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Jf(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Yf(e){let t=[];for(let n of e)t.some(e=>Al(e,n))||t.push(n);return t}function Xf(e,...t){return e.filter(e=>!t.some(t=>Al(t,e)))}function Zf(){return{list:{fn:(...e)=>Uf(...e),argTypes:[`value`]},first:{fn:e=>Rf(e),argTypes:[`list`]},last:{fn:e=>Vf(e),argTypes:[`list`]},rest:{fn:e=>Gf(e),argTypes:[`list`]},initial:{fn:e=>Bf(e),argTypes:[`list`]},len:{fn:e=>Hf(e),argTypes:[`sized`]},reverse:{fn:e=>Kf(e),argTypes:[`list`]},uniq:{fn:e=>Yf(e),argTypes:[`list`]},without:{fn:(e,...t)=>Xf(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>zf(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>Af(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>qf(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>jf(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>kf(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>Wf(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>Of(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>Jf(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>Of(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>Uf(...e),argTypes:[`value`]},dig:{fn:(...e)=>Pf(...e),argTypes:[`value`]},all:{fn:(...e)=>Ef(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>Df(...e),argTypes:[`truthy`],returnType:`bool`}}}function Qf(...e){return e.reduce((e,t)=>e+t,0)}function $f(e){return e+1}function ep(e){return e+1}function tp(...e){return e.reduce((e,t)=>e+t,0)}function np(e){return Math.ceil(e)}function rp(e,t){return Math.trunc(e/t)}function ip(e,t){return e/t}function ap(e){return Math.floor(e)}function op(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function sp(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function cp(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function lp(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function up(e,t){return e%t}function dp(...e){return e.reduce((e,t)=>e*t,1)}function fp(...e){return e.reduce((e,t)=>e*t,1)}function pp(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function mp(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 hp(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),mp(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return mp(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:mp(n,i+t,r).join(` `)}default:return``}}function gp(e,t){return e-t}function _p(e,t){return e-t}function vp(e){return mp(0,e,e<0?-1:1)}function yp(){return{add:{fn:(...e)=>Qf(...e),argTypes:[`int`]},sub:{fn:(e,t)=>gp(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>dp(...e),argTypes:[`int`]},div:{fn:(e,t)=>rp(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>up(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>cp(...e),argTypes:[`int`]},max:{fn:(...e)=>op(...e),argTypes:[`int`]},floor:{fn:e=>ap(e),argTypes:[`float`]},ceil:{fn:e=>np(e),argTypes:[`float`]},round:{fn:(e,t)=>pp(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>tp(...e),argTypes:[`float`]},subf:{fn:(e,t)=>_p(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>fp(...e),argTypes:[`float`]},divf:{fn:(e,t)=>ip(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>$f(e),argTypes:[`int`]},add1f:{fn:e=>ep(e),argTypes:[`float`]},maxf:{fn:(...e)=>sp(...e),argTypes:[`float`]},minf:{fn:(...e)=>lp(...e),argTypes:[`float`]},biggest:{fn:(...e)=>op(...e),argTypes:[`int`]},seq:{fn:(...e)=>hp(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>vp(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>mp(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function bp(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function xp(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const $={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},Sp=/^[-_\s]$/,Cp=/^\p{P}$/u,wp=/^\p{L}$/u,Tp=/^\p{Lu}$/u,Ep=/^\p{N}$/u;function Dp(e){return e!==void 0&&Sp.test(e)}function Op(e){return e!==void 0&&wp.test(e)}function kp(e){return e!==void 0&&Tp.test(e)}function Ap(e){return e!==void 0&&Ep.test(e)}function jp(e){return e!==void 0&&Cp.test(e)}function Mp(e,t){if(t>=e.length)return{word:{wt:$.Invalid,text:``},next:t};let n=e[t],r=t+1;if(Dp(n)){for(;r<e.length&&Dp(e[r]);)r++;return{word:{wt:$.Connector,text:e.slice(t,r).join(``)},next:r}}if(jp(n)){for(;r<e.length&&jp(e[r]);)r++;return{word:{wt:$.Punct,text:e.slice(t,r).join(``)},next:r}}if(kp(n)){if(r>=e.length)return{word:{wt:$.UpperCase,text:n},next:r};if(kp(e[r])){let n=r;for(;n<e.length&&kp(e[n]);)n++;return n<e.length&&Op(e[n])?{word:{wt:$.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(Op(e[r])){let n=r+1;for(;n<e.length&&Op(e[n])&&!kp(e[n]);)n++;return{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:$.UpperCase,text:n},next:r}}if(Op(n)){for(;r<e.length&&Op(e[r])&&!kp(e[r]);)r++;return{word:{wt:$.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(Ap(n)){for(;r<e.length&&Ap(e[r]);)r++;return{word:{wt:$.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!Dp(e[r])&&!Op(e[r])&&!Ap(e[r])&&!jp(e[r]);)r++;return{word:{wt:$.Other,text:e.slice(t,r).join(``)},next:r}}function Np(e,t,n){if(t.wt!==$.UpperCase&&t.wt!==$.Connector){e.push(t.text);return}for(let r of t.text)Dp(r)?e.push(n):kp(r)?e.push(r.toLowerCase()):e.push(r)}function Pp(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=Mp(n,0);for(;a<n.length;){i.wt!==$.Connector&&Np(r,i,t);let e=i,o=i;if({word:i,next:a}=Mp(n,a),e.wt===$.Number){for(;i.wt===$.Alphabet||i.wt===$.Number;)Np(r,i,t),{word:i,next:a}=Mp(n,a);i.wt!==$.Invalid&&i.wt!==$.Punct&&i.wt!==$.Connector&&r.push(t);continue}if(e.wt===$.Connector){Np(r,o,t);continue}if(e.wt===$.Punct)continue;if(i.wt!==$.Number){i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=Mp(n,a),i.wt!==$.Alphabet){Np(r,s,t),i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}for(r.push(t),Np(r,s,t);i.wt===$.Alphabet||i.wt===$.Number;)Np(r,i,t),{word:i,next:a}=Mp(n,a);i.wt!==$.Invalid&&i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t)}return Np(r,i,t),r.join(``).toLowerCase()}function Fp(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!Dp(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++,Dp(i)&&Dp(e)){n.push(e);continue}Dp(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Ip(e){return Fp(e)}function Lp(...e){return e.join(` `)}function Rp(e,t){return t.includes(e)}function zp(e,t){return t.startsWith(e)}function Bp(e,t){return t.endsWith(e)}function Vp(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
90
|
+
`?(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 rl(e){return e===` `||e===` `||e===`\r`||e===`
|
|
91
|
+
`}function il(e){return e===`+`||e===`-`}function al(e){return e>=`0`&&e<=`9`}function ol(e){return al(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function sl(e){return e>=`0`&&e<=`7`}function cl(e){return e===`0`||e===`1`}function ll(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function ul(e){return ll(e)||e===`_`}function dl(e){return ul(e)||al(e)}function fl(e,t){return new pl(e,t).parseTemplate()}var pl=class{lex;buf=[];defines=new Map;source;rangeDepth=0;constructor(e,t){this.source=e,this.lex=t?new nl(e,t):new nl(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:gl(n)});return n}errAt(e,t,n={}){return new Wc(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 ${gl(e)}`,{found:gl(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=hl(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 ml(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${gl(n)} at top level`,{found:gl(n)})}return ml(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 Wc(`{{${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 Wc(`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:gl(e)});return wl(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(!_l(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:gl(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=[vl(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(vl(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;_l(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 vl(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:wl(e.value,e.pos,this.source)};case`Number`:return bl(e);case`Char`:return xl(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 ${gl(e)}`,{expected:`command argument`,found:gl(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 ml(e,t){return{type:`List`,pos:e,nodes:t}}function hl(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function gl(e){return e.type===`EOF`?`end of input`:e.value||e.type}function _l(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 vl(e){return{type:`Variable`,pos:e.pos,idents:yl(e.value)}}function yl(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function bl(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=Sl(i);return{...s,intValue:e}}if(a){let e=Cl(i);return{...s,floatValue:e}}let c=Cl(i);return{...s,complexValue:[0,c]}}function xl(e,t){let n=Tl(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 Sl(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 Cl(e){return Number(e)}function wl(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+=`
|
|
92
|
+
`;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 Wc(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Tl(e,t,n){let r=wl(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Wc(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function El(e,t){if(t(e)!==!1)for(let n of Dl(e))El(n,t)}function Dl(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return $c(e)}}const Ol=Symbol(`go-template-js.MISSING`);function kl(e,t){if(e==null)return Ol;if(e instanceof Map)return e.has(t)?e.get(t):Ol;if(Array.isArray(e))return Ol;if(typeof e==`object`){let n=e;return t in n?n[t]:Ol}return Ol}function Al(e,t){let n=e;for(let e of t){if(n===Ol)return Ol;n=kl(n,e)}return n}function jl(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)=>jl(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)||!jl(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=>jl(e[n],t[n])):!1}return!1}const Ml=new WeakSet;function Nl(e){return Ml.add(e),e}function Pl(e){return Ml.has(e)}function Fl(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 Il(e){return{eq:{fn:(e,...t)=>t.some(t=>zl(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!zl(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>Bl(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>Bl(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>Bl(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>Bl(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>Vl(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Hl(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)=>Gl(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Gl(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>eu(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>Jl(Gl(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>Zl(Gl(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>$l(Gl(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!Fl(e),argTypes:[`truthy`]}}}function Ll(){return{and:Nl({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Fl(t))return t;return t}}),or:Nl({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Fl(t))return t;return t}})}}function Rl(e){return{...Il(e),...Ll()}}function zl(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):jl(e,t)}function Bl(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 Vl(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Hl(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${Ul(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 ${Ul(t)}`);return e[t]}throw Error(`index: cannot index ${Ul(e)}`)}function Ul(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Wl(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 Gl(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+=Kl(a,t),r=o}return n}function Kl(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const ql={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function Jl(e){return e.replace(/[\0"'&<>]/g,e=>ql[e]??e)}const Yl={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Xl=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Zl(e){let t=``;for(let n of e){let e=Yl[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Xl.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Ql=new TextEncoder;function $l(e){let t=``,n=Ql.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 eu(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+=tu(c??``,l,u,n),a=s+1}return r}function tu(e,t,n,r){switch(e){case`s`:return typeof n==`string`?nu(t,n):nu(t,Kl(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Wl(n)}=${Kl(n,r)})`:nu(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return nu(t,ru(n));case`q`:return nu(t,JSON.stringify(Kl(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Wl(n)}=${Kl(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return nu(t,Number(n).toFixed(i))}case`t`:return nu(t,Fl(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 nu(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Wl(n)}=${Kl(n,r)})`:typeof n==`bigint`?nu(t,n.toString(16)):nu(t,Math.trunc(n).toString(16));default:return`%!${e}(${Wl(n)}=${Kl(n,r)})`}}function nu(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 ru(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(ru).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${ru(e)}:${ru(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(ru).join(` `)}}`:String(e)}function iu(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function au(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function ou(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 su(e,t,n){e.vars.set(t,n)}const cu=new Set([`default`,`zero`,`error`]);function lu(e){if(e===void 0)return`default`;if(cu.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${uu(e)}`)}function uu(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 du(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${uu(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${uu(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${uu(e.right)}`);return{left:e.left,right:e.right}}}const fu=Object.freeze({kind:`break`}),pu=Object.freeze({kind:`continue`}),mu={kind:`none`};let hu;(class e{source;_evaluate;_referencedFunctions;_referencedCalls;constructor(e,t,n,r){this.source=e,this._evaluate=t,this._referencedFunctions=n,this._referencedCalls=r}static{hu=(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 gu(e){let t=new Set,n=e=>{El(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}function _u(e){let t=[],n=e=>{El(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];n===void 0||n.type!==`Identifier`||t.push({name:n.ident,args:e.args.slice(1).map(e=>e.type===`String`?e.value:null)})})};n(e.root);for(let t of e.defines.values())n(t);return t}var vu=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??Du,this.missingKey=lu(e.missingKey),this.delims=du(e.delims),this.funcs={...Rl(this.toString),...e.funcs??{}}}parse(e){let t=fl(e,this.delims);return hu(t.source,e=>this.evalParsed(t,e),gu(t),_u(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=iu(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 fu;case`Continue`:throw pu;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 Gc(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:$c(e)}}evalIf(e,t,n){Fl(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(Fl(r)){let i=au(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=Fu(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=au(t,o);if(i.length===1)su(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;su(a,e,r),su(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===pu)continue;throw e}}}catch(e){if(e===fu)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Gc(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=au(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=au(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 Gc(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,mu);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)su(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 Gc(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Gc(`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 Kc(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Pl(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)}Cu(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 qc?new qc(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof Yc?new Yc(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 Ru(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 Kc(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return Cu(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 Gc(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Al(e,t);if(i!==Ol)return i;if(this.missingKey===`error`)throw new Jc(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=ou(t,i);if(!a.found)throw new Gc(`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(yu(e)));return}if(e instanceof Map){t.out.push(this.fromString(bu(e)));return}t.out.push(e)}};function yu(e){return`[${e.map(xu).join(` `)}]`}function bu(e){let t=[];for(let[n,r]of e)t.push(`${xu(n)}:${xu(r)}`);return`map[${t.join(` `)}]`}function xu(e){return e==null?`<nil>`:Array.isArray(e)?yu(e):e instanceof Map?bu(e):String(e)}function Su(e){return new vu(e)}function Cu(e,t,n,r,i,a=Du,o,s=Eu){let c=wu(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!Tu(o,d,a))throw new qc(e,t+1,Nu(o),Pu(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(!Au(n[l],d))throw new qc(e,t+1,`${Nu(`ordered`)} of the same kind as ${Pu(n[l])}`,Pu(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!ju(n[u],d))throw new qc(e,t+1,`${Nu(`comparable`)} of the same kind as ${Pu(n[u])}`,Pu(d),r,{source:i})}}}function wu(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 Tu(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 Ou(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||Ou(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||Ou(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||Ou(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 ku(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function Eu(e){return e}function Du(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 qc(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Pu(e),{line:0,column:0,offset:0})}function Ou(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 ku(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Au(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function ju(e,t){let n=Mu(e),r=Mu(t);return n===`nil`||r===`nil`?!0:n===r}function Mu(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 Nu(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 Pu(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Fu(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?Iu([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Iu(Object.entries(e)):[]}function Iu(e){return[...e].sort((e,t)=>Lu(e[0],t[0]))}function Lu(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 Ru(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 zu(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Bu(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 Vu(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 Hu(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=Vu(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 Uu(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Vu(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 Wu(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 Gu(e){return JSON.stringify(e)??`null`}function Ku(e){return typeof e==`string`?e:ru(e)}function qu(e){return e.map(Ku)}function Ju(){return{atoi:{fn:e=>zu(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Hu(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>Uu(e),argTypes:[`value`]},float64:{fn:e=>Bu(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Ku(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>qu(e),argTypes:[`list`]},toDecimal:{fn:e=>Wu(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>Gu(e),argTypes:[`serializable`],returnType:`string`}}}const Yu={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Xu(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*Yu[a],n=n.slice(e[0].length)}return t?-r:r}function Zu(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Yu.us?`${Math.floor(n)}ns`:n<Yu.ms?Qu(n,Yu.us,3,`µs`):n<Yu.s?Qu(n,Yu.ms,6,`ms`):$u(n),t?`-${r}`:r}function Qu(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 $u(e){let t=Math.floor(e/Yu.h);e-=t*Yu.h;let n=Math.floor(e/Yu.m);e-=n*Yu.m;let r=Math.floor(e/Yu.s),i=e-r*Yu.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 ed(e){return e*Yu.s}function td(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 nd(e,t){let n=t().getTime()-td(e).getTime();return Zu(Math.round(n/1e3)*1e9)}const rd=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],id=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],ad=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],od=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function sd(e){return e<10?`0${e}`:String(e)}function cd(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function ld(e){return e<10?` ${e}`:String(e)}function ud(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${sd(Math.floor(n/60))}${sd(n%60)}`}function dd(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${sd(Math.floor(n/60))}:${sd(n%60)}`}function fd(e){return`${e>=0?`+`:`-`}${sd(Math.floor(Math.abs(e)/60))}`}function pd(e){return e===0?`Z`:ud(e)}function md(e){return e===0?`Z`:dd(e)}function hd(e){return e===0?`Z`:fd(e)}function gd(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const _d=[[`.000000000`,e=>`.${gd(e.ms,9,!1)}`],[`.999999999`,e=>{let t=gd(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${gd(e.ms,6,!1)}`],[`.999999`,e=>{let t=gd(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${cd(e.ms)}`],[`.999`,e=>{let t=cd(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>rd[e.month-1]??`January`],[`Monday`,e=>ad[e.weekday]??`Monday`],[`Z07:00`,e=>md(e.offsetMinutes)],[`-07:00`,e=>dd(e.offsetMinutes)],[`Z0700`,e=>pd(e.offsetMinutes)],[`-0700`,e=>ud(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>id[e.month-1]??`Jan`],[`Mon`,e=>od[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>fd(e.offsetMinutes)],[`Z07`,e=>hd(e.offsetMinutes)],[`15`,e=>sd(e.hour)],[`01`,e=>sd(e.month)],[`02`,e=>sd(e.day)],[`_2`,e=>ld(e.day)],[`03`,e=>sd(e.hour12)],[`04`,e=>sd(e.minute)],[`05`,e=>sd(e.second)],[`06`,e=>sd(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 vd(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of _d)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const yd={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function bd(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const xd=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Sd(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=bd(new Intl.DateTimeFormat(`en-US`,{...yd,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=bd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=Cd(bd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=xd.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 Cd(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 wd(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function Td(e,t){return vd(e,Sd(td(t),wd()))}function Ed(e,t,n){return vd(e,Sd(td(t),n))}function Dd(e,t){let n=td(t),r=Xu(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function Od(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Zu(ed(t))}return typeof e==`bigint`?Zu(ed(Number(e))):typeof e==`number`?Zu(ed(e)):`0s`}const kd=36e11*24*365,Ad=36e11*24*30,jd=36e11*24,Md=36e11,Nd=6e10,Pd=1e9;function Fd(e){let t=Xu(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>kd?`${Math.floor(n/kd)}y`:n>Ad?`${Math.floor(n/Ad)}mo`:n>jd?`${Math.floor(n/jd)}d`:n>Md?`${Math.floor(n/Md)}h`:n>Nd?`${Math.floor(n/Nd)}m`:n>Pd?`${Math.floor(n/Pd)}s`:`0s`}function Id(e){let t=Sd(td(e),wd());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Ld(e,t){let n=Sd(td(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Rd(e){return e()}const zd=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Bd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Vd(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Hd(e,t,n){return[e.slice(t,t+n),t+n]}function Ud(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 Wd(e,t){for(let[n,r]of zd.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function Gd(e,t){for(let[n,r]of Bd.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Kd(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 qd(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 Jd(e,t){if(e[t]===` `){let[n,r]=Ud(e,t+1,1,1);return[n,r]}return Ud(e,t,1,2)}function Yd(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]=Ud(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=Ud(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=Ud(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Xd(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]=Ud(e,t+1,2,2);return[n*r*60,i]}return Yd(e,t,n)}function Zd(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 Qd(e,t,n){let[r,i]=Hd(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function $d(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Wd(t,n);return i.month=e,[r,i]}case`Monday`:return[Kd(t,n),i];case`Jan`:{let[e,r]=Gd(t,n);return i.month=e,[r,i]}case`Mon`:return[qd(t,n),i];case`2006`:{let[e,r]=Ud(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=Ud(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=Ud(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=Ud(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=Jd(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=Ud(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=Ud(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=Ud(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=Ud(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=Ud(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=Ud(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=Ud(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=Ud(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=Ud(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[Zd(t,n),i];case`-0700`:{let[e,r]=Yd(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=Yd(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]=Ud(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Xd(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Xd(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Xd(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]=Qd(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]=Qd(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]=Qd(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 ef=`.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 tf(e,t){let n=0,r=0,i=Vd();for(;n<e.length;){let a=!1;for(let o of ef)if(e.startsWith(o,n)){let[e,s]=$d(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 nf(e,t){return tf(e,t)}function rf(e){return String(Math.floor(td(e).getTime()/1e3))}function af(e=()=>new Date){return{now:{fn:()=>Rd(e),argTypes:[]},date:{fn:(e,t)=>Td(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>Ed(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>Dd(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>Id(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>Ld(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>Od(e),argTypes:[`value`]},durationRound:{fn:e=>Fd(e),argTypes:[`value`]},toDate:{fn:(e,t)=>nf(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>nd(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>rf(e),argTypes:[`value`]}}}function of(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 sf(...e){for(let t of e)if(!of(t))return t}function cf(e,t){return of(t)?e:t}function lf(e){return JSON.parse(e)}function uf(e,t,n){return Fl(n)?e:t}function df(e){return JSON.stringify(e)??`null`}function ff(e){return JSON.stringify(e,null,2)??`null`}function pf(){return{default:{fn:(e,t)=>cf(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>of(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>sf(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>uf(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>lf(e),argTypes:[`string`]},toJson:{fn:e=>df(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>ff(e),argTypes:[`serializable`],returnType:`string`}}}function mf(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function hf(e,t){return e[t]}function gf(e,t){return t in e}function _f(e){return Object.keys(e)}function vf(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 yf(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function bf(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 xf(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Sf(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function Cf(e,t,n){return e[t]=n,e}function wf(e,t){return delete e[t],e}function Tf(e){return Object.values(e)}function Ef(){return{dict:{fn:(...e)=>mf(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>hf(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>Cf(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>wf(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>_f(e),argTypes:[`dict`]},values:{fn:e=>Tf(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>Sf(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>xf(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>bf(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>gf(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>vf(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>yf(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 Df(...e){for(let t of e)if(of(t))return!1;return!0}function Of(...e){for(let t of e)if(!of(t))return!0;return!1}function kf(e,t){return[...e,t]}function Af(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 jf(e){return e.filter(e=>!of(e))}function Mf(...e){let t=[];for(let n of e)t.push(...n);return t}const Nf={line:0,column:0,offset:0};function Pf(e,t,n,r){return new qc(e,t,n,r,Nf)}function Ff(...e){if(e.length<3)throw Pf(`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(!Lf(t))throw Pf(`dig`,e.length-1,`dict`,Rf(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Pf(`dig`,e,`string`,Rf(r[e]));return If(t,n,r,e.length)}function If(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(!Lf(a))throw Pf(`dig`,r-1,`dict at intermediate key`,Rf(a));return If(a,t,n.slice(1),r)}function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Rf(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function zf(e){return e[0]}function Bf(e,t){return t.some(t=>jl(t,e))}function Vf(e){return e.slice(0,-1)}function Hf(e){return e[e.length-1]}function Uf(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Wf(...e){return e}function Gf(e,t){return[t,...e]}function Kf(e){return e.slice(1)}function qf(e){return[...e].reverse()}function Jf(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Yf(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Xf(e){let t=[];for(let n of e)t.some(e=>jl(e,n))||t.push(n);return t}function Zf(e,...t){return e.filter(e=>!t.some(t=>jl(t,e)))}function Qf(){return{list:{fn:(...e)=>Wf(...e),argTypes:[`value`]},first:{fn:e=>zf(e),argTypes:[`list`]},last:{fn:e=>Hf(e),argTypes:[`list`]},rest:{fn:e=>Kf(e),argTypes:[`list`]},initial:{fn:e=>Vf(e),argTypes:[`list`]},len:{fn:e=>Uf(e),argTypes:[`sized`]},reverse:{fn:e=>qf(e),argTypes:[`list`]},uniq:{fn:e=>Xf(e),argTypes:[`list`]},without:{fn:(e,...t)=>Zf(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>Bf(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>jf(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>Jf(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>Mf(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>Af(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>Gf(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>kf(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>Yf(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>kf(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>Wf(...e),argTypes:[`value`]},dig:{fn:(...e)=>Ff(...e),argTypes:[`value`]},all:{fn:(...e)=>Df(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>Of(...e),argTypes:[`truthy`],returnType:`bool`}}}function $f(...e){return e.reduce((e,t)=>e+t,0)}function ep(e){return e+1}function tp(e){return e+1}function np(...e){return e.reduce((e,t)=>e+t,0)}function rp(e){return Math.ceil(e)}function ip(e,t){return Math.trunc(e/t)}function ap(e,t){return e/t}function op(e){return Math.floor(e)}function sp(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function cp(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function lp(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function up(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function dp(e,t){return e%t}function fp(...e){return e.reduce((e,t)=>e*t,1)}function pp(...e){return e.reduce((e,t)=>e*t,1)}function mp(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function hp(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 gp(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),hp(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return hp(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:hp(n,i+t,r).join(` `)}default:return``}}function _p(e,t){return e-t}function vp(e,t){return e-t}function yp(e){return hp(0,e,e<0?-1:1)}function bp(){return{add:{fn:(...e)=>$f(...e),argTypes:[`int`]},sub:{fn:(e,t)=>_p(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>fp(...e),argTypes:[`int`]},div:{fn:(e,t)=>ip(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>dp(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>lp(...e),argTypes:[`int`]},max:{fn:(...e)=>sp(...e),argTypes:[`int`]},floor:{fn:e=>op(e),argTypes:[`float`]},ceil:{fn:e=>rp(e),argTypes:[`float`]},round:{fn:(e,t)=>mp(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>np(...e),argTypes:[`float`]},subf:{fn:(e,t)=>vp(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>pp(...e),argTypes:[`float`]},divf:{fn:(e,t)=>ap(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>ep(e),argTypes:[`int`]},add1f:{fn:e=>tp(e),argTypes:[`float`]},maxf:{fn:(...e)=>cp(...e),argTypes:[`float`]},minf:{fn:(...e)=>up(...e),argTypes:[`float`]},biggest:{fn:(...e)=>sp(...e),argTypes:[`int`]},seq:{fn:(...e)=>gp(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>yp(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>hp(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function xp(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function Sp(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const $={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},Cp=/^[-_\s]$/,wp=/^\p{P}$/u,Tp=/^\p{L}$/u,Ep=/^\p{Lu}$/u,Dp=/^\p{N}$/u;function Op(e){return e!==void 0&&Cp.test(e)}function kp(e){return e!==void 0&&Tp.test(e)}function Ap(e){return e!==void 0&&Ep.test(e)}function jp(e){return e!==void 0&&Dp.test(e)}function Mp(e){return e!==void 0&&wp.test(e)}function Np(e,t){if(t>=e.length)return{word:{wt:$.Invalid,text:``},next:t};let n=e[t],r=t+1;if(Op(n)){for(;r<e.length&&Op(e[r]);)r++;return{word:{wt:$.Connector,text:e.slice(t,r).join(``)},next:r}}if(Mp(n)){for(;r<e.length&&Mp(e[r]);)r++;return{word:{wt:$.Punct,text:e.slice(t,r).join(``)},next:r}}if(Ap(n)){if(r>=e.length)return{word:{wt:$.UpperCase,text:n},next:r};if(Ap(e[r])){let n=r;for(;n<e.length&&Ap(e[n]);)n++;return n<e.length&&kp(e[n])?{word:{wt:$.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(kp(e[r])){let n=r+1;for(;n<e.length&&kp(e[n])&&!Ap(e[n]);)n++;return{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:$.UpperCase,text:n},next:r}}if(kp(n)){for(;r<e.length&&kp(e[r])&&!Ap(e[r]);)r++;return{word:{wt:$.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(jp(n)){for(;r<e.length&&jp(e[r]);)r++;return{word:{wt:$.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!Op(e[r])&&!kp(e[r])&&!jp(e[r])&&!Mp(e[r]);)r++;return{word:{wt:$.Other,text:e.slice(t,r).join(``)},next:r}}function Pp(e,t,n){if(t.wt!==$.UpperCase&&t.wt!==$.Connector){e.push(t.text);return}for(let r of t.text)Op(r)?e.push(n):Ap(r)?e.push(r.toLowerCase()):e.push(r)}function Fp(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=Np(n,0);for(;a<n.length;){i.wt!==$.Connector&&Pp(r,i,t);let e=i,o=i;if({word:i,next:a}=Np(n,a),e.wt===$.Number){for(;i.wt===$.Alphabet||i.wt===$.Number;)Pp(r,i,t),{word:i,next:a}=Np(n,a);i.wt!==$.Invalid&&i.wt!==$.Punct&&i.wt!==$.Connector&&r.push(t);continue}if(e.wt===$.Connector){Pp(r,o,t);continue}if(e.wt===$.Punct)continue;if(i.wt!==$.Number){i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=Np(n,a),i.wt!==$.Alphabet){Pp(r,s,t),i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}for(r.push(t),Pp(r,s,t);i.wt===$.Alphabet||i.wt===$.Number;)Pp(r,i,t),{word:i,next:a}=Np(n,a);i.wt!==$.Invalid&&i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t)}return Pp(r,i,t),r.join(``).toLowerCase()}function Ip(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!Op(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++,Op(i)&&Op(e)){n.push(e);continue}Op(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Lp(e){return Ip(e)}function Rp(...e){return e.join(` `)}function zp(e,t){return t.includes(e)}function Bp(e,t){return t.startsWith(e)}function Vp(e,t){return t.endsWith(e)}function Hp(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
93
93
|
`).map(e=>n+e).join(`
|
|
94
|
-
`)}function
|
|
95
|
-
`,t)}function
|
|
96
|
-
`)){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 bm(e,t,n){return ym(e,t,n)}function xm(){return{abbrev:{fn:(e,t)=>bp(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>xp(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Ip(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Lp(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Rp(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>zp(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Bp(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Vp(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Hp(e),argTypes:[`string`]},join:{fn:(e,t)=>Up(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>Gp(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Kp(e),argTypes:[`string`]},nindent:{fn:(e,t)=>qp(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Jp(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Yp(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Xp(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Zp(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Qp(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>$p(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>em(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>tm(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>nm(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>rm(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>am(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>om(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>sm(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>um(e),argTypes:[`string`]},trim:{fn:e=>dm(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>fm(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>pm(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>mm(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>hm(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>gm(e),argTypes:[`string`]},upper:{fn:e=>_m(e),argTypes:[`string`]},wrap:{fn:(e,t)=>vm(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>bm(e,t,n),argTypes:[`int`,`string`,`string`]}}}const Sm=`menus.`,Cm=`closed`;function wm(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function Tm(e){return e}function Em(e,t,n){return n===void 0?Sm+wm(e)+`.`+wm(t):Sm+wm(n)}function Dm(e,t){return e+`.`+t}const Om=`menu`;function km(e){let t=xu({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Om).map(e=>({apply:e.args[0]??null,key:e.args.length>4?e.args[4]:void 0}))}catch{return`parse-failed`}}function Am(e){let t=xu({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Om)}catch{return!1}}function jm(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,[`root`])})}function Mm(e,t){for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`menus.`)&&jm(e,`${n}.${r}`,`"${r}" is in the reserved "${Sm}" namespace (synthesized by {{ menu }} helpers) — rename it`);for(let[n,r]of Object.entries(t.helpers??{}))Am(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:Q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&Am(i)&&jm(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 Nn(t.root))typeof n.when==`string`&&Am(n.when)&&jm(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))Am(i.template)&&(r.get(t)??0)>1&&jm(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(!Am(r.template))continue;let n=km(r.template);if(n!==`parse-failed`)for(let r of n){if(r.apply===null){jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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" "themePage" }}).`);continue}if(r.key===null){jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose accordion key is not a string literal — a shared key must be a literal so the mutually-exclusive group can be gated at load (e.g. {{ menu "applyTheme" "themePage" false false "pickers" }}).`);continue}if(r.key===``){jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} with an empty accordion key — a shared key must be a non-empty name (or omit it for an independent menu).`);continue}if(r.apply===``){jm(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 n=Tm(r.apply);if(n===`closed`){jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${Cm}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let c=Em(t,r.apply,r.key),l=r.key===void 0?`ind${t}${r.apply}`:`key${r.key}`,u=s.get(c);if(u!==void 0&&u!==l){jm(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${c}") 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(c,l);let d=Dm(c,n);if(o.has(d)){jm(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${d}") — ${r.key===void 0?`a segment cannot contain two menus over the same apply action "${r.apply}"`:`menus sharing key "${r.key}" must have distinct apply actions`}.`);continue}o.add(d),i.add(c),a[d]={set:c,cycle:[Cm,n]}}}if(i.size===0)return;let c={};for(let e of i)c[e]={kind:`state`,key:e,default:Cm};t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const Nm=[`themes`,`styles`],Pm=[`set`,`copy`,`open`];function Fm(e){return`set`in e}function Im(e,t){if(t===void 0)return{};if(!gs(t))return Lm(e,`actions`,`actions must be an object, got ${_s(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Rm(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Lm(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))})}function Rm(e,t,n){if(!gs(n))return Lm(e,t,`${t} must be an action object, got ${_s(n)}`),null;let r=Pm.filter(e=>e in n);return r.length===1?zm[r[0]](e,t,n):(Lm(e,t,`action must declare exactly one of: ${Pm.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const zm={set:$m,copy:Bm(`copy`),open:Bm(`open`)};function Bm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Lm(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=ds(t,n,r,e);return i===null?null:{[e]:i}}}function Vm(e,t,n,r,i,a){let o=ds(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Lm(e,s,i),null):o.includes(`/`)?(Lm(e,s,a(o)),null):o}function Hm(e,t,n){return Vm(e,t,`set`,n,`set key must be non-empty (the SessionState key to write)`,e=>`set key "${e}" contains "/" — state keys must be slash-free`)}const Um={to:eh()},Wm={from:th()},Gm={min:ih(),max:ih(),by:ih()},Km={int:rh()},qm={cycle:nh()},Jm={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Ym={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Xm(e,...t){let n=Object.keys(e),r=(t,n,r)=>bs(t,e,n,r),i=Ms(e);return{detect:n,allowed:[`set`,...n],label:n.join(`/`),json:{type:`object`,properties:{set:{type:`string`},...i.properties},required:[`set`,...i.required??[]],additionalProperties:!1},parse:t.length?Ts(r,...t):r}}const Zm=[Xm(Um),Xm(Wm),Xm(Gm,Jm,Ym),Xm(Km),Xm(qm)],Qm=`a set action declares exactly one value source: "to" (a literal value), "from" (an option domain: ${Nm.join(`/`)}), "min"/"max"/"by" (a bounded step), "int" (an unbounded integer cursor), or "cycle" (an enumerated domain stepped in order)`;function $m(e,t,n){let r=Hm(e,t,n),i=Zm.filter(e=>e.detect.some(e=>e in n));if(i.length!==1)return Lm(e,t,`${Qm}${i.length>1?` — found: ${i.map(e=>e.label).join(`, `)}`:``}`),null;let a=i[0];for(let r of Object.keys(n))a.allowed.includes(r)||Lm(e,`${t}.${r}`,`Unknown key "${r}" on this set action. Expected one of: ${a.allowed.join(`, `)}`);let o=a.parse(e,t,n);return r===null||o===null?null:{set:r,...o}}function eh(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Vm(e,t,n,r,`set value must be non-empty — an empty value cannot be delivered on the set-state wire`,e=>`set value "${e}" contains "/" — set values must be slash-free`)??void 0}}function th(){return{required:!0,json:{enum:[...Nm]},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Nm.includes(i)){Lm(e,`${t}.${n}`,`from must be one of: ${Nm.join(`, `)}, got ${vs(i)}`);return}return i}}}function nh(){return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(e,t,n,r)=>{let i=r[n],a=`${t}.${n}`;if(!Array.isArray(i)||i.some(e=>typeof e!=`string`)){Lm(e,a,`cycle must be an array of strings (the enumerated values a click steps through), got ${_s(i)}`);return}let o=i;if(o.length<2){Lm(e,a,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let s=o.some(e=>e===``),c=o.filter(e=>e.includes(`/`));if(s){Lm(e,a,`cycle members must be non-empty — an empty value cannot be delivered on the set-state wire`);return}if(c.length>0){Lm(e,a,`cycle member(s) ${c.map(e=>`"${e}"`).join(`, `)} contain "/" — set values must be slash-free`);return}if(new Set(o).size!==o.length){Lm(e,a,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return o}}}function rh(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Lm(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${vs(r[n])}`);return}return!0}}}function ih(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Lm(e,`${t}.${n}`,`${n} must be an integer, got ${vs(i)}`);return}return i}}}function ah(e,t){if(t===void 0)return{};if(!gs(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${_s(t)}`,line:Q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${vs(i)}`,line:Q(e.source,[`helpers`,r])});continue}n[r]=i}return n}const oh=/{{([\s\S]*?)}}/g,sh=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,ch=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function lh(e){let t=new Set,n;for(oh.lastIndex=0;(n=oh.exec(e))!==null;){let e=n[1].replace(sh,``),r;for(ch.lastIndex=0;(r=ch.exec(e))!==null;)t.add(r[1])}return t}const uh=/\baction\s+$/;function dh(e){let t=new Set;oh.lastIndex=0;let n;for(;(n=oh.exec(e))!==null;){let e=n[1],r=0,i;for(sh.lastIndex=0;(i=sh.exec(e))!==null;)uh.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const fh=/\b(?:picker|menu)\s+$/;function ph(e){let t=new Set;oh.lastIndex=0;let n;for(;(n=oh.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(sh.lastIndex=0;(a=sh.exec(e))!==null;)fh.test(e.slice(r,a.index))&&(i=2),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}return t}function mh(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 hh={gitTaculous:`gitaculous`};function gh(e,t){let n=new Set(Object.keys(t.variables));for(let[e,r]of Object.entries(t.segments))if(r.vars)for(let t of Object.keys(r.vars))n.add(`${e}.${t}`);let r=Sh(e.source),i=Q(e.source,[r]);for(let a of Nn(t.root))if(a.when!==void 0&&xh(e,`${r}.when`,a.when,n,{line:i}),a.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,a.name)){let t=hh[a.name],n=t===void 0?``:` (the built-in segment "${a.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:r,message:`${r} entry "${a.name}" does not match any declared segment${n}`,line:i})}for(let[r,i]of Object.entries(t.variables))yh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))yh(e,`segments.${r}.vars.${t}`,a,n,r);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){xh(e,`segments.${r}.${a}`,o,n,{segCtx:r});for(let n of dh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}"`,line:Q(e.source,[`segments`,r,a])});for(let n of ph(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}" (in a picker or menu)`,line:Q(e.source,[`segments`,r,a])})}}}for(let[r,i]of Object.entries(t.variables))bh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))bh(e,`segments.${r}.vars.${t}`,a,n,r);(_h(t)||vh(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:Q(e.source,[`variables`])})}function _h(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 vh(e){return Object.values(e.actions).some(Fm)}function yh(e,t,n,r,i){n.kind===`template`&&xh(e,`${t}.template`,n.template,r,{segCtx:i}),Pn(n)&&n.cache&&`key`in n.cache&&xh(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function bh(e,t,n,r,i){if(Pn(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:Q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function xh(e,t,n,r,i){for(let a of lh(n)){if(mh(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&mh(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Q(e.source,t.split(`.`))})}}function Sh(e){try{let t=Hn.default.parse(e);if(gs(t)&&`root`in t)return`root`}catch{}return`layout`}function Ch(e,t){let{graph:n,nodeInfo:r}=wh(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:Q(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function wh(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 lh(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),Pn(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 Th=[`json5`,`json`];function Eh(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?u.homedir()+e.slice(1):e}function Dh(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[Eh(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??o.join(u.homedir(),`.config`);return[...e?Th.map(t=>o.join(e,`.cc-candybar.${t}`)):[],...Th.map(e=>o.join(i,`.cc-candybar.${e}`)),...Th.map(e=>o.join(a,`cc-candybar`,`config.${e}`))]}function Oh(e,t,r){return Dh(e,t,r).find(n.existsSync)??null}function kh(e,t){let r=Dh(e,t),i=new Set,a=[];for(let e of r)i.has(e)||(i.add(e),n.existsSync(e)&&a.push(e));let s=new Map;for(let e of a){let t=o.dirname(e),n=o.basename(e).replace(/\.(json5|json)$/,``),r=o.join(t,n);s.has(r)||s.set(r,[]),s.get(r).push(e)}let c=[...s.values()].filter(e=>e.length>1);return c.length===0?null:`config-extension collision: ${c.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Ah(e,t=Yn,r){let i=e===null?``:n.readFileSync(e,`utf-8`);return{config:Is(e===null?{}:Mh(e,i,r),t),source:i}}function jh(e,t=`<config>`,n=``,r=new Set(rs())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(gh(a,e),Ch(a,e),i.length>0)throw new ss(t,i);return e}function Mh(e,t,n=new Set(rs())){let r=Nh(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!gs(r))throw new ss(e,[{path:``,message:`Config root must be an object, got ${_s(r)}`}]);let o=Ph(a,r);if(i.length>0)throw new ss(e,i);return o}function Nh(e,t){try{return Hn.default.parse(t)}catch(t){let n=t;throw new ss(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Ph(e,t){for(let n of Object.keys(t))Fh.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Fh].join(`, `)}`,line:Q(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=Rs(e,t.globals)),t.variables!==void 0&&(n.variables=Zs(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=mc(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.
|
|
94
|
+
`)}function Up(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function Wp(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Pf(`join`,2,`list of strings/primitives`,`list element of type ${Gp(e)}`);n.push(String(e))}return n.join(e)}function Gp(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Kp(e){return Fp(e,`-`)}function qp(e){return e.toLowerCase()}function Jp(e,t){return`\n${Hp(e,t)}`}function Yp(e){return e.replace(/\s+/g,``)}function Xp(e,t,n){return n===1?e:t}function Zp(...e){return e.map(e=>`"${e}"`).join(` `)}function Qp(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function $p(e,t){return t.repeat(Math.max(0,e))}function em(e,t,n){return n.split(e).join(t)}function tm(e){return Fp(e,`_`)}function nm(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function rm(e,t){return t.split(e)}function im(e,t,n){let r=am(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function am(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 om(...e){return e.map(e=>`'${e}'`).join(` `)}function sm(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 cm(e){let t=``;for(let n of e)lm(n)?t+=n.toLowerCase():um(n)?t+=n.toUpperCase():t+=n;return t}function lm(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function um(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function dm(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function fm(e){return e.trim()}function pm(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 mm(e,t){return t.startsWith(e)?t.slice(e.length):t}function hm(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function gm(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 _m(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function vm(e){return e.toUpperCase()}function ym(e,t){return bm(e,`
|
|
95
|
+
`,t)}function bm(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
96
|
+
`)){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 xm(e,t,n){return bm(e,t,n)}function Sm(){return{abbrev:{fn:(e,t)=>xp(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>Sp(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Lp(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Rp(...e),argTypes:[`string`]},contains:{fn:(e,t)=>zp(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Bp(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Vp(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Hp(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Up(e),argTypes:[`string`]},join:{fn:(e,t)=>Wp(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>Kp(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>qp(e),argTypes:[`string`]},nindent:{fn:(e,t)=>Jp(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Yp(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Xp(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Zp(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Qp(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>$p(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>em(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>tm(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>nm(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>rm(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>im(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>om(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>sm(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>cm(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>dm(e),argTypes:[`string`]},trim:{fn:e=>fm(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>pm(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>mm(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>hm(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>gm(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>_m(e),argTypes:[`string`]},upper:{fn:e=>vm(e),argTypes:[`string`]},wrap:{fn:(e,t)=>ym(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>xm(e,t,n),argTypes:[`int`,`string`,`string`]}}}const Cm=`menus.`,wm=`closed`;function Tm(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function Em(e){return e}function Dm(e,t,n){return n===void 0?Cm+Tm(e)+`.`+Tm(t):Cm+Tm(n)}function Om(e,t){return e+`.`+t}const km=`menu`;function Am(e){let t=Su({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===km).map(e=>({apply:e.args[0]??null,key:e.args.length>4?e.args[4]:void 0}))}catch{return`parse-failed`}}function jm(e){let t=Su({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(km)}catch{return!1}}function Mm(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,[`root`])})}function Nm(e,t){for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`menus.`)&&Mm(e,`${n}.${r}`,`"${r}" is in the reserved "${Cm}" namespace (synthesized by {{ menu }} helpers) — rename it`);for(let[n,r]of Object.entries(t.helpers??{}))jm(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:Q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&jm(i)&&Mm(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 Nn(t.root))typeof n.when==`string`&&jm(n.when)&&Mm(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))jm(i.template)&&(r.get(t)??0)>1&&Mm(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(!jm(r.template))continue;let n=Am(r.template);if(n!==`parse-failed`)for(let r of n){if(r.apply===null){Mm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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" "themePage" }}).`);continue}if(r.key===null){Mm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose accordion key is not a string literal — a shared key must be a literal so the mutually-exclusive group can be gated at load (e.g. {{ menu "applyTheme" "themePage" false false "pickers" }}).`);continue}if(r.key===``){Mm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} with an empty accordion key — a shared key must be a non-empty name (or omit it for an independent menu).`);continue}if(r.apply===``){Mm(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 n=Em(r.apply);if(n===`closed`){Mm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${wm}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let c=Dm(t,r.apply,r.key),l=r.key===void 0?`ind${t}${r.apply}`:`key${r.key}`,u=s.get(c);if(u!==void 0&&u!==l){Mm(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${c}") 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(c,l);let d=Om(c,n);if(o.has(d)){Mm(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${d}") — ${r.key===void 0?`a segment cannot contain two menus over the same apply action "${r.apply}"`:`menus sharing key "${r.key}" must have distinct apply actions`}.`);continue}o.add(d),i.add(c),a[d]={set:c,cycle:[wm,n]}}}if(i.size===0)return;let c={};for(let e of i)c[e]={kind:`state`,key:e,default:wm};t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const Pm=[`themes`,`styles`],Fm=[`set`,`copy`,`open`];function Im(e){return`set`in e}function Lm(e,t){if(t===void 0)return{};if(!_s(t))return Rm(e,`actions`,`actions must be an object, got ${vs(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=zm(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Rm(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))})}function zm(e,t,n){if(!_s(n))return Rm(e,t,`${t} must be an action object, got ${vs(n)}`),null;let r=Fm.filter(e=>e in n);return r.length===1?Bm[r[0]](e,t,n):(Rm(e,t,`action must declare exactly one of: ${Fm.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Bm={set:eh,copy:Vm(`copy`),open:Vm(`open`)};function Vm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Rm(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=fs(t,n,r,e);return i===null?null:{[e]:i}}}function Hm(e,t,n,r,i,a){let o=fs(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Rm(e,s,i),null):o.includes(`/`)?(Rm(e,s,a(o)),null):o}function Um(e,t,n){return Hm(e,t,`set`,n,`set key must be non-empty (the SessionState key to write)`,e=>`set key "${e}" contains "/" — state keys must be slash-free`)}const Wm={to:th()},Gm={from:nh()},Km={min:ah(),max:ah(),by:ah()},qm={int:ih()},Jm={cycle:rh()},Ym={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Xm={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Zm(e,...t){let n=Object.keys(e),r=(t,n,r)=>xs(t,e,n,r),i=Ns(e);return{detect:n,allowed:[`set`,...n],label:n.join(`/`),json:{type:`object`,properties:{set:{type:`string`},...i.properties},required:[`set`,...i.required??[]],additionalProperties:!1},parse:t.length?Es(r,...t):r}}const Qm=[Zm(Wm),Zm(Gm),Zm(Km,Ym,Xm),Zm(qm),Zm(Jm)],$m=`a set action declares exactly one value source: "to" (a literal value), "from" (an option domain: ${Pm.join(`/`)}), "min"/"max"/"by" (a bounded step), "int" (an unbounded integer cursor), or "cycle" (an enumerated domain stepped in order)`;function eh(e,t,n){let r=Um(e,t,n),i=Qm.filter(e=>e.detect.some(e=>e in n));if(i.length!==1)return Rm(e,t,`${$m}${i.length>1?` — found: ${i.map(e=>e.label).join(`, `)}`:``}`),null;let a=i[0];for(let r of Object.keys(n))a.allowed.includes(r)||Rm(e,`${t}.${r}`,`Unknown key "${r}" on this set action. Expected one of: ${a.allowed.join(`, `)}`);let o=a.parse(e,t,n);return r===null||o===null?null:{set:r,...o}}function th(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Hm(e,t,n,r,`set value must be non-empty — an empty value cannot be delivered on the set-state wire`,e=>`set value "${e}" contains "/" — set values must be slash-free`)??void 0}}function nh(){return{required:!0,json:{enum:[...Pm]},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Pm.includes(i)){Rm(e,`${t}.${n}`,`from must be one of: ${Pm.join(`, `)}, got ${ys(i)}`);return}return i}}}function rh(){return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(e,t,n,r)=>{let i=r[n],a=`${t}.${n}`;if(!Array.isArray(i)||i.some(e=>typeof e!=`string`)){Rm(e,a,`cycle must be an array of strings (the enumerated values a click steps through), got ${vs(i)}`);return}let o=i;if(o.length<2){Rm(e,a,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let s=o.some(e=>e===``),c=o.filter(e=>e.includes(`/`));if(s){Rm(e,a,`cycle members must be non-empty — an empty value cannot be delivered on the set-state wire`);return}if(c.length>0){Rm(e,a,`cycle member(s) ${c.map(e=>`"${e}"`).join(`, `)} contain "/" — set values must be slash-free`);return}if(new Set(o).size!==o.length){Rm(e,a,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return o}}}function ih(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Rm(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${ys(r[n])}`);return}return!0}}}function ah(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Rm(e,`${t}.${n}`,`${n} must be an integer, got ${ys(i)}`);return}return i}}}function oh(e,t){if(t===void 0)return{};if(!_s(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${vs(t)}`,line:Q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${ys(i)}`,line:Q(e.source,[`helpers`,r])});continue}n[r]=i}return n}const sh=/{{([\s\S]*?)}}/g,ch=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,lh=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function uh(e){let t=new Set,n;for(sh.lastIndex=0;(n=sh.exec(e))!==null;){let e=n[1].replace(ch,``),r;for(lh.lastIndex=0;(r=lh.exec(e))!==null;)t.add(r[1])}return t}const dh=/\baction\s+$/;function fh(e){let t=new Set;sh.lastIndex=0;let n;for(;(n=sh.exec(e))!==null;){let e=n[1],r=0,i;for(ch.lastIndex=0;(i=ch.exec(e))!==null;)dh.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const ph=/\b(?:picker|menu)\s+$/;function mh(e){let t=new Set;sh.lastIndex=0;let n;for(;(n=sh.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(ch.lastIndex=0;(a=ch.exec(e))!==null;)ph.test(e.slice(r,a.index))&&(i=2),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}return t}function hh(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 gh={gitTaculous:`gitaculous`};function _h(e,t){let n=new Set(Object.keys(t.variables));for(let[e,r]of Object.entries(t.segments))if(r.vars)for(let t of Object.keys(r.vars))n.add(`${e}.${t}`);let r=Ch(e.source),i=Q(e.source,[r]);for(let a of Nn(t.root))if(a.when!==void 0&&Sh(e,`${r}.when`,a.when,n,{line:i}),a.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,a.name)){let t=gh[a.name],n=t===void 0?``:` (the built-in segment "${a.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:r,message:`${r} entry "${a.name}" does not match any declared segment${n}`,line:i})}for(let[r,i]of Object.entries(t.variables))bh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))bh(e,`segments.${r}.vars.${t}`,a,n,r);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){Sh(e,`segments.${r}.${a}`,o,n,{segCtx:r});for(let n of fh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}"`,line:Q(e.source,[`segments`,r,a])});for(let n of mh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}" (in a picker or menu)`,line:Q(e.source,[`segments`,r,a])})}}}for(let[r,i]of Object.entries(t.variables))xh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))xh(e,`segments.${r}.vars.${t}`,a,n,r);(vh(t)||yh(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:Q(e.source,[`variables`])})}function vh(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 yh(e){return Object.values(e.actions).some(Im)}function bh(e,t,n,r,i){n.kind===`template`&&Sh(e,`${t}.template`,n.template,r,{segCtx:i}),Pn(n)&&n.cache&&`key`in n.cache&&Sh(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function xh(e,t,n,r,i){if(Pn(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:Q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function Sh(e,t,n,r,i){for(let a of uh(n)){if(hh(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&hh(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Q(e.source,t.split(`.`))})}}function Ch(e){try{let t=Hn.default.parse(e);if(_s(t)&&`root`in t)return`root`}catch{}return`layout`}function wh(e,t){let{graph:n,nodeInfo:r}=Th(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:Q(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function Th(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 uh(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),Pn(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 Eh=[`json5`,`json`];function Dh(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?u.homedir()+e.slice(1):e}function Oh(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[Dh(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??o.join(u.homedir(),`.config`);return[...e?Eh.map(t=>o.join(e,`.cc-candybar.${t}`)):[],...Eh.map(e=>o.join(i,`.cc-candybar.${e}`)),...Eh.map(e=>o.join(a,`cc-candybar`,`config.${e}`))]}function kh(e,t,r){return Oh(e,t,r).find(n.existsSync)??null}function Ah(e,t){let r=Oh(e,t),i=new Set,a=[];for(let e of r)i.has(e)||(i.add(e),n.existsSync(e)&&a.push(e));let s=new Map;for(let e of a){let t=o.dirname(e),n=o.basename(e).replace(/\.(json5|json)$/,``),r=o.join(t,n);s.has(r)||s.set(r,[]),s.get(r).push(e)}let c=[...s.values()].filter(e=>e.length>1);return c.length===0?null:`config-extension collision: ${c.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function jh(e,t=Yn,r){let i=e===null?``:n.readFileSync(e,`utf-8`);return{config:Ls(e===null?{}:Nh(e,i,r),t),source:i}}function Mh(e,t=`<config>`,n=``,r=new Set(rs())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(_h(a,e),wh(a,e),i.length>0)throw new cs(t,i);return e}function Nh(e,t,n=new Set(rs())){let r=Ph(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!_s(r))throw new cs(e,[{path:``,message:`Config root must be an object, got ${vs(r)}`}]);let o=Fh(a,r);if(i.length>0)throw new cs(e,i);return o}function Ph(e,t){try{return Hn.default.parse(t)}catch(t){let n=t;throw new cs(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Fh(e,t){for(let n of Object.keys(t))Ih.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Ih].join(`, `)}`,line:Q(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=zs(e,t.globals)),t.variables!==void 0&&(n.variables=Qs(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=hc(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.
|
|
97
97
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
98
98
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
99
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`layout`])}),t.root!==void 0&&(n.root=
|
|
100
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Ih.test(t))continue;let r=Lh(t);if(r!=null)return r}return null}const Vh=10*1e3;function Hh(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 Uh(e,t){if(!(t<60))return e*3600/t}function Wh(e,t,n,r){let i=r-t;if(i<50||i>Vh)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Gh(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Wh(t.input,t.atMs,n.input,n.atMs),i=Wh(t.output,t.atMs,n.output,n.atMs),a=Wh(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 Kh(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>Vh)continue;let o=Wh(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function qh(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 Nn(e.root)){if(t.when)for(let e of lh(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 lh(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Jh(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 lh(e.template))n.push(t)}}}return i}function Jh(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 Yh(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Xh(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.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function Zh(e,t,n,r){let i=e=>Yh(r,e),a=(t.clock??(()=>new Date))().getTime(),o=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[s,c,l,u,d,f,p,m]=await Promise.all([o(`git`,i(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Xh(r),e.workspace?.project_dir)),o(`session`,i(`session.cost`)||i(`session.tokens`)||i(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),o(`today`,i(`today`),()=>t.usageStore.getTodayInfo(e)),o(`context`,i(`context`),()=>t.contextProvider.getContextInfo(e)),o(`metrics`,i(`metrics`)||i(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),o(`tmux`,i(`tmux`),()=>t.tmuxService.getSessionId()),o(`cache`,i(`cache`),()=>Rh(e.transcript_path)),o(`speed`,i(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,a))]),h=[],g=e=>{if(e.kind===`failed`){h.push(e.reason);return}return e.kind===`ok`?e.value:void 0},_=eg(s);h.push(..._.failures);let v=g(c),y=g(l),b=g(u),x=g(d),S=g(f),C=g(p);for(let e of h)t.log(`warn`,`provider fetch failed: ${e}`);let ee=e.rate_limits?.five_hour,te=e.rate_limits?.seven_day,w=ee?Hh(ee.used_percentage,ee.resets_at,18e6,a):void 0,ne=te?Hh(te.used_percentage,te.resets_at,6048e5,a):void 0,re=v?.session.cost,ie=x?.sessionDuration,T=i(`burn`)&&re!=null&&ie!=null?Uh(re,ie):void 0,E=g(m),ae=E===void 0?void 0:Gh(E),oe=E===void 0?void 0:Kh(E),se=ae!==void 0||oe!==void 0?{...ae,...oe!==void 0&&{history:oe}}:void 0,ce=i(`theme`)?t.sessionState.get(e.session_id,`theme`):void 0,D=typeof ce==`string`?ce:void 0,le=$h(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:$h(e.workspace.current_dir)??``,project_dir:$h(e.workspace.project_dir)??``}:e.workspace,O=v===void 0?void 0:Qh({cost:v.session.cost,tokens:v.session.tokens}),de=y===void 0?void 0:{cost:y.cost,tokens:y.tokens},fe=x===void 0?void 0:Qh({lastResponseTime:x.lastResponseTime,responseTime:x.responseTime,sessionDuration:x.sessionDuration,messageCount:x.messageCount,linesAdded:x.linesAdded,linesRemoved:x.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},..._.git!==void 0&&{git:_.git},...S!==void 0&&{tmux:{session:S}},...D!==void 0&&{theme:D},...O!==void 0&&{session:O},...de!==void 0&&{today:de},...T!==void 0&&{burn:{costPerHour:T}},...se!==void 0&&{speed:se},...i(`block`)&&ee!==void 0&&{block:{nativeUtilization:ee.used_percentage,resetsAt:ee.resets_at,...w!==void 0&&{etaMinutes:w}}},...te!==void 0&&{weekly:{percentage:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...C!==void 0&&{cache:{expiresAt:C}},...b!==void 0&&{context:{totalTokens:b.totalTokens,contextLeft:b.contextLeftPercentage}},...fe!==void 0&&{metrics:fe}}}function Qh(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 $h(e){return e===void 0||e.length===0||o.sep!==`\\`?e:e.replace(/\\/g,`/`)}function eg(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=t.pullRequest,f={};return d?.kind===`ok`?(f.prNumber=d.value.number,f.prState=d.value.state,f.prUrl=d.value.url):d?.kind===`failed`&&(n.push(`git.pr: ${d.reason}`),f.prError=d.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},...f},failures:n}}function tg(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 ng(e){return typeof e==`string`?e:String(e)}function rg(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 ig(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 ag=/^(?:(?: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,og=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function sg(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(ag);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(og);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 cg(e){let t=e.match(og);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 lg(e){return e.toLocaleString()}const ug=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],dg=ug.length;function fg(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*(dg-1));o+=ug[t]}return o}function pg(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 mg=rs(),hg=[...is];function gg(){return{basename:{fn:e=>s(e),argTypes:[`string`]},dirname:{fn:e=>c(e),argTypes:[`string`]},int:{fn:e=>rg(e),argTypes:[`value`]},string:{fn:e=>ng(e),argTypes:[`value`]},bool:{fn:e=>ig(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>mg,argTypes:[]},styles:{fn:()=>hg,argTypes:[]},sparkline:{fn:(e,t)=>fg(pg(e),t),argTypes:[`string`,`int`]}}}function _g(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>lg(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>sg(e),argTypes:[`string`]},shortenModelName:{fn:e=>cg(e),argTypes:[`string`]}}}function vg(e,t,n=()=>new Date){return xu({fromString:e=>new Ca(e),toString:e=>e.plain,clock:n,missingKey:`error`,funcs:{...ff(),...xm(),...Zf(),...yp(),...rf(n),...qu(),...Tf(),...Qo(),...e===void 0?{}:Zo(e),...gg(),..._g(n),...t??{}}})}function yg(e){return bg(e,new Set(e.names()),``)}function bg(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 bg(e,t,a)}})}function xg(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 Sg(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 Cg(e){let t=await _e({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 wg(e,t,n){let r;try{r=await C(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(`
|
|
101
|
-
`)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const
|
|
102
|
-
`)?r.slice(0,-1):r}return Pa(new wa([...e],n),{colorSystem:t.colorCompatibility})}const
|
|
99
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`layout`])}),t.root!==void 0&&(n.root=Ac(e,`root`,t.root)),t.actions!==void 0&&(n.actions=Lm(e,t.actions)),t.helpers!==void 0&&(n.helpers=oh(e,t.helpers)),Hc(e,n),Nm(e,n),n}const Ih=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`helpers`]),Lh=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Rh(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 zh(e){let t=await Bh(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function Bh(e){for(let t of[65536,1048576]){let n=await fn(e,t);if(n.kind!==`ok`)return n;let r=Vh(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function Vh(e,t){let n=e.toString(`utf8`).split(`
|
|
100
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Lh.test(t))continue;let r=Rh(t);if(r!=null)return r}return null}const Hh=10*1e3;function Uh(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 Wh(e,t){if(!(t<60))return e*3600/t}function Gh(e,t,n,r){let i=r-t;if(i<50||i>Hh)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Kh(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Gh(t.input,t.atMs,n.input,n.atMs),i=Gh(t.output,t.atMs,n.output,n.atMs),a=Gh(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 qh(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>Hh)continue;let o=Gh(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Jh(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 Nn(e.root)){if(t.when)for(let e of uh(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 uh(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Yh(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 uh(e.template))n.push(t)}}}return i}function Yh(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 Xh(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Zh(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.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function Qh(e,t,n,r){let i=e=>Xh(r,e),a=(t.clock??(()=>new Date))().getTime(),o=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[s,c,l,u,d,f,p,m]=await Promise.all([o(`git`,i(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Zh(r),e.workspace?.project_dir)),o(`session`,i(`session.cost`)||i(`session.tokens`)||i(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),o(`today`,i(`today`),()=>t.usageStore.getTodayInfo(e)),o(`context`,i(`context`),()=>t.contextProvider.getContextInfo(e)),o(`metrics`,i(`metrics`)||i(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),o(`tmux`,i(`tmux`),()=>t.tmuxService.getSessionId()),o(`cache`,i(`cache`),()=>zh(e.transcript_path)),o(`speed`,i(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,a))]),h=[],g=e=>{if(e.kind===`failed`){h.push(e.reason);return}return e.kind===`ok`?e.value:void 0},_=tg(s);h.push(..._.failures);let v=g(c),y=g(l),b=g(u),x=g(d),S=g(f),C=g(p);for(let e of h)t.log(`warn`,`provider fetch failed: ${e}`);let ee=e.rate_limits?.five_hour,te=e.rate_limits?.seven_day,w=ee?Uh(ee.used_percentage,ee.resets_at,18e6,a):void 0,ne=te?Uh(te.used_percentage,te.resets_at,6048e5,a):void 0,re=v?.session.cost,ie=x?.sessionDuration,T=i(`burn`)&&re!=null&&ie!=null?Wh(re,ie):void 0,E=g(m),ae=E===void 0?void 0:Kh(E),oe=E===void 0?void 0:qh(E),se=ae!==void 0||oe!==void 0?{...ae,...oe!==void 0&&{history:oe}}:void 0,ce=i(`theme`)?t.sessionState.get(e.session_id,`theme`):void 0,D=typeof ce==`string`?ce:void 0,le=eg(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:eg(e.workspace.current_dir)??``,project_dir:eg(e.workspace.project_dir)??``}:e.workspace,O=v===void 0?void 0:$h({cost:v.session.cost,tokens:v.session.tokens}),de=y===void 0?void 0:{cost:y.cost,tokens:y.tokens},fe=x===void 0?void 0:$h({lastResponseTime:x.lastResponseTime,responseTime:x.responseTime,sessionDuration:x.sessionDuration,messageCount:x.messageCount,linesAdded:x.linesAdded,linesRemoved:x.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},..._.git!==void 0&&{git:_.git},...S!==void 0&&{tmux:{session:S}},...D!==void 0&&{theme:D},...O!==void 0&&{session:O},...de!==void 0&&{today:de},...T!==void 0&&{burn:{costPerHour:T}},...se!==void 0&&{speed:se},...i(`block`)&&ee!==void 0&&{block:{nativeUtilization:ee.used_percentage,resetsAt:ee.resets_at,...w!==void 0&&{etaMinutes:w}}},...te!==void 0&&{weekly:{percentage:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...C!==void 0&&{cache:{expiresAt:C}},...b!==void 0&&{context:{totalTokens:b.totalTokens,contextLeft:b.contextLeftPercentage}},...fe!==void 0&&{metrics:fe}}}function $h(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 eg(e){return e===void 0||e.length===0||o.sep!==`\\`?e:e.replace(/\\/g,`/`)}function tg(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=t.pullRequest,f={};return d?.kind===`ok`?(f.prNumber=d.value.number,f.prState=d.value.state,f.prUrl=d.value.url):d?.kind===`failed`&&(n.push(`git.pr: ${d.reason}`),f.prError=d.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},...f},failures:n}}function ng(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 rg(e){return typeof e==`string`?e:String(e)}function ig(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 ag(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 og=/^(?:(?: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,sg=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function cg(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(og);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(sg);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 lg(e){let t=e.match(sg);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 ug(e){return e.toLocaleString()}const dg=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],fg=dg.length;function pg(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*(fg-1));o+=dg[t]}return o}function mg(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 hg=rs(),gg=[...is];function _g(){return{basename:{fn:e=>s(e),argTypes:[`string`]},dirname:{fn:e=>c(e),argTypes:[`string`]},int:{fn:e=>ig(e),argTypes:[`value`]},string:{fn:e=>rg(e),argTypes:[`value`]},bool:{fn:e=>ag(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>hg,argTypes:[]},styles:{fn:()=>gg,argTypes:[]},sparkline:{fn:(e,t)=>pg(mg(e),t),argTypes:[`string`,`int`]}}}function vg(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>ug(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>cg(e),argTypes:[`string`]},shortenModelName:{fn:e=>lg(e),argTypes:[`string`]}}}function yg(e,t,n=()=>new Date){return Su({fromString:e=>new Ca(e),toString:e=>e.plain,clock:n,missingKey:`error`,funcs:{...pf(),...Sm(),...Qf(),...bp(),...af(n),...Ju(),...Ef(),...Qo(),...e===void 0?{}:Zo(e),..._g(),...vg(n),...t??{}}})}function bg(e){return xg(e,new Set(e.names()),``)}function xg(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 xg(e,t,a)}})}function Sg(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 Cg(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 wg(e){let t=await _e({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 Tg(e,t,n){let r;try{r=await C(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(`
|
|
101
|
+
`)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const Eg=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Dg=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Og=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],kg=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ag(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>Eg[e.getMonth()]],[`Monday`,e=>Og[e.getDay()]],[`Jan`,e=>Dg[e.getMonth()]],[`Mon`,e=>kg[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 jg={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Mg(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=jg[t];try{return Ig(r,e)}catch{return Lg(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return zt(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return zt(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return zt(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return zt(e.stashCount,0)}}var Ng=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=a(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}},Pg=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:re(()=>{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&&(ne(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ne(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Fg(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Ig(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`?rg(e):t===`number`?ig(e):ag(e)}function Lg(e){return e===`number`?0:e===`boolean`?!1:``}var Rg=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new Ng;ttlMgr=new Pg;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=yg();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new rn({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,ng(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=Sg(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=bg(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 Ag(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Ag(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=jg[t.field],r=t.varDefault===void 0?Lg(n):Ig(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,Mg(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=Fg(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Ig(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=bg(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 wg(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 Tg(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,Ig(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Lg(t))}}defaultFor(e){try{return Ig(this.defaultEmptyValue,e)}catch{return Lg(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 zg={unicode:{},ascii:{glyph:`>`}},Bg={unicode:{},ascii:{left:`(`,right:`)`}};function Vg(e,t,n){switch(e){case`capsule`:return new Aa(Bg[t]);case`plain`:return new ja(n===void 0?{}:{separator:n});case`powerline`:return new ka(zg[t]);default:return e}}function Hg(e){switch(e){case`powerline`:return 1;case`capsule`:return 2;case`plain`:return 0;default:return e}}function Ug(e,t){if(e.length===0)return``;let n=Vg(t.style,t.charset,t.separator);if(t.wrap&&Number.isFinite(t.width)){let r=Pa(new Ka([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
|
|
102
|
+
`)?r.slice(0,-1):r}return Pa(new wa([...e],n),{colorSystem:t.colorCompatibility})}const Wg=new Map,Gg=new Map;function Kg(e){let t=es(e),n=Wg.get(t);if(n!==void 0)return n;let r=Vi(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);let i=new Pi(r);return Wg.set(t,i),i}function qg(e,t){let n=`${e.palette.name} ${t}`,r=Gg.get(n);if(r!==void 0)return r;let i={hueShift:t,chromaScale:1,lightnessScale:1,lightnessShift:0},a=new Pi($i(e.palette,i));return Gg.set(n,a),a}function Jg(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=Yg(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=Yg([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function Yg(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>Xg(e,t)):e,r=Ca.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 Xg(e,t){let n=e.copy();return n.style=t.add(e.style),n}function Zg(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function Qg(e,t){let n=Ca.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function $g(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=Qg(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 e_=class extends Error{constructor(e,t){super(`Invalid ${t} color spec: ${JSON.stringify(e)}`),this.name=`ColorSpecError`}};function t_(e,t,n,r){let i=n_(t,r),a=i===void 0?void 0:r_(e,i,void 0,`bg`),o=n_(n,r),s=o===void 0?void 0:r_(e,o,a,`fg`);return new J({bgcolor:a===void 0?void 0:K.fromRgba(a),color:s===void 0?void 0:K.fromRgba(s)})}function n_(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function r_(e,t,n,r){let i=e.resolve(t.trim(),n===void 0?void 0:{against:n});if(i===null)throw new e_(t,r);return i}function i_(e){return e===`themes`?rs():is}function a_(e,t,n){let r=new Map;for(let[i,a]of Object.entries(t))r.set(i,o_(e,i,a,n));return r}function o_(e,t,n,r){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:[...i_(n.from)]}:`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}}return`copy`in n?{kind:`copy`,text:s_(e,n.copy,t)}:{kind:`open`,target:s_(e,n.open,t)}}function s_(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function c_(e,t){return e.has(t)?rg(e.read(t)):``}function l_(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function u_(e,t,n){let r=new Ca(e,{style:new J({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function d_(e,t){return Math.max(e.members.indexOf(c_(t,e.stateVar)),0)}function f_(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=c_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=c_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=c_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(d_(e,r)+1)%e.members.length];return{effect:{verb:at,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:ot,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:st,args:[l_(e.text,bg(r))]},active:!1};case`open`:return{effect:{verb:ct,args:[l_(e.target,bg(r))]},active:!1}}}function p_(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-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[d_(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 m_(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}=p_(e,r,t,i),{effect:s,active:c}=f_(r,a,o,i,c_(i,`session.id`));return u_(a,pt([s]),c)}function h_(e){return{action:{fn:(t,...n)=>m_(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function g_(e){return new Ca(e).cellLength}function __(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 v_(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ca(` `)),n.push(t);let r=Ca.fromFragments(n);return r.noWrap=t,r.end=``,r}function y_(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 b_(e,t,n,r,i){let a=y_(i,e,`set-option`,`a set-option action ({ set, from })`),o=y_(i,t,`set-int`,`an int action ({ set, int: true })`),s=i.store,c=c_(s,`session.id`),l=c_(s,a.stateVar),u=a.options.map(g_),d=r?Math.max(1,ig(s.read(`term.cols`))-Hg(i.stripStyle)-2*i.padding):1/0,f=g_(`✕`)+1,p=g_(`←`)+1+g_(`→`)+1,m=__(u,d,f),h=m.length>1?__(u,d,f+p):m,g=parseInt(c_(s,o.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>pt([{verb:at,args:[c,o.key,String(e)]}]),b=e=>pt([{verb:at,args:[c,a.key,e,...n?[o.key,`-1`]:[]]}]),x=[u_(`✕`,y(-1),!1)];_>0&&x.push(u_(`←`,y(_-1),!1));for(let e of v){let t=a.options[e];x.push(u_(t,b(t),t===l))}return _<h.length-1&&x.push(u_(`→`,y(_+1),!1)),v_(x,r)}function x_(e){return{picker:{fn:(t,n,r,i)=>b_(t,n,r===!0,i===!0,e),argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const S_=Symbol(`cc-candybar.menuDrop`);function C_(e){return e.flatMap(e=>e[S_]??[])}function w_(e,t){let n=e.compiled.get(t);if(!n||n.kind!==`set-int`)throw Error(`{{ menu }} page action "${t}" must be an int action ({ set, int: true })`);return n.key}function T_(e,t,n,r,i,a){let o=a.current;if(o===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let s=a.action,c=Dm(o.segName,e,i),l=Em(e),u=c_(s.store,c)===l,d=c_(s.store,`session.id`),f=u_(u?`▾`:`▸`,pt([{verb:at,args:[d,c,u?wm:l,w_(s,t),`0`]}]),!1);return f[S_]=u?[b_(e,t,n,r,s)]:[],f}function E_(e){return{menu:{fn:(t,n,r,i,a)=>T_(t,n,r===!0,i===!0,a,e),argTypes:[`string`,`string`,`bool`,`bool`,`string`],returnType:`T`}}}function D_(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
103
103
|
`)){n.push(r);continue}let e=r.split(`
|
|
104
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function
|
|
105
|
-
`)}const
|
|
104
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function O_(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 k_={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 O_(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(!Zg(i.when,t.scope))return[];t.beginSegment(e.name);let n=i.template.evaluate(t.scope),o=t.collectDrops(n),s=t_(qg(i.paletteResolver??t.basePalette,a),i.bg,i.fg,t.scope),c=o.length>0?t.focusTint(s):s,l={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:c,padding:t.padding},u=D_(Jg(n,c)).map(e=>$g(e,l)),d=o.map(e=>$g(Jg([e],c),l)),f=[...u,...d];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,f.flat()),f}catch(t){return[[new Ca(`⚠ ${e.name}: ${t.message??String(t)}`)]]}}}};function A_(e){return k_[e]}function j_(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Cg(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 M_(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:j_(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:j_(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?Cg(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 N_(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 P_(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a={action:i,current:null},o=yg(void 0,{...h_(i),...x_(i),...E_(a)},n?.clock),s=N_(o,e.helpers),c=e=>o.parse(s+e),l=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!l.has(n.key)&&l.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`&&!l.has(r.key)&&l.set(r.key,`${t}.${e}`);i.compiled=a_(c,e.actions,l);let u=[];for(let[n,i]of Object.entries(e.variables))try{M_(t,n,i,r)}catch(e){u.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{M_(t,`${n}.${e}`,a,r)}catch(t){u.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let d=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};d[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`),paletteResolver:n.palette===void 0?void 0:Kg(n.palette)}}let f=(e,t,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},p=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:f(e.when,t,`when`),compileChild:p};return A_(e.kind).compile(e,n)};return{segments:d,root:p(e.root,`root`),menuRuntime:a,loadWarnings:u}}function F_(e){let t=e.bgcolor;return t===void 0?e:new J({bgcolor:K.fromRgba(q(t.getTruecolor(),1)),color:e.color})}function I_(e,t,n,r,i,a,o,s){r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let c=bg(n),l=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,u=Number.isFinite(l)?l:0;s?.clear();let d={value:0},f=()=>{let e=d.value*u;return d.value+=1,e},p=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},m=e=>{t.menuRuntime.current={segName:e}},h=e=>(t.menuRuntime.current=null,C_(e)),g=(e,t)=>{let n={scope:c,basePalette:a,visible:t&&Zg(e.when,c),padding:o.padding,nextHueShift:f,perSegmentSink:s,beginSegment:m,collectDrops:h,focusTint:F_,lookupSegment:p,renderChild:g};return A_(e.kind).render(e,n)};return g(t.root,!0).map(e=>Ug(e,o)).join(`
|
|
105
|
+
`)}const L_=rs(),R_=new Set(L_),z_=new Set(is),B_=e=>e?R_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${L_.join(`, `)})`}:{ok:!1,reason:`theme name is required`},V_=e=>e?z_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${is.join(`, `)})`}:{ok:!1,reason:`style name is required`},H_=new Set([`1`,`true`]),U_=new Set([`0`,`false`]),W_=new Map([[`style`,{validator:V_,permanent:!0}],[`theme`,{validator:B_,permanent:!0}],[`toolbar-expanded`,{validator:e=>H_.has(e)?{ok:!0,value:`1`}:U_.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`},permanent:!0}]]);function G_(){return[...W_.keys()]}function K_(e,t,n){if(t===`int`)return Z_(`menu page "${e}"`);if(t===`range`){let t=n.flatMap(e=>e.kind===`range`?[e.min]:[]),r=n.flatMap(e=>e.kind===`range`?[e.max]:[]);return Q_(Math.min(...t),Math.max(...r),`stepper "${e}"`)}return Y_([...new Set(n.flatMap(e=>e.kind===`allow-list`?e.allowed:[]))],`state "${e}"`)}function q_(e,t){if(!e)throw Error(`registerStateValidator: key is required`);if(e.includes(`/`))throw Error(`registerStateValidator: key "${e}" contains "/" — the set-state wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let n=W_.get(e);if(n){if(n.permanent)throw Error(`registerStateValidator: key "${e}" is a built-in state key and cannot be re-claimed (built-in keys: ${[...J_()].join(`, `)})`);if(n.kind!==t.kind)throw Error(`registerStateValidator: key "${e}" is already a ${n.kind} state key; cannot also register it as ${t.kind}. A state key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);n.specs.push(t),n.validator=K_(e,n.kind,n.specs)}else{let n=[t];W_.set(e,{permanent:!1,kind:t.kind,validator:K_(e,t.kind,n),specs:n})}let r=!0;return()=>{if(!r)return;r=!1;let n=W_.get(e);if(!n||n.permanent)return;let i=n.specs.indexOf(t);i>=0&&n.specs.splice(i,1),n.specs.length===0?W_.delete(e):n.validator=K_(e,n.kind,n.specs)}}function J_(){let e=[];for(let[t,n]of W_)n.permanent&&e.push(t);return e}function Y_(e,t){let n=e.filter(e=>e.includes(`/`));if(n.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the set-state wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${n.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 r=new Set(e),i=[...e];return e=>e?r.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${i.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}const X_=/^-?\d+$/;function Z_(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!X_.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 Q_(e,t,n){return r=>r?X_.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 $_(e){return e===`themes`?L_:is}function ev(e,t){let n=t.filter(e=>e.kind===`range`),r=t.some(e=>e.kind===`int`),i=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(n.length===0&&!r)return{kind:`allow-list`,allowed:[...new Set(i)]};let a=i.filter(e=>!X_.test(e));if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${a.join(`, `)}). A state key has one key shape — point that click at a distinct key, or write an integer.`);if(r&&n.length>0)throw Error(`deriveActionValidators: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a state key has one key shape. Use distinct keys.`);if(n.length>0){let t=Math.min(...n.map(e=>e.min)),r=Math.max(...n.map(e=>e.max)),a=i.filter(e=>{let n=parseInt(e,10);return n<t||n>r});if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is a bounded range [${t},${r}] but a click writes out-of-range value(s) to it (${a.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:r,seed:iv(n[0].seed,t,r)}}return{kind:`int`}}function tv(e){let t=new Set(J_());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function nv(e){let t=new Map;for(let{key:n,spec:r}of e){let e=t.get(n);e?e.push(r):t.set(n,[r])}return[...t].map(([e,t])=>({key:e,spec:ev(e,t)}))}function rv(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:$_(e.from)}}]:`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:iv(t.get(e.set),e.min,e.max)}}]:[]}function iv(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function av(e){let t=new Map;for(let n of Object.values(e.variables)){if(n.kind!==`state`)continue;let e=n.default;e!==void 0&&X_.test(e)&&t.set(n.key,parseInt(e,10))}return t}function ov(e){let t=av(e);return tv(Object.values(e.actions).flatMap(e=>rv(e,t)))}function sv(e){return nv(ov(e))}function cv(e,t){let n=W_.get(e);return n?n.validator(t):{ok:!1,reason:`unknown state key "${e}" (have: ${G_().join(`, `)})`}}function lv(e){let t=W_.get(e);if(!t||t.permanent||t.kind!==`range`)return null;let n=t.specs.flatMap(e=>e.kind===`range`?[e]:[]);if(n.length===0)return null;let r=Math.min(...n.map(e=>e.min)),i=Math.max(...n.map(e=>e.max));return{min:r,max:i,seed:iv(n[0].seed,r,i)}}var uv=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,fv(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){fv(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},dv=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,X.computed)(()=>{let e=n();return fv(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function fv(e,t,n,r){let i=ng(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var pv=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new uv(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new dv(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 mv(e,t,n){return e+`\0`+t+`\0`+(n??``)}var hv=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=mv(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=kh(e.projectDir,e.cwd,e.configFile);e.lastWarning=Ah(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof cs||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(`
|
|
106
106
|
`);e.lastWarning=e.lastWarning?e.lastWarning+`
|
|
107
|
-
`+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=Ah(t),i=jh(n,t??`<default>`,r),a=new uv,o=new Lg(a,i.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),s,c=[];try{s=j_(i,o,{cwd:e.cwd});for(let{key:e,spec:t}of iv(i))c.push(W_(e,t))}catch(e){for(let e of c)e();throw o.dispose(),e}return{config:i,store:a,registry:o,compiled:s,neededInputPaths:qh(i),lastRenderCellsBySegment:new Map,validatorDisposers:c}}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 r=Dh(e.projectDir,e.cwd,e.configFile),i=new Map;for(let e of r){let t=o.dirname(e);if(!n.existsSync(t))continue;let r=o.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(r)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),s=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(s,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){N(`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 pv=16384;var mv=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<pv){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%pv}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 hv=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function gv(e){let t=e.rssLimitBytes??hv,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=o.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),_v(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 s(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:s}}function _v(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 vv(e,t,r={}){let i=we();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:N,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>ie.writeHeapSnapshot(e),listSnapshots:()=>{try{return n.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>o.join(i,e))}catch{return[]}},removeFile:e=>n.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}const yv=`CC_CANDYBAR_PARENT_PID`;function bv(e){let t=e[yv];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${yv} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function xv(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??1e3);return n.unref(),{disarm:()=>clearInterval(n)}}function Sv(t){try{return e.kill(t,0),!0}catch(e){return e.code===`EPERM`}}const Cv={load:()=>({}),save:()=>{},flush:()=>{}};function wv(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var Tv=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=Cv,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=wv(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 Ev=(e,t)=>O(t);function Dv(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 Ov=class{timer=null;pending=null;constructor(e,t=500,n=Ev){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=n.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 Dv(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{n.mkdirSync(o.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;n.writeFileSync(t,JSON.stringify(e),{mode:384}),n.chmodSync(t,384),n.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},kv=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Av(e){if(!e)throw new kv(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new kv(`invalid session id "${e}"`);return e}function jv(e){return Mv(()=>decodeURIComponent(e))}function Mv(e){try{return e()}catch(e){throw e instanceof URIError?new kv(`malformed wire encoding: ${e.message}`):e}}function Nv(e,t){let n=ve({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 Pv=(e,t)=>Nv(jv(e),t),Fv=(e,t)=>{let n=ve({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,jv(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`})`)}},Iv=(e,t)=>Nv(jv(e),t),Lv=(e,t)=>Nv(jv(e),t),Rv=(e,t)=>{let n=Av(jv(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},zv=(e,t)=>{let[n=``,...r]=Mv(()=>ft(e)),i=Av(n);if(r.length===0)throw new kv(`set-state: <key>/<value> is required (have keys: ${H_().join(`, `)})`);if(r.length%2!=0)throw new kv(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${H_().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new kv(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=av(t,n);if(!i.ok)throw new kv(`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})`)},Bv=/^-?\d+$/;function Vv(e,t,n){return e>n?t:e<t?n:e}const Hv=(e,t)=>{let[n=``,r=``,i=``]=Mv(()=>ft(e)),a=Av(n);if(!r)throw new kv(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Bv.test(i))throw new kv(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=ov(r);if(!s)throw new kv(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${H_().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&Bv.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=Vv(l+o,s.min,s.max),d=av(r,String(u));if(!d.ok)throw new kv(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},Uv=`config-override`,Wv=new Map([[st,Pv],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new kv(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Av(Mv(()=>decodeURIComponent(e.slice(0,n)))),i=Mv(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new kv(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new kv(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Uv),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Uv,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ct,Fv],[at,zv],[ot,Hv],[lt,Iv],[ut,Lv],[`toolbar-toggle`,Rv]]),Gv=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of mt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`toolbar-toggle`)){let e=ft(o);e.length>0&&e[0]&&(i=e[0])}let e=Wv.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof kv||(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(`
|
|
108
|
-
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new kv(e)}},Kv=new Map([...Wv,[it,Gv]]);Object.freeze([...Kv.keys()]);const qv=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`]),Jv=[[`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 Yv(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Jv){let i=Xv(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))qv.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function Xv(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 Zv(e,t){switch(e){case`vars`:return{what:e,vars:Qv(t)};case`segments`:return{what:e,segments:ny(t)};case`config`:return{what:e,config:ay(t)}}}function Qv(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=ey(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:$v(r.lastUpdatedMs())})}return o}function $v(e){return e===null?null:Math.max(0,Date.now()-e)}function ey(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,ty(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}`,ty(i));return t}function ty(e){return e.kind}function ny(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=ry(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:iy(t.template,i),lastRender:r.get(e)??null})}return o}function ry(e){let t=[],n=new Set;for(let r of Nn(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 iy(e,t){let n=new Set;for(let r of lh(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 ay(e){return e===null?null:e.config}const oy=[`vars`,`segments`,`config`];function sy(e){return typeof e==`string`&&oy.includes(e)}function cy(e){return Math.max(1,e-2)}var ly=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 _n(e);if(n.length===0)return O(`No entries in transcript`),F;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})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),F}catch(e){return I(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function uy(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 dy=class{calculateMessageCount(e){return e.filter(uy).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let e of t){let t=e.type||e.message?.role||e.message?.type;if(uy(e))n=e.timestamp;else if(t===`assistant`&&n){let t=(e.timestamp.getTime()-n.getTime())/1e3;t>.1&&t<300&&(r=t)}}return r}async getMetricsInfo(e,t){try{if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=(await _n(t.transcript_path)).filter(e=>!e.isSidechain),r=this.calculateMessageCount(n),i=this.calculateLastResponseTime(n);return P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:i,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}catch(t){return I(`metrics (${e}): ${t instanceof Error?t.message:String(t)}`)}}};const fy=new Map;function py(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var my=class{async getSessionId(){if(!process.env.TMUX_PANE)return F;let e=py(process.env.TMUX),t=fy.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await _e({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?P(n.stdout.trim()):F:I(`tmux display-message: ${n.reason}`);return fy.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function hy(e){return e<32||e===127||e>=128&&e<=159}function gy(e,t){let n=``;for(let t of e)n+=hy(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 _y=`\x1B[38;2;255;255;255m`,vy=`\x1B[48;2;200;40;40m`,yy=`\x1B[0m`,by=new mv;k(by.launchStats);const xy=new Zt({counters:by,logger:N}),Sy=new rn({watchers:xy,logger:N}),Cy=new jn,wy=new Tv,Ty=new ly,Ey=new dy,Dy=new my,Oy=new fv({gitService:Sy,sessionState:wy,watchers:xy});function ky(){n.mkdirSync(we(),{recursive:!0}),Ee(Te()),wy.useStorage(new Ov(Oe(),500,N)),e.on(`uncaughtException`,e=>{N(`error`,`uncaughtException: ${e.stack||e.message}`),Hy(1)}),e.on(`unhandledRejection`,e=>{N(`error`,`unhandledRejection: ${String(e)}`),Hy(1)});for(let t of[`SIGINT`,`SIGTERM`,`SIGHUP`])e.on(t,()=>{N(`info`,`received ${t}, shutting down`),Hy(0)});xv({anchor:bv(e.env),isAlive:Sv,onOrphaned:e=>{N(`info`,`parent watchdog: ${e}; shutting down`),Hy(0)}}),Ay(m.createServer({allowHalfOpen:!1},e=>{Uy(e)}),Te(),!1)}function Ay(t,n,r){t.removeAllListeners(`error`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){N(`error`,`server error: ${i.message}`),Hy(1);return}if(r){N(`info`,`lost rebind race; another daemon is alive — exiting`),e.exit(0);return}jy(t,n)}),t.listen(n,()=>Py(n))}async function jy(t,r){await Ny(r)&&(N(`info`,`another daemon is listening on socket — exiting`),e.exit(0)),await Ny(r)&&(N(`info`,`race: another daemon claimed the socket during recovery — exiting`),e.exit(0)),N(`warn`,`stale socket from crashed daemon — unlinking and rebinding`);try{n.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){N(`error`,`cannot unlink stale socket ${r}: ${e.message}`),Hy(1);return}}Ay(t,r,!0)}function My(e){return new Promise(t=>{let n=m.connect(e),r=!1,i=null,a=e=>{r||(r=!0,i&&clearTimeout(i),n.removeAllListeners(),n.destroy(),t(e))};n.once(`connect`,()=>a(`alive`)),n.once(`error`,e=>{let t=e.code;a(t===`ECONNREFUSED`||t===`ENOENT`||t===`ENOTSOCK`?`dead`:`unknown`)}),i=setTimeout(()=>a(`unknown`),50),i.unref()})}async function Ny(e){return await My(e)!==`dead`}function Py(t){try{n.chmodSync(t,384)}catch(e){N(`warn`,`chmod socket failed: ${e.message}`)}Ry(),N(`info`,`daemon up: pid=${e.pid} v=3 sock=${t}`),Fy(),Ly()}function Fy(){let t=import.meta.url,r=[];t.startsWith(`file://`)&&r.push(_(t)),e.argv[1]&&r.push(e.argv[1]);let i=new Map;for(let e of r)try{i.set(e,n.statSync(e).mtimeMs)}catch{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(n.statSync(e).mtimeMs!==t){N(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),Hy(0);return}}catch(e){N(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let Iy=null;function Ly(){Iy=gv(vv(by.startedAt.getTime(),e=>Hy(e))),Iy.arm()}function Ry(){let t=JSON.stringify({pid:e.pid,version:3,binPath:e.argv[1],startedAt:new Date().toISOString()});try{n.writeFileSync(De(),t,{mode:384}),n.chmodSync(De(),384)}catch(e){N(`warn`,`pidfile write failed: ${e.message}`)}}function zy(){try{n.unlinkSync(De())}catch{}}let By=0,Vy=!1;function Hy(t){if(!Vy){Vy=!0,setTimeout(()=>e.kill(e.pid,`SIGKILL`),500);try{Sy.close()}catch(e){N(`warn`,`gitService close failed: ${e.message}`)}try{Cy.close()}catch(e){N(`warn`,`usageStore close failed: ${e.message}`)}try{xy.closeAll()}catch(e){N(`warn`,`watcherRegistry close failed: ${e.message}`)}try{wy.flush()}catch(e){N(`warn`,`sessionState flush failed: ${e.message}`)}zy(),Rt(),e.exit(t)}}function Uy(e){By++,by.inFlight=By;let t=!1,n=(n,r)=>{if(t){r!==null&&N(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>Hy(r);try{e.end(Ne(n),i)}catch(e){N(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{by.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pe(e=>{Gy(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{N(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{N(`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=>{N(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),By=Math.max(0,By-1),by.inFlight=By})}const Wy=e=>({resp:e,exitAfterFlush:null});async function Gy(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Wy({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?N(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):N(`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 Wy({ok:!0,stats:by.snapshot({gitCache:Sy.getStats(),usageCache:Cy.getStats(),renderCacheSize:Oy.size,watchersActive:xy.size(),nextRestartReason:Iy?.describeNextRestart()??null})});if(e.kind===`render`){by.requestsTotal++;let t=Date.now();try{let{report:n}=Yv(e.hookData);for(let e of n.unknownTopLevelFields)N(`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 by.requestsErrored++,N(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Wy({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Jy(e.args),s=e.hookData.session_id,c=wy.get(s,`config-override`)??a,l=Oy.getOrCreate(i,e.cwd,c),u=je(e.termCols),d=cy(u??120),f={...Qy,width:d},p=``;if(l.state!==null){let t=await Zh(e.hookData,nb,e.cwd,l.state.neededInputPaths),n=Ug(ts(wy.get(e.hookData.session_id,`theme`),l.state.config.globals.palette));f.style=os(wy.get(e.hookData.session_id,`style`),l.state.config.globals.style),f.wrap=l.state.config.globals.autoWrap??!0,f.padding=l.state.config.globals.padding??1,p=N_(l.state.config,l.state.compiled,l.state.store,l.state.registry,t,n,f,l.state.lastRenderCellsBySegment)}let m=wy.get(e.hookData.session_id,`click.error`);m&&wy.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
|
|
109
|
-
`)||null,g
|
|
110
|
-
`})}catch(e){throw
|
|
111
|
-
`)}function
|
|
112
|
-
`);return e?`${i}\n${e}`:i}const
|
|
113
|
-
`);return}e.stdout.write(
|
|
107
|
+
`+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=jh(t),i=Mh(n,t??`<default>`,r),a=new pv,o=new Rg(a,i.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),s,c=[];try{s=P_(i,o,{cwd:e.cwd});for(let{key:e,spec:t}of sv(i))c.push(q_(e,t))}catch(e){for(let e of c)e();throw o.dispose(),e}return{config:i,store:a,registry:o,compiled:s,neededInputPaths:Jh(i),lastRenderCellsBySegment:new Map,validatorDisposers:c}}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 r=Oh(e.projectDir,e.cwd,e.configFile),i=new Map;for(let e of r){let t=o.dirname(e);if(!n.existsSync(t))continue;let r=o.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(r)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),s=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(s,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){N(`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 gv=16384;var _v=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<gv){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%gv}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 vv=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function yv(e){let t=e.rssLimitBytes??vv,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=o.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),bv(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 s(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:s}}function bv(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 xv(e,t,r={}){let i=we();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:N,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>ie.writeHeapSnapshot(e),listSnapshots:()=>{try{return n.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>o.join(i,e))}catch{return[]}},removeFile:e=>n.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}const Sv=`CC_CANDYBAR_PARENT_PID`;function Cv(e){let t=e[Sv];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${Sv} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function wv(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??1e3);return n.unref(),{disarm:()=>clearInterval(n)}}function Tv(t){try{return e.kill(t,0),!0}catch(e){return e.code===`EPERM`}}const Ev={load:()=>({}),save:()=>{},flush:()=>{}};function Dv(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var Ov=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=Ev,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=Dv(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 kv=(e,t)=>O(t);function Av(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 jv=class{timer=null;pending=null;constructor(e,t=500,n=kv){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=n.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 Av(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{n.mkdirSync(o.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;n.writeFileSync(t,JSON.stringify(e),{mode:384}),n.chmodSync(t,384),n.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},Mv=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Nv(e){if(!e)throw new Mv(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new Mv(`invalid session id "${e}"`);return e}function Pv(e){return Fv(()=>decodeURIComponent(e))}function Fv(e){try{return e()}catch(e){throw e instanceof URIError?new Mv(`malformed wire encoding: ${e.message}`):e}}function Iv(e,t){let n=ve({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 Lv=(e,t)=>Iv(Pv(e),t),Rv=(e,t)=>{let n=ve({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,Pv(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`})`)}},zv=(e,t)=>Iv(Pv(e),t),Bv=(e,t)=>Iv(Pv(e),t),Vv=(e,t)=>{let n=Nv(Pv(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},Hv=(e,t)=>{let[n=``,...r]=Fv(()=>ft(e)),i=Nv(n);if(r.length===0)throw new Mv(`set-state: <key>/<value> is required (have keys: ${G_().join(`, `)})`);if(r.length%2!=0)throw new Mv(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${G_().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Mv(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=cv(t,n);if(!i.ok)throw new Mv(`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})`)},Uv=/^-?\d+$/;function Wv(e,t,n){return e>n?t:e<t?n:e}const Gv=(e,t)=>{let[n=``,r=``,i=``]=Fv(()=>ft(e)),a=Nv(n);if(!r)throw new Mv(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Uv.test(i))throw new Mv(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=lv(r);if(!s)throw new Mv(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${G_().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&Uv.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=Wv(l+o,s.min,s.max),d=cv(r,String(u));if(!d.ok)throw new Mv(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},Kv=`config-override`,qv=new Map([[st,Lv],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Mv(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Nv(Fv(()=>decodeURIComponent(e.slice(0,n)))),i=Fv(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Mv(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Mv(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Kv),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Kv,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ct,Rv],[at,Hv],[ot,Gv],[lt,zv],[ut,Bv],[`toolbar-toggle`,Vv]]),Jv=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of mt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`toolbar-toggle`)){let e=ft(o);e.length>0&&e[0]&&(i=e[0])}let e=qv.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof Mv||(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(`
|
|
108
|
+
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new Mv(e)}},Yv=new Map([...qv,[it,Jv]]);Object.freeze([...Yv.keys()]);const Xv=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`]),Zv=[[`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 Qv(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Zv){let i=$v(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))Xv.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function $v(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 ey(e,t){switch(e){case`vars`:return{what:e,vars:ty(t)};case`segments`:return{what:e,segments:ay(t)};case`config`:return{what:e,config:cy(t)}}}function ty(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=ry(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:ny(r.lastUpdatedMs())})}return o}function ny(e){return e===null?null:Math.max(0,Date.now()-e)}function ry(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,iy(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}`,iy(i));return t}function iy(e){return e.kind}function ay(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=oy(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:sy(t.template,i),lastRender:r.get(e)??null})}return o}function oy(e){let t=[],n=new Set;for(let r of Nn(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 sy(e,t){let n=new Set;for(let r of uh(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 cy(e){return e===null?null:e.config}const ly=[`vars`,`segments`,`config`];function uy(e){return typeof e==`string`&&ly.includes(e)}function dy(e){return Math.max(1,e-2)}var fy=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 _n(e);if(n.length===0)return O(`No entries in transcript`),F;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})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),F}catch(e){return I(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function py(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 my=class{calculateMessageCount(e){return e.filter(py).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let e of t){let t=e.type||e.message?.role||e.message?.type;if(py(e))n=e.timestamp;else if(t===`assistant`&&n){let t=(e.timestamp.getTime()-n.getTime())/1e3;t>.1&&t<300&&(r=t)}}return r}async getMetricsInfo(e,t){try{if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=(await _n(t.transcript_path)).filter(e=>!e.isSidechain),r=this.calculateMessageCount(n),i=this.calculateLastResponseTime(n);return P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:i,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}catch(t){return I(`metrics (${e}): ${t instanceof Error?t.message:String(t)}`)}}};const hy=new Map;function gy(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var _y=class{async getSessionId(){if(!process.env.TMUX_PANE)return F;let e=gy(process.env.TMUX),t=hy.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await _e({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?P(n.stdout.trim()):F:I(`tmux display-message: ${n.reason}`);return hy.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function vy(e){return e<32||e===127||e>=128&&e<=159}function yy(e,t){let n=``;for(let t of e)n+=vy(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 by=`\x1B[38;2;255;255;255m`,xy=`\x1B[48;2;200;40;40m`,Sy=`\x1B[0m`,Cy=new _v;k(Cy.launchStats);const wy=new Zt({counters:Cy,logger:N}),Ty=new rn({watchers:wy,logger:N}),Ey=new jn,Dy=new Ov,Oy=new fy,ky=new my,Ay=new _y,jy=new hv({gitService:Ty,sessionState:Dy,watchers:wy});function My(){n.mkdirSync(we(),{recursive:!0}),Ee(Te()),Dy.useStorage(new jv(Oe(),500,N)),e.on(`uncaughtException`,e=>{N(`error`,`uncaughtException: ${e.stack||e.message}`),Gy(1)}),e.on(`unhandledRejection`,e=>{N(`error`,`unhandledRejection: ${String(e)}`),Gy(1)});for(let t of[`SIGINT`,`SIGTERM`,`SIGHUP`])e.on(t,()=>{N(`info`,`received ${t}, shutting down`),Gy(0)});wv({anchor:Cv(e.env),isAlive:Tv,onOrphaned:e=>{N(`info`,`parent watchdog: ${e}; shutting down`),Gy(0)}}),Ny(m.createServer({allowHalfOpen:!1},e=>{Ky(e)}),Te(),!1)}function Ny(t,n,r){t.removeAllListeners(`error`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){N(`error`,`server error: ${i.message}`),Gy(1);return}if(r){N(`info`,`lost rebind race; another daemon is alive — exiting`),e.exit(0);return}Py(t,n)}),t.listen(n,()=>Ly(n))}async function Py(t,r){await Iy(r)&&(N(`info`,`another daemon is listening on socket — exiting`),e.exit(0)),await Iy(r)&&(N(`info`,`race: another daemon claimed the socket during recovery — exiting`),e.exit(0)),N(`warn`,`stale socket from crashed daemon — unlinking and rebinding`);try{n.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){N(`error`,`cannot unlink stale socket ${r}: ${e.message}`),Gy(1);return}}Ny(t,r,!0)}function Fy(e){return new Promise(t=>{let n=m.connect(e),r=!1,i=null,a=e=>{r||(r=!0,i&&clearTimeout(i),n.removeAllListeners(),n.destroy(),t(e))};n.once(`connect`,()=>a(`alive`)),n.once(`error`,e=>{let t=e.code;a(t===`ECONNREFUSED`||t===`ENOENT`||t===`ENOTSOCK`?`dead`:`unknown`)}),i=setTimeout(()=>a(`unknown`),50),i.unref()})}async function Iy(e){return await Fy(e)!==`dead`}function Ly(t){try{n.chmodSync(t,384)}catch(e){N(`warn`,`chmod socket failed: ${e.message}`)}Vy(),N(`info`,`daemon up: pid=${e.pid} v=3 sock=${t}`),Ry(),By()}function Ry(){let t=import.meta.url,r=[];t.startsWith(`file://`)&&r.push(_(t)),e.argv[1]&&r.push(e.argv[1]);let i=new Map;for(let e of r)try{i.set(e,n.statSync(e).mtimeMs)}catch{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(n.statSync(e).mtimeMs!==t){N(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),Gy(0);return}}catch(e){N(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let zy=null;function By(){zy=yv(xv(Cy.startedAt.getTime(),e=>Gy(e))),zy.arm()}function Vy(){let t=JSON.stringify({pid:e.pid,version:3,binPath:e.argv[1],startedAt:new Date().toISOString()});try{n.writeFileSync(De(),t,{mode:384}),n.chmodSync(De(),384)}catch(e){N(`warn`,`pidfile write failed: ${e.message}`)}}function Hy(){try{n.unlinkSync(De())}catch{}}let Uy=0,Wy=!1;function Gy(t){if(!Wy){Wy=!0,setTimeout(()=>e.kill(e.pid,`SIGKILL`),500);try{Ty.close()}catch(e){N(`warn`,`gitService close failed: ${e.message}`)}try{Ey.close()}catch(e){N(`warn`,`usageStore close failed: ${e.message}`)}try{wy.closeAll()}catch(e){N(`warn`,`watcherRegistry close failed: ${e.message}`)}try{Dy.flush()}catch(e){N(`warn`,`sessionState flush failed: ${e.message}`)}Hy(),Rt(),e.exit(t)}}function Ky(e){Uy++,Cy.inFlight=Uy;let t=!1,n=(n,r)=>{if(t){r!==null&&N(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>Gy(r);try{e.end(Ne(n),i)}catch(e){N(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{Cy.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pe(e=>{Jy(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{N(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{N(`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=>{N(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Uy=Math.max(0,Uy-1),Cy.inFlight=Uy})}const qy=e=>({resp:e,exitAfterFlush:null});async function Jy(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return qy({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?N(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):N(`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 qy({ok:!0,stats:Cy.snapshot({gitCache:Ty.getStats(),usageCache:Ey.getStats(),renderCacheSize:jy.size,watchersActive:wy.size(),nextRestartReason:zy?.describeNextRestart()??null})});if(e.kind===`render`){Cy.requestsTotal++;let t=Date.now();try{let{report:n}=Qv(e.hookData);for(let e of n.unknownTopLevelFields)N(`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 Cy.requestsErrored++,N(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),qy({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Zy(e.args),s=e.hookData.session_id,c=Dy.get(s,`config-override`)??a,l=jy.getOrCreate(i,e.cwd,c),u=je(e.termCols),d=dy(u??120),f={...tb,width:d},p=``;if(l.state!==null){let t=await Qh(e.hookData,ab,e.cwd,l.state.neededInputPaths),n=Kg(ts(Dy.get(e.hookData.session_id,`theme`),l.state.config.globals.palette));f.style=os(Dy.get(e.hookData.session_id,`style`),l.state.config.globals.style),f.wrap=l.state.config.globals.autoWrap??!0,f.padding=l.state.config.globals.padding??1,f.charset=l.state.config.globals.charset??`unicode`,p=I_(l.state.config,l.state.compiled,l.state.store,l.state.registry,t,n,f,l.state.lastRenderCellsBySegment)}let m=Dy.get(e.hookData.session_id,`click.error`);m&&Dy.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
|
|
109
|
+
`)||null,g=$y(p,h,l.lastWarning),_=Date.now()-t,v=Ty.getStats(),y=Ey.getStats();return N(`info`,`render sid=${e.hookData.session_id??`?`} took=${_}ms termCols=${u??`?`} width=${d} git=${v.size}/${v.hits}h/${v.misses}m usage=${y.size}/${y.hits}h/${y.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),qy({ok:!0,output:g+`
|
|
110
|
+
`})}catch(e){throw Cy.requestsErrored++,e}}if(e.kind===`click`)return qy(await ob(e.verb,e.value));if(e.kind===`debug`){if(!uy(e.what))return qy({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${ly.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=jy.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?ib(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`):rb};return qy({ok:!0,debug:ey(e.what,n)})}return qy({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const Yy=`\x1B]8;;`,Xy=`\x1B]8;;\x1B\\`;function Zy(e){let{values:t,tokens:n}=v({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:Dh(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function Qy(e,t,n,r){let i=pt([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>yy(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${Yy}${i}\\${n}${r} ⚠ ${a[0]} ${Sy}${Xy}`,...a.slice(1).map(e=>`${Yy}${i}\\${n}${r} ${e} ${Sy}${Xy}`)].join(`
|
|
111
|
+
`)}function $y(e,t,n){let r=[];if(t&&r.push(Qy(lt,t,xy,by)),n&&r.push(Qy(ut,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
|
|
112
|
+
`);return e?`${i}\n${e}`:i}const eb={sessionState:Dy,dlog:N},tb={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},nb={...tb,width:1/0},rb=new Map;function ib(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Ug(i,{...nb,charset:t}));return n}const ab={gitProvider:Ty,usageStore:Ey,contextProvider:Oy,metricsProvider:ky,tmuxService:Ay,sessionState:Dy,log:N,clock:()=>new Date};function ob(e,t){let n=Yv.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,eb),{ok:!0,output:``}}catch(e){let t=e instanceof Mv?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const sb={connectMs:200,budgetMs:500};async function cb(t){let n=t.includes(`--json`),r=await lb();if(r.kind!==`ok`&&(e.stderr.write(`daemon-stats: ${He(r)}\n`),e.exit(1)),n){e.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
113
|
+
`);return}e.stdout.write(pb(r.value))}function lb(){return Ie({kind:`stats`},sb,e=>`stats`in e?e.stats:void 0)}function ub(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function db(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function fb(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 pb(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 ${fb(e.uptimeSec)}`),t.push(` rss ${ub(e.rssBytes)}`),t.push(` heapUsed ${ub(e.heapUsedBytes)}`),t.push(` heapTotal ${ub(e.heapTotalBytes)}`),t.push(` external ${ub(e.externalBytes)}`),t.push(` arrayBuffers ${ub(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 ${db(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 ${db(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(`
|
|
114
114
|
`)+`
|
|
115
|
-
`}const
|
|
116
|
-
`);return}e.stdout.write(
|
|
117
|
-
`;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?``:` ${
|
|
115
|
+
`}const mb={connectMs:200,budgetMs:500};async function hb(t,n){let r=n.includes(`--json`),i=await gb(t);if(i.kind!==`ok`&&(e.stderr.write(`${t}: ${He(i)}\n`),e.exit(1)),r){e.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
116
|
+
`);return}e.stdout.write(_b(i.value))}function gb(e){return Ie({kind:`debug`,what:e},mb,e=>`debug`in e?e.debug:void 0)}function _b(e){switch(e.what){case`vars`:return vb(e.vars);case`segments`:return yb(e.segments);case`config`:return bb(e.config);default:return e}}function vb(e){if(e.length===0)return`no variables (DSL not active)
|
|
117
|
+
`;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?``:` ${Sb(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${xb(i.value)}${e}${a}`)}return t.join(`
|
|
118
118
|
`)+`
|
|
119
|
-
`}function
|
|
119
|
+
`}function yb(e){if(e.length===0)return`no segments (DSL not active)
|
|
120
120
|
`;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(`
|
|
121
121
|
`)+`
|
|
122
|
-
`}function
|
|
122
|
+
`}function bb(e){return e===null?`config: DSL not active
|
|
123
123
|
`:JSON.stringify(e,null,2)+`
|
|
124
|
-
`}function
|
|
124
|
+
`}function xb(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Sb(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Cb(e){let t=o.resolve(e),r;try{r=n.readFileSync(t,`utf-8`)}catch(t){return{kind:`unreadable`,path:e,message:t instanceof Error?t.message:String(t)}}try{let{config:e}=jh(t);Mh(e,t,r)}catch(e){if(e instanceof cs)return{kind:`invalid`,message:e.message};throw e}return{kind:`valid`,path:e}}function wb(t){let n=t[0];(n===void 0||n===``)&&(e.stderr.write(`lint: missing <path>
|
|
125
125
|
Usage: cc-candybar lint <config-file>
|
|
126
|
-
`),e.exit(2)),Cb(
|
|
127
|
-
`,code:1};case`unreadable`:return{stream:e.stderr,text:`lint: cannot read ${t.path}: ${t.message}\n`,code:2}}}function
|
|
128
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:
|
|
126
|
+
`),e.exit(2)),Eb(Cb(n))}function Tb(t){switch(t.kind){case`valid`:return{stream:e.stdout,text:`✓ ${t.path}: config valid\n`,code:0};case`invalid`:return{stream:e.stderr,text:t.message+`
|
|
127
|
+
`,code:1};case`unreadable`:return{stream:e.stderr,text:`lint: cannot read ${t.path}: ${t.message}\n`,code:2}}}function Eb(t){let n=Tb(t);n.stream.write(n.text),e.exit(n.code)}function Db(){let e=kb();return e===null?null:n.readFileSync(e,`utf-8`)}function Ob(){let t=Db();t===null&&(e.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),e.exit(2)),e.stdout.write(t),e.exit(0)}function kb(){let t=o.join(`schema`,`cc-candybar.schema.json`),r=e.argv[1];if(r===void 0)return null;let i=o.dirname(o.resolve(r));for(;;){let e=o.join(i,t);if(n.existsSync(e))return e;let r=o.dirname(i);if(r===i)return null;i=r}}const Ab=`${xy}${by}`;function jb(e){return`${Ab}⚠ cc-candybar: ${Mb(e)}${Sy}\n`}function Mb(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: ${yy(e.message,60)}`;case`render_failed`:return`render failed: ${yy(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${yy(e.message,60)}`}}function Nb(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
128
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:jb(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function Pb(){let t=e.env.COLUMNS;if(t){let e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}let n=e.stderr.columns;if(n&&n>0)return n}function Fb(){console.log(`
|
|
129
129
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
130
130
|
|
|
131
131
|
Usage: cc-candybar [options]
|
|
@@ -166,7 +166,7 @@ Config tooling:
|
|
|
166
166
|
config [--json] The effective merged config. (All three query the
|
|
167
167
|
running daemon; none spawn one.)
|
|
168
168
|
|
|
169
|
-
`)}async function
|
|
169
|
+
`)}async function Ib(){try{(e.argv.includes(`--help`)||e.argv.includes(`-h`))&&(Fb(),e.exit(0));let n=e.argv[2];if(n===`install`&&(Pt(e.argv.slice(3)),e.exit(0)),n===`install-url-handler`&&(At(),e.exit(0)),n===`url-handle`){await Mt(e.argv[3]);return}if(n===`daemon`){My();return}if(n===`daemon-stats`&&(await cb(e.argv.slice(3)),e.exit(0)),n===`lint`){wb(e.argv.slice(3));return}if(n===`schema`){Ob();return}uy(n)&&(await hb(n,e.argv.slice(3)),e.exit(0)),e.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
170
170
|
|
|
171
171
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
172
172
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -182,4 +182,4 @@ Add to ~/.claude/settings.json:
|
|
|
182
182
|
Run with --help for more options.
|
|
183
183
|
|
|
184
184
|
To test output manually:
|
|
185
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),e.exit(1)),O(`Working directory: ${e.cwd()}`),O(`Process args:`,e.argv);let r=await t(e.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
185
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),e.exit(1)),O(`Working directory: ${e.cwd()}`),O(`Process args:`,e.argv);let r=await t(e.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),Fb(),e.exit(1));let i=Nb(await Ke(r,e.argv,e.cwd(),Pb()));i.debug!==null&&O(i.debug),i.kick&&Je(),e.stdout.write(i.output),e.exit(0)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Error generating statusline:`,n),e.exit(1)}}Ib();export{};
|