@xauyxau/hnch 1.11.0 → 1.12.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.
Files changed (2) hide show
  1. package/dist/index.js +11 -11
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import As from'yargs';import {hideBin}from'yargs/helpers';import Wt,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as De from'yjs';import {Awareness}from'y-protocols/awareness';import {mkdirSync,chmodSync,writeFileSync,unlinkSync,existsSync,readFileSync}from'fs';import {homedir}from'os';import {join}from'path';import {randomUUID}from'crypto';import {createInterface}from'readline';import {WebsocketProvider}from'y-websocket';import bi from'ws';import Qo from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var Yr="https://hnch.dev";function nt(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function an(){return join(nt(),"config.json")}function jn(){let e=nt();existsSync(e)||mkdirSync(e,{recursive:true});}function Ne(){let e=an();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function G(e){jn();let n={...Ne(),...e};writeFileSync(an(),JSON.stringify(n,null,2)+`
3
- `,"utf-8");}async function Jr(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,o=>{t.close(),n(o.trim());});})}function Gr(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function se(){let e=Ne(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let o=await Jr("Enter your display name: ");e.displayName=o||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=Yr,t=true),t&&G(e);let n=process.env.HNCH_RELAY_URL||e.relayUrl;return n=Gr(n),{participantId:e.participantId,displayName:e.displayName,relayUrl:n,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales}}function ot(e){jn();let n={...Ne()};for(let[o,r]of Object.entries(e))r===""?delete n[o]:r!==void 0&&(n[o]=r);writeFileSync(an(),JSON.stringify(n,null,2)+`
4
- `,"utf-8");}var vt="hnch_abstain";function fe(e){return e===vt}var Wr={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},_n=new Map(Object.entries(Wr).map(([e,t])=>[t,e]));function Pe(e){return e.role??"voter"}function W(e){let{revealedAt:t,skippedAt:n}=e;return t===void 0&&n===void 0?null:t===void 0?"skipped":n===void 0||t<=n?"revealed":"skipped"}var Ct={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},Fn={id:"t-shirt",cards:["XS","S","M","L","XL"]},Vn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},Yn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},Jn={id:"risk",cards:["Low","Medium","High","Critical"]},ae={[Ct.id]:Ct,[Fn.id]:Fn,[Vn.id]:Vn,[Yn.id]:Yn,[Jn.id]:Jn},Gn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function Wn(e){return e in Gn?Gn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(n=>n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var Ie="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",It=Ie.length,dn=Math.floor(It/2);function rt(e){let t=Ie.indexOf(e);if(t===-1)throw new Error(`fractional-index: invalid character '${e}'`);return t}function qn(e,t){return e.length>=t?e:e+"0".repeat(t-e.length)}function qr(e){let t=e.length-1;for(;t>0&&e[t]==="0";)t--;return e.slice(0,t+1)}function Kr(e,t){let n=e.length,o=Array.from({length:n+1}).fill(0),r=0;for(let s=n-1;s>=0;s--){let l=e[s]+t[s]+r;o[s+1]=l%It,r=Math.floor(l/It);}o[0]=r;let i=Array.from({length:n+1}).fill(0),a=0;for(let s=0;s<=n;s++){let l=o[s]+a*It;i[s]=Math.floor(l/2),a=l%2;}return i.slice(1)}function cn(e,t){let n=Ie[dn];if(e===null&&t===null)return n+n;if(t===null)return e+n+n+n+n;if(e===null)return zr(t);if(e>=t)throw new Error(`keyBetween: a must be < b (a='${e}', b='${t}')`);return Xr(e,t)}function zr(e){for(let t=e.length-1;t>=0;t--){let n=rt(e[t]);if(n>0)return e.slice(0,t)+Ie[n-1]+Ie[dn]}if(e.length>1)return e.slice(0,-1);throw new Error(`keyBetween: cannot generate key before '${e}' \u2014 use keyBetween(null, null) for the initial key`)}function Xr(e,t){let n=Math.max(e.length,t.length),o=qn(e,n).split("").map(l=>rt(l)),r=qn(t,n).split("").map(l=>rt(l)),a=Kr(o,r).map(l=>Ie[l]).join(""),s=qr(a);return s>e&&s<t?s:a>e&&a<t?a:Qr(e,t)}function Qr(e,t){for(let n=0;n<t.length;n++){let o=n<e.length?rt(e[n]):0;if(rt(t[n])===o+1)return (n<e.length?e.slice(0,n+1):e+Ie[0])+Ie[dn]}throw new Error(`keyBetween: space exhausted between '${e}' and '${t}'`)}var Zr="meta",it="settings",ei="participants",ti="rounds",ni="agenda",oi=["roomUuid","createdAt","createdBy","sessionEndedAt"],ri=["name","defaultScale","hostParticipantId"],ii=["displayName","joinedAt","role","leftAt","removedBy"],si=["id","title","description","ticketId","state","source","externalId","sortKey","createdAt","consumedAt","consumedByRoundId"],ai=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt","agendaItemId"];function bt(e){return e.getMap(Zr)}function Tt(e){return e.getMap(it)}function Rt(e){return e.getMap(ei)}function ln(e){return e.getArray(ti)}function At(e){return e.getArray(ni)}function st(e,t){let n={};for(let o of t){let r=e.get(o);r!==void 0&&(n[o]=r);}return n}function di(e){return st(bt(e),oi)}function ci(e){return st(Tt(e),ri)}function li(e){let t=Rt(e),n=[];return t.forEach((o,r)=>{let i=st(o,ii);n.push({id:r,...i});}),n.sort((o,r)=>o.joinedAt-r.joinedAt||o.id.localeCompare(r.id)),n}function ui(e){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}function pi(e){let t=st(e,ai),n=e.get("votes"),o=n?ui(n):{};return {...t,votes:o}}function mi(e){let t=ln(e),n=[];return t.forEach(o=>{n.push(pi(o));}),n}function fi(e){return st(e,si)}function gi(e){let t=At(e),n=[];return t.forEach(o=>{n.push(fi(o));}),n.sort((o,r)=>o.sortKey.localeCompare(r.sortKey)),n}function q(e){return {meta:di(e),settings:ci(e),participants:li(e),rounds:mi(e),agenda:gi(e)}}function Kn(e,t){if(bt(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let n=bt(e);n.set("roomUuid",t.roomUuid),n.set("createdAt",t.createdAt),n.set("createdBy",t.participantId);let o=Tt(e);t.sessionName!==void 0&&o.set("name",t.sessionName),o.set("defaultScale",t.defaultScale),o.set("hostParticipantId",t.participantId);let r=new De.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),Rt(e).set(t.participantId,r);});}function Ye(e,t){e.transact(()=>{let n=Rt(e),o=n.get(t.participantId),r=o??new De.Map;r.set("displayName",t.displayName),o===void 0&&r.set("joinedAt",Date.now()),r.delete("leftAt"),r.delete("removedBy"),o===void 0&&n.set(t.participantId,r);});}function Je(e,t){e.transact(()=>{let n=Tt(e);for(let[o,r]of Object.entries(t))r===void 0?n.delete(o):n.set(o,r);});}function un(e,t,n){e.transact(()=>{let o=Rt(e),r=o.get(t),i=r??new De.Map;i.set("displayName",n.displayName),i.set("joinedAt",n.joinedAt),n.role!==void 0&&i.set("role",n.role),r===void 0&&o.set(t,i);});}function pn(e,t){let n=t.scale??Tt(e).get("defaultScale");if(!n)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let o=new De.Map;o.set("id",t.id),o.set("createdAt",t.createdAt),o.set("createdBy",t.createdBy),o.set("scale",n),t.title!==void 0&&o.set("title",t.title),t.description!==void 0&&o.set("description",t.description),t.ticketId!==void 0&&o.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&o.set("parentRoundId",t.parentRoundId),t.agendaItemId!==void 0&&o.set("agendaItemId",t.agendaItemId),o.set("timerStartedAt",t.createdAt),o.set("votes",new De.Map),ln(e).push([o]);}),t.id}function zn(e,t,n){let o=at(e,t);if(!o)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{n.title!==void 0&&o.set("title",n.title),n.description!==void 0&&o.set("description",n.description);});}function at(e,t){let n=ln(e);for(let o=0;o<n.length;o+=1){let r=n.get(o);if(r.get("id")===t)return r}}function Xn(e,t,n,o){let r=at(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(n,o);});}function Qn(e,t,n){let o=at(e,t);if(!o)throw new Error(`clearVote: round ${t} not found`);o.get("revealedAt")===void 0&&e.transact(()=>{o.get("votes").delete(n);});}function mn(e,t,n){let o=at(e,t);if(!o)throw new Error(`revealRound: round ${t} not found`);if(o.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{o.set("revealedAt",n);});}function Zn(e,t,n){let o=at(e,t);if(!o)throw new Error(`skipRound: round ${t} not found`);if(o.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(o.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{o.set("skippedAt",n);});}function eo(e){e.transact(()=>{bt(e).set("sessionEndedAt",Date.now());});}function te(e){let{rounds:t}=e;if(t.length===0)return null;for(let n=t.length-1;n>=0;n-=1){let o=t[n];if(o.revealedAt===void 0)return o}return t.at(-1)}function to(e){let t=Object.values(e.votes);return t.length<2?false:t.every(n=>n===t[0])}function no(e,t){let n=At(e);for(let o=0;o<n.length;o++){let r=n.get(o);if(r.get("id")===t)return r}}function Et(e,t){if(!t.title?.trim()&&!t.ticketId?.trim())throw new Error("appendAgendaItem: at least one of {title, ticketId} is required");let n=crypto.randomUUID(),o=At(e),r=null;o.forEach(a=>{if(a.get("state")==="pending"){let s=a.get("sortKey");s!==void 0&&(r===null||s>r)&&(r=s);}});let i=cn(r,null);return e.transact(()=>{let a=new De.Map;a.set("id",n),a.set("state","pending"),a.set("source",t.source??"manual"),a.set("sortKey",i),a.set("createdAt",t.createdAt),t.title!==void 0&&a.set("title",t.title),t.description!==void 0&&a.set("description",t.description),t.ticketId!==void 0&&a.set("ticketId",t.ticketId),t.externalId!==void 0&&a.set("externalId",t.externalId),At(e).push([a]);}),n}function kt(e,t,n,o={}){let r=no(e,t);if(!r)throw new Error(`setAgendaItemState: item ${t} not found`);let i=r.get("state");if(!(i===n&&n==="consumed")){if(i!=="pending")throw new Error(`setAgendaItemState: invalid transition '${i}' \u2192 '${n}' for item ${t}`);e.transact(()=>{r.set("state",n),n==="consumed"&&(r.set("consumedAt",o.timestamp??Date.now()),o.consumedByRoundId!==void 0&&r.set("consumedByRoundId",o.consumedByRoundId));});}}function oo(e,t,n,o){kt(e,t,"consumed",{consumedByRoundId:n,timestamp:o});}function ro(e,t,n,o){let r=no(e,t);if(!r)throw new Error(`reorderAgendaItem: item ${t} not found`);let i=r.get("state");if(i!=="pending")throw new Error(`reorderAgendaItem: item ${t} is ${i}; only pending items may be reordered`);let a=cn(n??null,o??null);e.transact(()=>{r.set("sortKey",a);});}function Ge(e){for(let t of e.agenda)if(t.state==="pending")return t;return null}function io(e){let t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function so(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}function ao(e,t){let n=new Map;for(let d of t)n.set(d.id,d);let o=n.get(e);if(o===void 0||o.parentRoundId===void 0)return null;let r=new Set([o.id]),i=o,a=1;for(;i.parentRoundId!==void 0;){let d=n.get(i.parentRoundId);if(d===void 0||r.has(d.id))return null;r.add(d.id),i=d,a+=1;}let s=i,l=new Map;for(let d of t){if(d.parentRoundId===void 0)continue;let p=l.get(d.parentRoundId);p===void 0?l.set(d.parentRoundId,[d]):p.push(d);}let u=0,c=[s];for(;c.length>0;){let d=c.shift();u+=1;let p=l.get(d.id);p!==void 0&&c.push(...p);}return {chainRoot:s,depth:a,total:u}}var co="PBKDF2",hi="SHA-256",lo=new TextEncoder;function Si(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Oe(e,t){let n=await crypto.subtle.importKey("raw",lo.encode(e),co,false,["deriveBits"]),o=await crypto.subtle.deriveBits({name:co,salt:lo.encode(t),iterations:1e5,hash:hi},n,256);return Si(o)}var uo="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(uo.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${uo.length}`);function fn(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function po(e,t=true){let n=fn(e);return !t||n.length!==6?n:`${n.slice(0,3)}-${n.slice(3)}`}function xi(e,t){let n=new Map;t.forEach((i,a)=>n.set(i,a));let o=[...new Set(e.filter(i=>!n.has(i)))].toSorted(),r=new Map;return o.forEach((i,a)=>r.set(i,t.length+a)),i=>n.get(i)??r.get(i)??Number.MAX_SAFE_INTEGER}function gn(e,t){let n=new Map;for(let a of e)n.set(a,(n.get(a)??0)+1);let o=null,r=0,i=[...n.keys()].toSorted((a,s)=>t(a)-t(s));for(let a of i){let s=n.get(a);s>r&&(r=s,o=a);}return o}function mo(e,t){let n=Object.values(e);if(n.length===0)return null;let o=xi(n,t.cards);if(t.cards.every(a=>Number.isFinite(parseFloat(a)))){let a=n.map(parseFloat).filter(Number.isFinite);if(a.length===0)return {kind:"categorical",mode:gn(n,o)};let s=a.reduce((b,E)=>b+E,0)/a.length,l=[...a].toSorted((b,E)=>b-E),u=Math.floor(l.length/2),c=l.length%2===1?l[u]:(l[u-1]+l[u])/2,d=gn(n,o),p;if(new Set(n).size===1)p="unanimous";else {let b=n.map(A=>o(A)),E=Math.min(...b);p=Math.max(...b)-E<=1?"close":"spread";}return {kind:"numeric",mean:s,median:c,mode:d,spread:p}}return {kind:"categorical",mode:gn(n,o)}}function fo(e){return e.replaceAll(/\|/g,"\\|")}function wi(e){return e.replaceAll(/\\/g,"\\\\").replaceAll(/]/g,"\\]")}function yi(e){let n=(e.match(/`+/g)??[]).reduce((o,r)=>Math.max(o,r.length),0);return "`".repeat(n+1)}function hn(e){if(!e)return "";if(so(e))return ` ([${wi(e)}](<${e}>))`;let t=yi(e);return ` (${t}${e}${t})`}function vi(e){return e instanceof Map?e:new Map(Object.entries(e))}function Ci(e){let t=new Map;for(let r of e)t.set(r.id,r);function n(r){if(!r.parentRoundId)return r;let i=t.get(r.parentRoundId);return i?n(i):r}let o=new Map;for(let r of e){let i=n(r),a=o.get(i.id);a?a.push(r):o.set(i.id,[r]);}return o}function go(e,t){let n=new Map;e.scale.cards.forEach((a,s)=>n.set(a,s));let o=new Map;for(let[a,s]of Object.entries(e.votes)){let l=t.get(a)??a,u=o.get(s);u?u.push(l):o.set(s,[l]);}let r=[...o.entries()].map(([a,s])=>({card:a,scaleIndex:n.get(a)??Number.MAX_SAFE_INTEGER,voters:[...s].toSorted().map(fo)}));return r.sort((a,s)=>{let l=s.voters.length-a.voters.length;return l!==0?l:a.scaleIndex-s.scaleIndex}),["| Vote | Voters |","|------|--------|",...r.map(a=>`| ${fo(a.card)} | ${a.voters.join(", ")} |`)].join(`
5
- `)}function ho(e){let t=mo(e.votes,e.scale),n=e.timerStartedAt!=null&&e.revealedAt!=null?io(e.revealedAt-e.timerStartedAt):null,o=[];return t?.kind==="numeric"?o.push(`Avg ${t.mean.toFixed(1)} \xB7 Med ${t.median}`):t?.kind==="categorical"&&o.push(`Most common: ${t.mode}`),n!=null&&o.push(`Elapsed ${n}`),o.join(" \xB7 ")}function So(e){let{rounds:t}=e,n=vi(e.participants),o=new Map;for(let[c,d]of n)o.set(c,d.displayName);let r=t.filter(c=>c.revealedAt!=null);if(r.length===0)return "";let i=new Map;t.forEach((c,d)=>i.set(c.id,d+1));let a=Ci(r),s=new Set,l=[];for(let c of r)for(let[d,p]of a)if(p.includes(c)&&!s.has(d)){s.add(d),l.push(d);break}let u=[];for(let c of l){let d=a.get(c),p=d.find(f=>f.id===c),b=d.filter(f=>f.id!==c),E=i.get(p.id)??0,R=p.title?`## Round ${E} \u2014 ${p.title}${hn(p.ticketId)}`:`## Round ${E}${hn(p.ticketId)}`,A=go(p,o),H=ho(p),m=H?`${R}
2
+ import Os from'yargs';import {hideBin}from'yargs/helpers';import zt,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as $e from'yjs';import {Awareness}from'y-protocols/awareness';import {mkdirSync,chmodSync,writeFileSync,unlinkSync,existsSync,readFileSync}from'fs';import {homedir}from'os';import {join}from'path';import {randomUUID}from'crypto';import {createInterface}from'readline';import {WebsocketProvider}from'y-websocket';import Pi from'ws';import or from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var It="hnch_abstain";function me(e){return e===It}var Yr={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},_n=new Map(Object.entries(Yr).map(([e,t])=>[t,e]));var Ge={"racing-green":{base:"#0B3D2E",soft:"rgba(11,61,46,0.14)",ink:"#fff",label:"Racing Green"},dijon:{base:"#C9A227",soft:"rgba(201,162,39,0.18)",ink:"#000",label:"Dijon"},blue:{base:"#0A84FF",soft:"rgba(10,132,255,0.14)",ink:"#fff",label:"Blue"},indigo:{base:"#5E5CE6",soft:"rgba(94,92,230,0.14)",ink:"#fff",label:"Indigo"},violet:{base:"#BF5AF2",soft:"rgba(191,90,242,0.14)",ink:"#fff",label:"Violet"},pink:{base:"#FF375F",soft:"rgba(255,55,95,0.14)",ink:"#fff",label:"Pink"},red:{base:"#FF453A",soft:"rgba(255,69,58,0.14)",ink:"#fff",label:"Red"},orange:{base:"#FF9F0A",soft:"rgba(255,159,10,0.16)",ink:"#000",label:"Orange"},amber:{base:"#FFD60A",soft:"rgba(255,214,10,0.18)",ink:"#000",label:"Amber"},green:{base:"#30D158",soft:"rgba(48,209,88,0.14)",ink:"#000",label:"Green"},teal:{base:"#40C8E0",soft:"rgba(64,200,224,0.14)",ink:"#000",label:"Teal"},graphite:{base:"#1C1C1E",soft:"rgba(28,28,30,0.10)",ink:"#fff",label:"Graphite"}};var it=["racing-green","dijon","blue","indigo","violet","pink","red","orange","amber","green","teal","graphite"],Jr=/^#[0-9a-fA-F]{6}$/;function Kr(e){return Object.hasOwn(Ge,e)}function Oe(e){return e?Kr(e)?Ge[e].base:Jr.test(e)?e.toLowerCase():null:null}function Fn(e){let t=5381;for(let o=0;o<e.length;o++)t=(t<<5)+t+e.charCodeAt(o)|0;let n=Math.abs(t)%it.length;return it[n]}function Me(e){return e.role??"voter"}function J(e){let{revealedAt:t,skippedAt:n}=e;return t===void 0&&n===void 0?null:t===void 0?"skipped":n===void 0||t<=n?"revealed":"skipped"}var At={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},Vn={id:"t-shirt",cards:["XS","S","M","L","XL"]},Yn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},Jn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},Kn={id:"risk",cards:["Low","Medium","High","Critical"]},se={[At.id]:At,[Vn.id]:Vn,[Yn.id]:Yn,[Jn.id]:Jn,[Kn.id]:Kn},Wn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function Gn(e){return e in Wn?Wn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(n=>n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var Ae="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tt=Ae.length,cn=Math.floor(Tt/2);function st(e){let t=Ae.indexOf(e);if(t===-1)throw new Error(`fractional-index: invalid character '${e}'`);return t}function qn(e,t){return e.length>=t?e:e+"0".repeat(t-e.length)}function Wr(e){let t=e.length-1;for(;t>0&&e[t]==="0";)t--;return e.slice(0,t+1)}function Gr(e,t){let n=e.length,o=Array.from({length:n+1}).fill(0),r=0;for(let a=n-1;a>=0;a--){let l=e[a]+t[a]+r;o[a+1]=l%Tt,r=Math.floor(l/Tt);}o[0]=r;let i=Array.from({length:n+1}).fill(0),s=0;for(let a=0;a<=n;a++){let l=o[a]+s*Tt;i[a]=Math.floor(l/2),s=l%2;}return i.slice(1)}function ln(e,t){let n=Ae[cn];if(e===null&&t===null)return n+n;if(t===null)return e+n+n+n+n;if(e===null)return qr(t);if(e>=t)throw new Error(`keyBetween: a must be < b (a='${e}', b='${t}')`);return zr(e,t)}function qr(e){for(let t=e.length-1;t>=0;t--){let n=st(e[t]);if(n>0)return e.slice(0,t)+Ae[n-1]+Ae[cn]}if(e.length>1)return e.slice(0,-1);throw new Error(`keyBetween: cannot generate key before '${e}' \u2014 use keyBetween(null, null) for the initial key`)}function zr(e,t){let n=Math.max(e.length,t.length),o=qn(e,n).split("").map(l=>st(l)),r=qn(t,n).split("").map(l=>st(l)),s=Gr(o,r).map(l=>Ae[l]).join(""),a=Wr(s);return a>e&&a<t?a:s>e&&s<t?s:Xr(e,t)}function Xr(e,t){for(let n=0;n<t.length;n++){let o=n<e.length?st(e[n]):0;if(st(t[n])===o+1)return (n<e.length?e.slice(0,n+1):e+Ae[0])+Ae[cn]}throw new Error(`keyBetween: space exhausted between '${e}' and '${t}'`)}var Qr="meta",at="settings",Zr="participants",ei="rounds",ti="agenda",ni=["roomUuid","createdAt","createdBy","sessionEndedAt"],oi=["name","defaultScale","hostParticipantId"],ri=["displayName","joinedAt","role","leftAt","removedBy","avatarColor"],ii=["id","title","description","ticketId","state","source","externalId","sortKey","createdAt","consumedAt","consumedByRoundId"],si=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt","agendaItemId"];function Rt(e){return e.getMap(Qr)}function kt(e){return e.getMap(at)}function Nt(e){return e.getMap(Zr)}function un(e){return e.getArray(ei)}function Et(e){return e.getArray(ti)}function dt(e,t){let n={};for(let o of t){let r=e.get(o);r!==void 0&&(n[o]=r);}return n}function ai(e){return dt(Rt(e),ni)}function di(e){return dt(kt(e),oi)}function ci(e){let t=Nt(e),n=[];return t.forEach((o,r)=>{let i=dt(o,ri);n.push({id:r,...i});}),n.sort((o,r)=>o.joinedAt-r.joinedAt||o.id.localeCompare(r.id)),n}function li(e){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}function ui(e){let t=dt(e,si),n=e.get("votes"),o=n?li(n):{};return {...t,votes:o}}function pi(e){let t=un(e),n=[];return t.forEach(o=>{n.push(ui(o));}),n}function fi(e){return dt(e,ii)}function mi(e){let t=Et(e),n=[];return t.forEach(o=>{n.push(fi(o));}),n.sort((o,r)=>o.sortKey.localeCompare(r.sortKey)),n}function K(e){return {meta:ai(e),settings:di(e),participants:ci(e),rounds:pi(e),agenda:mi(e)}}function zn(e,t){if(Rt(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let n=Rt(e);n.set("roomUuid",t.roomUuid),n.set("createdAt",t.createdAt),n.set("createdBy",t.participantId);let o=kt(e);t.sessionName!==void 0&&o.set("name",t.sessionName),o.set("defaultScale",t.defaultScale),o.set("hostParticipantId",t.participantId);let r=new $e.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),t.avatarColor!==void 0&&r.set("avatarColor",t.avatarColor),Nt(e).set(t.participantId,r);});}function qe(e,t){e.transact(()=>{let n=Nt(e),o=n.get(t.participantId),r=o??new $e.Map;r.set("displayName",t.displayName),o===void 0&&r.set("joinedAt",Date.now()),t.avatarColor!==void 0&&r.set("avatarColor",t.avatarColor),r.delete("leftAt"),r.delete("removedBy"),o===void 0&&n.set(t.participantId,r);});}function ze(e,t){e.transact(()=>{let n=kt(e);for(let[o,r]of Object.entries(t))r===void 0?n.delete(o):n.set(o,r);});}function pn(e,t,n){e.transact(()=>{let o=Nt(e),r=o.get(t),i=r??new $e.Map;i.set("displayName",n.displayName),i.set("joinedAt",n.joinedAt),n.role!==void 0&&i.set("role",n.role),n.avatarColor!==void 0&&i.set("avatarColor",n.avatarColor),r===void 0&&o.set(t,i);});}function fn(e,t){let n=t.scale??kt(e).get("defaultScale");if(!n)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let o=new $e.Map;o.set("id",t.id),o.set("createdAt",t.createdAt),o.set("createdBy",t.createdBy),o.set("scale",n),t.title!==void 0&&o.set("title",t.title),t.description!==void 0&&o.set("description",t.description),t.ticketId!==void 0&&o.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&o.set("parentRoundId",t.parentRoundId),t.agendaItemId!==void 0&&o.set("agendaItemId",t.agendaItemId),o.set("timerStartedAt",t.createdAt),o.set("votes",new $e.Map),un(e).push([o]);}),t.id}function Xn(e,t,n){let o=ct(e,t);if(!o)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{n.title!==void 0&&o.set("title",n.title),n.description!==void 0&&o.set("description",n.description);});}function ct(e,t){let n=un(e);for(let o=0;o<n.length;o+=1){let r=n.get(o);if(r.get("id")===t)return r}}function Qn(e,t,n,o){let r=ct(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(n,o);});}function Zn(e,t,n){let o=ct(e,t);if(!o)throw new Error(`clearVote: round ${t} not found`);o.get("revealedAt")===void 0&&e.transact(()=>{o.get("votes").delete(n);});}function mn(e,t,n){let o=ct(e,t);if(!o)throw new Error(`revealRound: round ${t} not found`);if(o.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{o.set("revealedAt",n);});}function eo(e,t,n){let o=ct(e,t);if(!o)throw new Error(`skipRound: round ${t} not found`);if(o.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(o.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{o.set("skippedAt",n);});}function to(e){e.transact(()=>{Rt(e).set("sessionEndedAt",Date.now());});}function te(e){let{rounds:t}=e;if(t.length===0)return null;for(let n=t.length-1;n>=0;n-=1){let o=t[n];if(o.revealedAt===void 0)return o}return t.at(-1)}function no(e){let t=Object.values(e.votes);return t.length<2?false:t.every(n=>n===t[0])}function oo(e,t){let n=Et(e);for(let o=0;o<n.length;o++){let r=n.get(o);if(r.get("id")===t)return r}}function Pt(e,t){if(!t.title?.trim()&&!t.ticketId?.trim())throw new Error("appendAgendaItem: at least one of {title, ticketId} is required");let n=crypto.randomUUID(),o=Et(e),r=null;o.forEach(s=>{if(s.get("state")==="pending"){let a=s.get("sortKey");a!==void 0&&(r===null||a>r)&&(r=a);}});let i=ln(r,null);return e.transact(()=>{let s=new $e.Map;s.set("id",n),s.set("state","pending"),s.set("source",t.source??"manual"),s.set("sortKey",i),s.set("createdAt",t.createdAt),t.title!==void 0&&s.set("title",t.title),t.description!==void 0&&s.set("description",t.description),t.ticketId!==void 0&&s.set("ticketId",t.ticketId),t.externalId!==void 0&&s.set("externalId",t.externalId),Et(e).push([s]);}),n}function Dt(e,t,n,o={}){let r=oo(e,t);if(!r)throw new Error(`setAgendaItemState: item ${t} not found`);let i=r.get("state");if(!(i===n&&n==="consumed")){if(i!=="pending")throw new Error(`setAgendaItemState: invalid transition '${i}' \u2192 '${n}' for item ${t}`);e.transact(()=>{r.set("state",n),n==="consumed"&&(r.set("consumedAt",o.timestamp??Date.now()),o.consumedByRoundId!==void 0&&r.set("consumedByRoundId",o.consumedByRoundId));});}}function ro(e,t,n,o){Dt(e,t,"consumed",{consumedByRoundId:n,timestamp:o});}function io(e,t,n,o){let r=oo(e,t);if(!r)throw new Error(`reorderAgendaItem: item ${t} not found`);let i=r.get("state");if(i!=="pending")throw new Error(`reorderAgendaItem: item ${t} is ${i}; only pending items may be reordered`);let s=ln(n??null,o??null);e.transact(()=>{r.set("sortKey",s);});}function Xe(e){for(let t of e.agenda)if(t.state==="pending")return t;return null}function so(e){let t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function ao(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}function co(e,t){let n=new Map;for(let d of t)n.set(d.id,d);let o=n.get(e);if(o===void 0||o.parentRoundId===void 0)return null;let r=new Set([o.id]),i=o,s=1;for(;i.parentRoundId!==void 0;){let d=n.get(i.parentRoundId);if(d===void 0||r.has(d.id))return null;r.add(d.id),i=d,s+=1;}let a=i,l=new Map;for(let d of t){if(d.parentRoundId===void 0)continue;let p=l.get(d.parentRoundId);p===void 0?l.set(d.parentRoundId,[d]):p.push(d);}let u=0,c=[a];for(;c.length>0;){let d=c.shift();u+=1;let p=l.get(d.id);p!==void 0&&c.push(...p);}return {chainRoot:a,depth:s,total:u}}var lo="PBKDF2",gi="SHA-256",uo=new TextEncoder;function hi(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Be(e,t){let n=await crypto.subtle.importKey("raw",uo.encode(e),lo,false,["deriveBits"]),o=await crypto.subtle.deriveBits({name:lo,salt:uo.encode(t),iterations:1e5,hash:gi},n,256);return hi(o)}var po="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(po.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${po.length}`);function gn(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function fo(e,t=true){let n=gn(e);return !t||n.length!==6?n:`${n.slice(0,3)}-${n.slice(3)}`}function mo(e){let t=new Set(e).size;return t===1?"unanimous":t===2?"close":"spread"}function xi(e,t){let n=new Map;t.forEach((i,s)=>n.set(i,s));let o=[...new Set(e.filter(i=>!n.has(i)))].toSorted(),r=new Map;return o.forEach((i,s)=>r.set(i,t.length+s)),i=>n.get(i)??r.get(i)??Number.MAX_SAFE_INTEGER}function hn(e,t){let n=new Map;for(let s of e)n.set(s,(n.get(s)??0)+1);let o=null,r=0,i=[...n.keys()].toSorted((s,a)=>t(s)-t(a));for(let s of i){let a=n.get(s);a>r&&(r=a,o=s);}return o}function go(e,t){let n=Object.values(e);if(n.length===0)return null;let o=xi(n,t.cards);if(t.cards.every(s=>Number.isFinite(parseFloat(s)))){let s=n.map(parseFloat).filter(Number.isFinite);if(s.length===0)return {kind:"categorical",mode:hn(n,o),spread:mo(n)};let a=s.reduce((R,k)=>R+k,0)/s.length,l=[...s].toSorted((R,k)=>R-k),u=Math.floor(l.length/2),c=l.length%2===1?l[u]:(l[u-1]+l[u])/2,d=hn(n,o),p;if(new Set(n).size===1)p="unanimous";else {let R=n.map(A=>o(A)),k=Math.min(...R);p=Math.max(...R)-k<=1?"close":"spread";}return {kind:"numeric",mean:a,median:c,mode:d,spread:p}}return {kind:"categorical",mode:hn(n,o),spread:mo(n)}}function ho(e){return e.replaceAll(/\|/g,"\\|")}function Si(e){return e.replaceAll(/\\/g,"\\\\").replaceAll(/]/g,"\\]")}function wi(e){let n=(e.match(/`+/g)??[]).reduce((o,r)=>Math.max(o,r.length),0);return "`".repeat(n+1)}function xn(e){if(!e)return "";if(ao(e))return ` ([${Si(e)}](<${e}>))`;let t=wi(e);return ` (${t}${e}${t})`}function yi(e){return e instanceof Map?e:new Map(Object.entries(e))}function Ci(e){let t=new Map;for(let r of e)t.set(r.id,r);function n(r){if(!r.parentRoundId)return r;let i=t.get(r.parentRoundId);return i?n(i):r}let o=new Map;for(let r of e){let i=n(r),s=o.get(i.id);s?s.push(r):o.set(i.id,[r]);}return o}function xo(e,t){let n=new Map;e.scale.cards.forEach((s,a)=>n.set(s,a));let o=new Map;for(let[s,a]of Object.entries(e.votes)){let l=t.get(s)??s,u=o.get(a);u?u.push(l):o.set(a,[l]);}let r=[...o.entries()].map(([s,a])=>({card:s,scaleIndex:n.get(s)??Number.MAX_SAFE_INTEGER,voters:[...a].toSorted().map(ho)}));return r.sort((s,a)=>{let l=a.voters.length-s.voters.length;return l!==0?l:s.scaleIndex-a.scaleIndex}),["| Vote | Voters |","|------|--------|",...r.map(s=>`| ${ho(s.card)} | ${s.voters.join(", ")} |`)].join(`
3
+ `)}function So(e){let t=go(e.votes,e.scale),n=e.timerStartedAt!=null&&e.revealedAt!=null?so(e.revealedAt-e.timerStartedAt):null,o=[];return t?.kind==="numeric"?o.push(`Avg ${t.mean.toFixed(1)} \xB7 Med ${t.median}`):t?.kind==="categorical"&&o.push(`Most common: ${t.mode}`),n!=null&&o.push(`Elapsed ${n}`),o.join(" \xB7 ")}function wo(e){let{rounds:t}=e,n=yi(e.participants),o=new Map;for(let[c,d]of n)o.set(c,d.displayName);let r=t.filter(c=>c.revealedAt!=null);if(r.length===0)return "";let i=new Map;t.forEach((c,d)=>i.set(c.id,d+1));let s=Ci(r),a=new Set,l=[];for(let c of r)for(let[d,p]of s)if(p.includes(c)&&!a.has(d)){a.add(d),l.push(d);break}let u=[];for(let c of l){let d=s.get(c),p=d.find(g=>g.id===c),R=d.filter(g=>g.id!==c),k=i.get(p.id)??0,T=p.title?`## Round ${k} \u2014 ${p.title}${xn(p.ticketId)}`:`## Round ${k}${xn(p.ticketId)}`,A=xo(p,o),B=So(p),f=B?`${T}
6
4
 
7
5
  ${A}
8
6
 
9
- ${H}`:`${R}
7
+ ${B}`:`${T}
10
8
 
11
- ${A}`;u.push(m);for(let f of b){let v=`### Re-vote ${i.get(f.id)??0}${hn(f.ticketId)}`,N=go(f,o),w=ho(f),D=w?`${v}
9
+ ${A}`;u.push(f);for(let g of R){let v=`### Re-vote ${i.get(g.id)??0}${xn(g.ticketId)}`,P=xo(g,o),b=So(g),O=b?`${v}
12
10
 
13
- ${N}
11
+ ${P}
14
12
 
15
- ${w}`:`${v}
13
+ ${b}`:`${v}
16
14
 
17
- ${N}`;u.push(D);}}return u.join(`
15
+ ${P}`;u.push(O);}}return u.join(`
18
16
 
19
17
  `)+`
20
- `}function Nt(e,t,n){if(e.startsWith("custom-")){let r=(n??[]).find(i=>i.id===e);return r?{id:r.id,cards:r.cards}:void 0}let o=ae[e];if(o){let r=(t??{})[e]??[];if(r.length===0)return o;let i=o.cards.filter((a,s)=>!r.includes(s));return i.length===0?void 0:{id:e,cards:i}}}function Pt(e,t){let n=Object.keys(ae).map(r=>Nt(r,e,t)).filter(r=>r!==void 0),o=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...n,...o]}function Me(e,t){if(e.startsWith("custom-")){let n=(t??[]).find(o=>o.id===e);if(n&&n.label.trim().length>0)return n.label}return Wn(e)}async function xo(e,t){let n=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!n.ok)throw new Error(`POST /rooms failed: ${n.status}`);return await n.json()}async function de(e,t){let n=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(n.status===404){let o=await n.json().catch(()=>null);throw new Error(`Room not found: ${o?.reason??"unknown-room"}`)}if(!n.ok)throw new Error(`GET /rooms/:code failed: ${n.status}`);return await n.json()}async function Sn(e,t,n){let o=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:n})});if(!o.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${o.status}`)}function wo(e){let n=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,o={did:e.deviceId};e.passwordHash!==void 0&&(o.pw=e.passwordHash);let r=new WebsocketProvider(n,e.roomUuid,e.doc,{params:o,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:bi}),i=u=>{e.onStatusChange?.(u.status);},a=u=>{if(u===null)return;let c=_n.get(u.code);c!==void 0&&(e.onRejection?.(c),r.shouldConnect=false,r.disconnect());};r.on("status",i),r.on("connection-close",a);let s=false,l=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(u){if(u.passwordHash===l)return;l=u.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let d={did:r.params.did??""};l!==void 0&&(d.pw=l),r.params=d,r.connect();},disconnect(){s||(s=true,r.off("status",i),r.off("connection-close",a),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Ai=5e3;function yo(e,t,n){let o=null,r=null;function i(){let c=new Set;return t.getStates().forEach(d=>{let p=d.participantId;typeof p=="string"&&c.add(p);}),c}function a(){return e.getMap(it).get("hostParticipantId")}function s(){r!==null&&(clearTimeout(r),r=null),o=null;}function l(){let c=a(),d=o;if(o=null,!d||c!==d)return;let p=i();if(p.has(c))return;let b=[...p].toSorted();if(b.length===0)return;let E=b[0];E===n&&Je(e,{hostParticipantId:E});}function u(){let c=a();if(!c)return;if(i().has(c)){s();return}o!==c&&(s(),o=c,r=setTimeout(()=>{r=null,l();},Ai));}return t.on("change",u),e.getMap(it).observe(u),u(),{stop(){s(),t.off("change",u),e.getMap(it).unobserve(u);}}}async function Io(e){let t,n=await xo(e.relayUrl);e.password&&(t=await Oe(e.password,n.uuid),await Sn(e.relayUrl,n.uuid,t));let o=new De.Doc,r=new Awareness(o),i=Date.now();return Kn(o,{roomUuid:n.uuid,createdAt:i,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??Ct,...e.sessionName!==void 0&&{sessionName:e.sessionName}}),r.setLocalStateField("participantId",e.participantId),We({doc:o,awareness:r,roomCode:n.code,roomUuid:n.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function bo(e){let t=await de(e.relayUrl,e.roomCode),n;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");n=await Oe(e.password,t.uuid);}let o=new De.Doc,r=new Awareness(o);return Ye(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),We({doc:o,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:n,onRejection:e.onRejection})}function We(e){let{doc:t,awareness:n,participantId:o,relayUrl:r,roomUuid:i}=e,a=new Set,s=new Set,l=new Set,u=wo({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:o,passwordHash:e.passwordHash,awareness:n,onStatusChange(m){a.forEach(f=>f(m));},onRejection(m){console.error(`Connection rejected: ${m}`),e.onRejection?.(m);}}),c=yo(t,n,o),d=()=>{s.forEach(m=>m());};t.getMap("meta").observeDeep(d),t.getMap("settings").observeDeep(d),t.getMap("participants").observeDeep(d),t.getArray("rounds").observeDeep(d);function p(){let m=new Set;return n.getStates().forEach(f=>{let y=f.participantId;typeof y=="string"&&m.add(y);}),m}let b=new Set,E=setInterval(()=>{let m=q(t),f=te(m);if(!f||f.revealedAt!==void 0||b.has(f.id))return;let y=p();if(y.size===0)return;let v=m.participants.filter(w=>y.has(w.id)&&Pe(w)==="voter");if(v.length===0)return;v.filter(w=>w.id in f.votes).length>=v.length&&(b.add(f.id),mn(t,f.id,Date.now()));},250),R=t.getMap("settings").get("hostParticipantId"),A=()=>{let m=t.getMap("settings").get("hostParticipantId");m!==R&&m!==void 0&&l.forEach(f=>f(m)),R=m;};t.getMap("settings").observe(A);let H=false;return {doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return q(t)},current(){return te(q(t))},isHost(){return q(t).settings.hostParticipantId===o},onlineIds:p,vote(m){let f=te(q(t));f&&Xn(t,f.id,o,m);},unvote(){let m=te(q(t));m&&Qn(t,m.id,o);},reveal(){let m=te(q(t));m&&mn(t,m.id,Date.now());},skip(){let m=te(q(t));m&&Zn(t,m.id,Date.now());},newRound(m,f,y){let v=randomUUID(),N=Date.now();return t.transact(()=>{pn(t,{id:v,createdAt:N,createdBy:o,...m!==void 0&&{title:m},...f!==void 0&&{ticketId:f},...y!==void 0&&{agendaItemId:y}}),y!==void 0&&oo(t,y,v,N);}),v},revote(){let m=te(q(t)),f=randomUUID();return pn(t,{id:f,createdAt:Date.now(),createdBy:o,...m?.id!==void 0&&{parentRoundId:m.id},...m?.title!==void 0&&{title:m.title},...m?.description!==void 0&&{description:m.description},...m?.ticketId!==void 0&&{ticketId:m.ticketId},...m?.agendaItemId!==void 0&&{agendaItemId:m.agendaItemId}}),f},updateRoundDescriptor(m,f){zn(t,m,f);},updateName(m){Je(t,{name:m});},updateScale(m){Je(t,{defaultScale:m});},updateDisplayName(m){let v=q(t).participants.find(N=>N.id===o)?.joinedAt??Date.now();un(t,o,{displayName:m,joinedAt:v});},async updateAccess(m,f){let y=null;if(m==="password"){if(!f)throw new Error("Password required for password mode");y=await Oe(f,i);}await Sn(r,i,y),u.updateCredentials({passwordHash:y});},handoffHost(m){if(!this.isHost())throw new Error("Only the current host can hand off");if(!p().has(m))throw new Error("Target participant is not online");if(!q(t).participants.some(N=>N.id===m))throw new Error("Target participant does not exist");Je(t,{hostParticipantId:m});},toggleRole(){let f=q(t).participants.find(w=>w.id===o),v=Pe(f??{})==="viewer"?"voter":"viewer",N=f?.joinedAt??Date.now();un(t,o,{displayName:f?.displayName??"",joinedAt:N,role:v});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");eo(t);},onChange(m){return s.add(m),()=>s.delete(m)},onStatusChange(m){return a.add(m),()=>a.delete(m)},onHostChange(m){return l.add(m),()=>l.delete(m)},disconnect(){H||(H=true,clearInterval(E),c.stop(),t.getMap("meta").unobserveDeep(d),t.getMap("settings").unobserveDeep(d),t.getMap("settings").unobserve(A),t.getMap("participants").unobserveDeep(d),t.getArray("rounds").unobserveDeep(d),u.disconnect());}}}function Ao(e){let t=fn(e);return t===""?null:t}var Di=1440*60*1e3;function wn(){return join(nt(),"last-session.json")}function Oi(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.roomCode=="string"&&typeof t.roomUuid=="string"&&typeof t.lastSeenAt=="number"&&(t.passwordHash===void 0||typeof t.passwordHash=="string")}function Dt(){let e=wn();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !Oi(t)||Date.now()-t.lastSeenAt>Di?(V(),null):t}catch{return V(),null}}function Ot(e){let t=nt();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let n=wn();writeFileSync(n,JSON.stringify(e,null,2)+`
21
- `,{encoding:"utf-8",mode:384}),chmodSync(n,384);}function V(){let e=wn();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function Mt(e){let t=true;try{await e.clearLastSession();}catch(n){t=false,e.logger.error(`Failed to clear cached session: ${n instanceof Error?n.message:String(n)}`);}return t?e.logger.error("Session expired (room no longer exists). Cached session cleared."):e.logger.error("Session expired. Could not delete ~/.config/hnch/last-session.json \u2014 please remove it manually."),e.exit(1)}function $t(e){let t=e.doc.getMap("meta"),n=null,o=false;function r(){if(o)return;let i=t.get("sessionEndedAt");if(i==null||i===n)return;n=i;let a=t.get("createdBy"),s=a===e.localParticipantId,l=e.doc.getMap("participants"),u=e.doc.getMap("settings").get("hostParticipantId")??a,c="host";if(u){let p=l.get(u)?.get("displayName");typeof p=="string"&&p.length>0&&(c=p);}setImmediate(()=>{o||e.onEnded({isLocal:s,hostName:c,timestamp:i});});}return t.observe(r),r(),()=>{o=true,t.unobserve(r);}}var Mi="@xauyxau/hnch";function Ut(e){return po(e)}function Bt(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function Ht(e){return `npx ${Mi} join ${e}`}function yn(e){let t=e.trim();return t===""?void 0:t}function Lt(e){return e?{title:e.title??"",ticketId:e.ticketId??"",agendaItemId:e.id}:{title:"",ticketId:"",agendaItemId:void 0}}function Ro(e,t,n){return [e,yn(t),n]}var $i={connecting:"yellow",connected:"green",disconnected:"red"};function No({roomCode:e,sessionName:t,status:n,isHost:o}){let r=t?`${e} \xB7 ${t}`:e;return jsxs(Box,{borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[jsxs(Text,{bold:true,children:["hnch \xB7 ",r]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:$i[n],children:n})]})]})}function he({items:e,onSelect:t,onClose:n,title:o}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(s=>!s.disabled),[i,a]=useState(Math.max(r,0));return useInput((s,l)=>{if(l.upArrow)a(u=>{let c=(u-1+e.length)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c-1+e.length)%e.length,d++;return c});else if(l.downArrow)a(u=>{let c=(u+1)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c+1)%e.length,d++;return c});else if(l.return){let u=e[i];u&&!u.disabled&&t(u.value);}else l.escape&&n?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Box,{flexDirection:"column",children:e.map((s,l)=>{let u=l===i,c=s.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...u&&{color:"cyan"},dimColor:c,children:u?">":" "}),jsx(Text,{bold:u,dimColor:c,children:s.label}),s.detail&&jsx(Text,{dimColor:true,children:s.detail})]},s.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function Y({value:e,onChange:t,onSubmit:n,onCancel:o,placeholder:r,isActive:i=true,mask:a=false}){useInput((c,d)=>{d.escape?o?.():d.return?n(e):d.backspace||d.delete?t(e.slice(0,-1)):c&&!d.ctrl&&!d.meta&&t(e+c);},{isActive:i});let s=a&&e.length>0?"*".repeat(e.length):e,l=s.length>0?s:r??"",u=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:u,children:l}),jsx(Text,{inverse:true,children:" "})]})}function Mo({mode:e,password:t,onModeChange:n,onPasswordChange:o,onClose:r}){let[i,a]=useState(e==="open"?0:1),[s,l]=useState(false);return useEffect(()=>{a(e==="open"?0:1);},[e]),useInput((u,c)=>{if(c.leftArrow)a(d=>Math.max(0,d-1));else if(c.rightArrow)a(d=>Math.min(1,d+1));else if(c.return){let d=i===0?"open":"password";d!==e&&n(d),d==="password"&&l(true);}else c.escape&&r?.();},{isActive:!s}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((u,c)=>{let d=c===i,p=u===e,b=u==="open"?"Open":"Password";return jsx(Text,{inverse:d,bold:p,...p&&{color:"cyan"},children:p?`[${b}]`:` ${b} `},u)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(Y,{value:t,onChange:o,onSubmit:()=>l(false),onCancel:()=>l(false),placeholder:"(required to join)",isActive:s,mask:true}),!s&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),s&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function Bo({scaleId:e,cards:t,disabledIndices:n,onOverrideChange:o,onClose:r}){let i=useMemo(()=>new Set(n),[n]),[a,s]=useState(0),l=u=>{let c=new Set(i);if(c.has(u))c.delete(u);else {if(c.size>=t.length-1)return;c.add(u);}let d=Array.from(c).toSorted((p,b)=>p-b);o(e,d);};return useInput((u,c)=>{c.leftArrow?s(d=>Math.max(0,d-1)):c.rightArrow?s(d=>Math.min(t.length-1,d+1)):u===" "?l(a):(c.return||c.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((u,c)=>{let d=c===a,p=i.has(c);return jsx(Text,{inverse:d,bold:!p,...!p&&{color:"cyan"},strikethrough:p,dimColor:p,children:u},u)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function En({initialName:e="",initialCards:t=[],onSave:n,onCancel:o}){let r=e.length>0,[i,a]=useState(e),[s,l]=useState(t.length>0?t:[""]),[u,c]=useState(0),[d,p]=useState("editing-name"),[b,E]=useState(""),R=()=>{let m=i.trim();if(m.length===0||m.length>40){E("Name must be 1-40 characters");return}a(m),E(""),p("editing-cards");},A=()=>{let m=i.trim();if(m.length===0||m.length>40){E("Name must be 1-40 characters");return}let f=s.map(v=>v.trim()).filter(v=>v.length>0),y=Array.from(new Set(f));if(y.length<2){E("Need at least 2 unique non-empty cards");return}E(""),n(m,y);};return useInput((m,f)=>{if(d==="editing-cards"){if(f.leftArrow)c(y=>Math.max(0,y-1));else if(f.rightArrow)c(y=>{let v=y+1;return v>=s.length&&s.length<25?(l(N=>[...N,""]),v):Math.min(v,s.length-1)});else if(f.return)A();else if(f.escape)o();else if(f.tab)p("editing-name");else if(f.backspace){let y=s[u]||"";if(y.length===0){if(s.length>2){let v=s.filter((N,w)=>w!==u);l(v),c(Math.max(0,u-1));}}else {let v=[...s];v[u]=y.slice(0,-1),l(v);}}else if(m&&!f.ctrl&&!f.meta){let y=s[u]||"";if(y.length<10){let v=[...s];v[u]=y+m,l(v);}}}},{isActive:d==="editing-cards"}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r?"\u2500\u2500 Edit Custom Scale \u2500\u2500":"\u2500\u2500 Create Custom Scale \u2500\u2500"}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Name:"}),jsx(Y,{value:i,onChange:a,onSubmit:R,onCancel:o,placeholder:"Scale name",isActive:d==="editing-name"})]}),d==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:s.map((m,f)=>{let y=f===u;return jsx(Text,{inverse:y,...!y&&{color:"cyan"},children:m.length>0?m:"\xB7"},f)})})]}),b&&jsx(Text,{color:"red",children:b}),jsx(Text,{dimColor:true,children:d==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function Ft({scales:e,selectedScaleId:t,presetOverrides:n,customScales:o=[],onSelect:r,onOverrideChange:i,onCustomScaleCreate:a,onCustomScaleEdit:s,onCustomScaleDelete:l,onClose:u,showNoneOption:c=false}){let[d,p]=useState(0),[b,E]=useState(null),[R,A]=useState("browsing"),[H,m]=useState(null),[f,y]=useState(null),v=a?[...e,{id:"__create-custom__",cards:[]}]:e,N=v.length;if(useInput((w,D)=>{if(R==="browsing"){if(D.escape){u();return}if(N===0)return;if(D.upArrow)p(S=>(S-1+N)%N);else if(D.downArrow)p(S=>(S+1)%N);else if(D.return){let S=v[d];if(!S)return;if(S.id==="__create-custom__"){A("creating");return}S.id in ae?E(b===S.id?null:S.id):r(S.id);}else if(w===" "){let S=v[d];S&&S.id!=="__create-custom__"&&r(S.id);}else if(w==="e"||w==="E"){let S=v[d];s&&S?.id.startsWith("custom-")&&(m(S.id),A("editing"));}else if(w==="d"||w==="D"){let S=v[d];l&&S?.id.startsWith("custom-")&&(y(S.id),A("confirming-delete"));}}else R==="confirming-delete"&&(w==="y"||w==="Y"?(f&&l&&l(f),y(null),A("browsing")):(w==="n"||w==="N"||D.escape)&&(y(null),A("browsing")));},{isActive:R==="browsing"&&b===null||R==="confirming-delete"}),R==="creating")return jsx(En,{onSave:(w,D)=>{a&&a(w,D),A("browsing");},onCancel:()=>A("browsing")});if(R==="editing"&&H){let w=o?.find(S=>S.id===H);if(e.find(S=>S.id===H)&&w)return jsx(En,{initialName:w.label,initialCards:w.cards,onSave:(S,_)=>{s&&s(H,S,_),m(null),A("browsing");},onCancel:()=>{m(null),A("browsing");}})}if(R==="confirming-delete"&&f){let w=v.find(S=>S.id===f),D=w?Me(w.id,o):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",D,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return v.length===0?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"(no scales available)"}),jsx(Text,{dimColor:true,children:"esc back"})]}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{flexDirection:"column",children:v.map((w,D)=>{let S=D===d,_=w.id===t,pe=b===w.id,oe=w.id in ae,re=w.id==="__create-custom__",J=w.cards.join(", "),I=c&&w.id==="",T=I?"(none)":re?"[+ Create custom scale]":Me(w.id,o);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...S&&{color:"cyan"},children:S?">":" "}),jsx(Text,{bold:S,children:T}),!I&&!re&&jsx(Text,{dimColor:true,children:J}),_&&jsx(Text,{color:"cyan",children:"[current]"})]}),pe&&!I&&!re&&jsx(Box,{paddingLeft:2,children:oe?jsx(Bo,{scaleId:w.id,cards:ae[w.id]?.cards??[],disabledIndices:n?.[w.id]??[],onOverrideChange:i,onClose:()=>E(null)}):null})]},w.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let w=d<v.length?v[d]:null;return w?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${s?" [e] edit":""}${l?" [d] delete":""} esc back`:w&&w.id in ae?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function Ki(e,t){return t?[...e]:e.filter(n=>n.value==="display-name")}function Ho({sessionName:e,displayName:t,currentScale:n,accessMode:o,presetOverrides:r,customScales:i,isHost:a=true,onChangeName:s,onChangeScale:l,onChangeDisplayName:u,onChangeAccess:c,onClose:d}){let[p,b]=useState(r??{}),E=useMemo(()=>Pt(p,i),[p,i]),[R,A]=useState("main-menu"),[H,m]=useState(e??""),[f,y]=useState(t),[v,N]=useState(o==="password"?"password":"open"),[w,D]=useState(""),[S,_]=useState(false),pe=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Me(n.id,i)}]`},{label:"Access",value:"access",detail:`[${o==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],oe=Ki(pe,a);function re(M){!a&&M!=="display-name"||(M==="room-name"?(m(e??""),A("editing-room-name")):M==="scale"?A("picking-scale"):M==="access"?A("picking-access"):M==="display-name"&&(y(t),A("editing-display-name")));}function J(M){let L=M.trim()===""?void 0:M.trim();s(L),A("main-menu");}function I(M){let L=M.trim();L.length>0&&(u(L),process.nextTick(()=>G({displayName:L}))),A("main-menu");}function T(M){let L=E.find(z=>z.id===M);L&&l(L),A("main-menu");}function O(M,L){let z={...p};L.length===0?delete z[M]:z[M]=L,b(z),G({presetOverrides:Object.keys(z).length>0?z:void 0});}async function F(M,L){_(true);try{await c(M,L),N(M),D(M==="password"?L??"":"");}catch(z){console.error(`Failed to update access: ${z}`);}finally{_(false),A("main-menu");}}return R==="main-menu"?jsx(he,{title:"\u2500\u2500 Settings \u2500\u2500",items:oe,onSelect:re,onClose:d}):R==="editing-room-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Room name: "}),jsx(Y,{value:H,onChange:m,onSubmit:J,onCancel:()=>A("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):R==="editing-display-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(Y,{value:f,onChange:y,onSubmit:I,onCancel:()=>A("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):R==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Ft,{scales:E,selectedScaleId:n.id,presetOverrides:p,onSelect:T,onOverrideChange:O,onClose:()=>A("main-menu")})]}):R==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),S&&jsx(Text,{dimColor:true,children:"Updating access..."}),!S&&jsx(Mo,{mode:v,password:w,onModeChange:M=>{M==="open"&&F("open");},onPasswordChange:D,onClose:()=>A("main-menu")})]}):jsx(Box,{})}function Jt({participants:e,onlineIds:t,hostId:n,votes:o,revealed:r,participantId:i}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(a=>{let s=t.has(a.id),l=s?"\u25CF":"\u25CB",u=s?"green":"gray",c=a.id===n,d=Pe(a)==="viewer",p=a.id===i,b=a.id in o,E=d?" (viewer)":r?o[a.id]?` \u2192 ${o[a.id]}`:"":b?" \u2713":" \xB7",R=p&&!d&&!(r&&o[a.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:u,children:l}),jsxs(Text,{children:[a.displayName,c?" (host)":""]}),R?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:d?"gray":b?"green":"gray",children:E})]},a.id)})]})}var zi=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function jo({onPick:e,onClose:t}){return jsx(he,{title:"Host Actions",items:zi,onSelect:e,onClose:t})}function Gt({roomCode:e,onPick:t,onClose:n}){let o=[{label:"Copy code",value:"code",detail:Ut(e)},{label:"Copy share link",value:"url",detail:Bt(e)},{label:"Copy npx command",value:"npx",detail:Ht(e)}];return jsx(he,{title:"Share",items:o,onSelect:r=>t(r),onClose:n})}function Zi(e){let t=e.rounds.filter(o=>W(o)!==null),n=Object.fromEntries(e.participants.map(o=>[o.id,o]));return So({rounds:t,participants:n})}async function _o(e,t,n){let o=Zi(e);try{await t(o),n("Results copied to clipboard");}catch{n("Clipboard write failed");}}function Fo(e,t,n){let o=ao(e.id,n);return o===null?`Round ${t}`:`Round ${o.depth}/${o.total} [re-vote]`}function Vo(e,t,n){let o=Fo(e,t,n),r=e.title?` \u2014 ${e.title}`:"",i=e.ticketId?` [${e.ticketId}]`:"",a=W(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${o}${r}${i}${a}`}function Yo(e){let t=Object.values(e).filter(c=>!fe(c)).map(c=>parseFloat(c)).filter(c=>!isNaN(c)).toSorted((c,d)=>c-d);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let o=t.reduce((c,d)=>c+d,0)/t.length,r=Math.floor(t.length/2),i=t.length%2===0?(t[r-1]+t[r])/2:t[r],a=Object.values(e).filter(c=>!fe(c)),s=new Map;for(let c of a)s.set(c,(s.get(c)??0)+1);let l=Math.max(...s.values()),u=a.length>0?Math.round(l/a.length*100):0;return {average:o.toFixed(1),median:i.toFixed(1),agreement:`${u}%`}}function Nn(e,t){let n=Math.floor((t-e)/1e3),o=Math.floor(n/60),r=n%60;return `${o}:${r.toString().padStart(2,"0")}`}function Jo(e,t,n=[]){let o=Fo(e,t,n);if(W(e)==="skipped"){let d=e.title?` ${e.title}`:"",p=e.ticketId?` [${e.ticketId}]`:"";return `${o}:${d}${p} \u2014 Skipped`}let r=new Map;for(let d of Object.values(e.votes))fe(d)||r.set(d,(r.get(d)??0)+1);let i=[...r.entries()].toSorted((d,p)=>p[1]-d[1]||d[0].localeCompare(p[0])).map(([d,p])=>`${d}\xD7${p}`).join(", "),a=Object.values(e.votes).filter(fe).length,s=a>0?` (${a} abstained)`:"",l=e.title?` ${e.title}`:"",u=e.ticketId?` [${e.ticketId}]`:"",c=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${Nn(e.timerStartedAt,e.revealedAt)}`:"";return `${o}:${l}${u} \u2014 ${i||"(no votes)"}${s}${c}`}function Go({projection:e,onlineIds:t,isHost:n,participantId:o,rounds:r,currentRound:i,settingsOpen:a,onStartRound:s,onNewRound:l,onRevote:u,onOpenSettings:c,onHandoffHost:d,onEndSession:p,onShare:b,shareOpen:E,onSetShareOpen:R,roomCode:A,confirmingQuit:H,myRole:m,onToggleRole:f,roundTitlePromptActive:y,roundTitleInput:v,onRoundTitleChange:N,onRoundTitleSubmit:w,onRoundTitleCancel:D,roundTicketIdPromptActive:S,roundTicketIdInput:_,onRoundTicketIdChange:pe,onRoundTicketIdSubmit:oe,onRoundTicketIdCancel:re,descriptorPromptActive:J,descriptorInput:I,onDescriptorChange:T,onDescriptorSubmit:O,onDescriptorCancel:F,onEditDescriptor:M,canExport:L,onExportResults:z,onAgendaAdd:Qe,agendaAddPromptActive:Te,agendaAddTitleInput:Ze,onAgendaAddTitleChange:tn,onAgendaAddTitleSubmit:je,onAgendaAddTitleCancel:St,agendaAddTicketIdPromptActive:ye,agendaAddTicketIdInput:nn,onAgendaAddTicketIdChange:_e,onAgendaAddTicketIdSubmit:Fe,onAgendaAddTicketIdCancel:Re}){let[Q,Z]=Wt.useState("idle"),[ge,ve]=Wt.useState(null),[et,ie]=Wt.useState(false),[me,Ee]=Wt.useState(false);useEffect(()=>{n||(Z("idle"),ve(null),ie(false),Ee(false));},[n]),useInput(x=>{if(x==="c"||x==="C"){R(true);return}if(x==="w"||x==="W"){f();return}if((x==="x"||x==="X")&&L){z();return}if(n){if(x==="a"||x==="A"){Qe();return}(x==="e"||x==="E")&&c(),(x==="s"||x==="S")&&s(),(x==="h"||x==="H")&&Z("picking"),(x==="m"||x==="M")&&ie(true),i!==null&&W(i)!==null&&((x==="n"||x==="N")&&l(),(x==="v"||x==="V")&&W(i)!=="skipped"&&u(),(x==="t"||x==="T")&&M());}},{isActive:!a&&!H&&Q==="idle"&&!y&&!S&&!et&&!me&&!E&&!J&&!Te&&!ye}),useInput((x,ee)=>{x==="y"||x==="Y"?(p(),Ee(false)):(x==="n"||x==="N"||ee.escape)&&Ee(false);},{isActive:me});let Ce=e.participants.filter(x=>x.id!==o&&t.has(x.id));useInput(x=>{if(Q==="picking"){let ee=parseInt(x,10);!isNaN(ee)&&ee>=1&&ee<=Ce.length?(ve(Ce[ee-1].id),Z("confirming")):(x==="Escape"||x==="q"||x==="Q")&&Z("idle");}},{isActive:Q==="picking"}),useInput(x=>{Q==="confirming"&&ge&&(x==="y"||x==="Y"?(d(ge),Z("idle"),ve(null)):(x==="n"||x==="N"||x==="Escape")&&(Z("idle"),ve(null)));},{isActive:Q==="confirming"});let ke=r.length>0,xt=r.filter(x=>W(x)!==null),tt=i!==null?xt.slice(0,-1):xt;return et?jsx(jo,{onPick:x=>{ie(false),x==="end-session"&&Ee(true);},onClose:()=>ie(false)}):E?jsx(Gt,{roomCode:A,onPick:x=>{R(false),b(x);},onClose:()=>R(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:ke?"Session":"Waiting for participants..."}),!ke&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(Jt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:o}),e.agenda.length>0&&jsx(rs,{items:e.agenda,nextPending:Ge(e)}),i!==null&&W(i)!==null&&jsx(ts,{projection:e,round:i,rounds:r}),tt.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),tt.map(x=>{let ee=r.indexOf(x)+1;return jsx(Text,{dimColor:true,children:Jo(x,ee,r)},x.id)})]}),Q==="picking"&&Ce.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),Ce.map((x,ee)=>jsxs(Text,{children:["[",ee+1,"] ",x.displayName]},x.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="picking"&&Ce.length===0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"No other online participants"}),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="confirming"&&ge&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(x=>x.id===ge)?.displayName,"? [y/n]"]})}),y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(Y,{value:v,onChange:N,onSubmit:w,onCancel:D,placeholder:"Enter to skip",isActive:y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),S&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(Y,{value:_,onChange:pe,onSubmit:oe,onCancel:re,placeholder:"e.g. PROJ-1234",isActive:S})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),J&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(Y,{value:I,onChange:T,onSubmit:O,onCancel:F,placeholder:"Enter to save",isActive:J})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),me&&jsxs(Box,{children:[jsx(Text,{color:"red",children:"End session for everyone? This cannot be undone. "}),jsx(Text,{dimColor:true,children:"y/n [Esc] Cancel"})]}),Te&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda title (optional, Enter to skip):"}),jsx(Y,{value:Ze,onChange:tn,onSubmit:je,onCancel:St,placeholder:"Enter to skip",isActive:Te})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),ye&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda ticket ID (optional, Enter to skip):"}),jsx(Y,{value:nn,onChange:_e,onSubmit:Fe,onCancel:Re,placeholder:"e.g. PROJ-1234",isActive:ye})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),Q==="idle"&&!y&&!S&&!J&&!me&&!Te&&!ye&&jsxs(Box,{gap:2,children:[n?jsx(Fragment,{children:i!==null&&W(i)!==null?jsxs(Fragment,{children:[W(i)!=="skipped"&&jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[t] Edit title"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]}):jsxs(Fragment,{children:[jsx(Text,{color:"yellow",children:"[s] Start round"}),jsx(Text,{color:"yellow",children:"[a] Agenda"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]})}):jsxs(Fragment,{children:[jsx(Text,{dimColor:true,children:"Waiting for host to start a round..."}),jsx(Text,{children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function ts({projection:e,round:t,rounds:n}){let o=n.indexOf(t)+1,r=Vo(t,o,n);if(W(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let i=Yo(t.votes),a=new Map(e.participants.map(p=>[p.id,p.displayName])),s=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?Nn(t.timerStartedAt,t.revealedAt):null,l=Object.entries(t.votes),u=l.filter(([,p])=>!fe(p)),c=l.filter(([,p])=>fe(p)).map(([p])=>p),d=u[0]?.[1];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),to(t)&&d!==void 0&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",d]}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:2,children:[jsx(Text,{bold:true,underline:true,children:"Name".padEnd(20)}),jsx(Text,{bold:true,underline:true,children:"Estimate".padEnd(10)})]}),u.map(([p,b])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(a.get(p)??p).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:b.padEnd(10)})]},p)),c.map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:(a.get(p)??p).padEnd(20)}),jsx(Text,{dimColor:true,children:"(abstained)".padEnd(10)})]},p)),e.participants.filter(p=>!(p.id in t.votes)).map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:p.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},p.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:i.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:i.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:i.agreement})]}),s!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",s]})]})]})}var ns={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"},os={consumed:"green",skipped:"yellow",cancelled:"red"};function rs({items:e,nextPending:t}){let n=e.filter(o=>o.state!=="cancelled");return jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 Agenda \u2500\u2500"}),n.map(o=>{let r=ns[o.state]??"?",i=os[o.state],a=t!==null&&o.id===t.id,s=[o.ticketId?`[${o.ticketId}]`:"",o.title??""].filter(Boolean).join(" ").trim()||o.id;return jsxs(Box,{gap:1,children:[i!==void 0?jsx(Text,{color:i,children:r}):jsx(Text,{children:r}),i!==void 0?jsx(Text,{color:i,children:s}):jsx(Text,{children:s}),a&&jsx(Text,{color:"cyan",children:"(next)"})]},o.id)}),n.length===0&&jsx(Text,{dimColor:true,children:"No pending items."})]})}function Ko({scale:e,selected:t,onSelect:n,onClear:o,disabled:r}){let[i,a]=useState(0);return useInput((s,l)=>{if(!r)if(l.leftArrow)a(u=>Math.max(0,u-1));else if(l.rightArrow)a(u=>Math.min(e.cards.length-1,u+1));else if(l.return){let u=e.cards[i];u===t?o():n(u);}else (l.backspace||l.delete)&&o();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((s,l)=>{let u=l===i,c=s===t;return jsx(Text,{inverse:u,bold:c,...c&&{color:"cyan"},children:c?`[${s}]`:` ${s} `},s)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function cs(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function zo({projection:e,round:t,onlineIds:n,isHost:o,myId:r,myRole:i,elapsedMs:a,roomCode:s,shareOpen:l,settingsOpen:u,onVote:c,onClearVote:d,onReveal:p,onSkip:b,onToggleRole:E,onShare:R,onSetShareOpen:A,onOpenSettings:H,confirmingQuit:m}){let f=t.votes[r],y=f!==void 0&&fe(f);if(useInput(S=>{if(S==="e"||S==="E"){H();return}if(S==="c"||S==="C"){A(true);return}if(i==="voter"&&(S==="a"||S==="A")){y?d():c(vt);return}o&&(S==="r"||S==="R")&&p(),o&&(S==="s"||S==="S")&&b(),(S==="w"||S==="W")&&E();},{isActive:!m&&!u&&!l}),l)return jsx(Gt,{roomCode:s,onPick:S=>{A(false),R(S);},onClose:()=>A(false)});let v=f,N=e.rounds.indexOf(t)+1,w=t.title?` \u2014 ${t.title}`:"",D=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",N,w,D]}),a!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",cs(a)]})]}),jsxs(Box,{gap:4,children:[jsx(Jt,{participants:e.participants,onlineIds:n,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),i==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsxs(Box,{flexDirection:"column",gap:1,children:[y&&jsx(Text,{dimColor:true,children:"(abstaining this round \u2014 press [a] to vote)"}),jsx(Ko,{scale:t.scale,selected:y?void 0:v,onSelect:c,onClear:d,disabled:m||y})]})]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),o&&jsx(Text,{color:"yellow",children:"[s] Skip"}),i==="voter"&&jsxs(Text,{color:"yellow",children:["[a] ",y?"Vote":"Abstain"]}),jsxs(Text,{color:"yellow",children:["[w] ",i==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var ms=3e3;function zt(e=ms){let[t,n]=useState(null),o=useRef(null),r=useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null);},[]),i=useCallback(s=>{r(),n(s),o.current=setTimeout(()=>{n(null),o.current=null;},e);},[r,e]),a=useCallback(()=>{r(),n(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:i,dismiss:a}}function hs(e){let t=te(e);return !t||W(t)!==null?"lobby":"voting"}function Qt({session:e,participantId:t,displayName:n,accessMode:o,presetOverrides:r,customScales:i}){let{exit:a}=useApp(),[s,l]=useState(e.projection()),[u,c]=useState("connecting"),[d,p]=useState(e.onlineIds()),[b,E]=useState(),[R,A]=useState(false),[H,m]=useState(o==="password"?"password":"open"),[f,y]=useState(n),[v,N]=useState(false),[w,D]=useState(false),[S,_]=useState(""),[pe,oe]=useState(false),[re,J]=useState(""),[I,T]=useState(),[O,F]=useState(false),[M,L]=useState(""),[z,Qe]=useState(null),[Te,Ze]=useState(false),[tn,je]=useState(""),[St,ye]=useState(false),[nn,_e]=useState(""),[Fe,Re]=useState(),[Q,Z]=useState(),ge=zt(3e3),[ve,et]=useState(false),ie=zt(3e3),me=zt(3e3);useEffect(()=>{let C=e.onChange(()=>{l(e.projection()),p(e.onlineIds());}),U=e.onStatusChange(c),Ve=e.onHostChange(wt=>{let Ur=e.projection().participants.find(Hr=>Hr.id===wt),Br=wt===t?"You are now the host":`${Ur?.displayName||"Unknown"} is now the host`;ge.show(Br);}),rn=setInterval(()=>{p(e.onlineIds());let wt=e.projection(),yt=te(wt);yt?.timerStartedAt!==void 0&&yt.revealedAt===void 0?E(Date.now()-yt.timerStartedAt):E(void 0);},1e3);return ()=>{C(),U(),Ve(),clearInterval(rn);}},[e,t,ge.show]),useInput(C=>{(C==="q"||C==="Q")&&N(true);},{isActive:!R&&!v&&!w&&!pe&&!O&&!ve&&!Te&&!St}),useInput((C,U)=>{C==="y"||C==="Y"?(e.disconnect(),a()):(C==="n"||C==="N"||U.escape)&&N(false);},{isActive:v});let Ee=hs(s),Ce=te(s),ke=s.settings.hostParticipantId===t,xt=s.participants.find(C=>C.id===t),tt=Pe(xt??{}),x=useCallback(()=>{let C=Lt(Ge(s));_(C.title),Z(C.agendaItemId),D(true);},[s]),ee=useCallback(C=>{D(false),_(""),T(yn(C));let U=Lt(Ge(s));J(U.ticketId),oe(true);},[s]),cr=useCallback(()=>{D(false),_(""),T(void 0),Z(void 0);},[]),lr=useCallback(C=>{oe(false),J("");let[U,Ve,rn]=Ro(I,C,Q);e.newRound(U,Ve,rn),T(void 0),Z(void 0);},[e,I,Q]),ur=useCallback(()=>{oe(false),J(""),T(void 0),Z(void 0);},[]),pr=useCallback(()=>{let C=e.current();!C||C.revealedAt===void 0||(Qe(C.id),L(C.title??""),F(true));},[e]),mr=useCallback(C=>{let U=z;if(F(false),Qe(null),!U)return;let Ve=C.trim();Ve!==""&&e.updateRoundDescriptor(U,{title:Ve});},[e,z]),fr=useCallback(()=>{F(false),Qe(null);},[]),gr=useCallback(C=>{e.vote(C);},[e]),hr=useCallback(()=>{e.unvote();},[e]),Sr=useCallback(()=>{e.reveal();},[e]),xr=useCallback(()=>{e.skip();},[e]),wr=useCallback(()=>{let C=Lt(Ge(s));_(C.title),Z(C.agendaItemId),D(true);},[s]),yr=useCallback(()=>{e.revote();},[e]),$n=useCallback(()=>{e.toggleRole();},[e]),vr=useCallback(C=>{e.updateName(C);},[e]),Cr=useCallback(C=>{e.updateScale(C);},[e]),Ir=useCallback(C=>{e.updateDisplayName(C),y(C);},[e]),br=useCallback(async(C,U)=>{await e.updateAccess(C,U),m(C);},[e]),Ar=useCallback(C=>{try{e.handoffHost(C);}catch(U){console.error(`Handoff failed: ${U instanceof Error?U.message:String(U)}`);}},[e]),Un=useCallback(()=>{A(true);},[]),Tr=useCallback(()=>{A(false);},[]),Rr=useCallback(()=>{e.endSessionForEveryone();},[e]),Bn=useCallback(async C=>{let U=C==="code"?Ut(e.roomCode):C==="url"?Bt(e.roomCode):Ht(e.roomCode);try{await Qo.write(U),ie.show("Copied!");}catch{ie.show(`Copy failed \u2014 ${U}`);}},[e.roomCode,ie]),on=s.rounds.filter(C=>W(C)!==null),Er=on.length>0?on.at(-1):null,kr=on.length>0,Nr=useCallback(()=>_o(s,C=>Qo.write(C),me.show),[s,me.show]),Pr=useCallback(()=>{je(""),Ze(true);},[]),Dr=useCallback(C=>{Ze(false),je("");let U=C.trim()===""?void 0:C.trim();Re(U),_e(""),ye(true);},[]),Or=useCallback(()=>{Ze(false),je(""),Re(void 0);},[]),Mr=useCallback(C=>{ye(false),_e("");let U=C.trim()===""?void 0:C.trim();if(!Fe&&!U){Re(void 0);return}Et(e.doc,{...Fe!==void 0&&{title:Fe},...U!==void 0&&{ticketId:U},createdAt:Date.now()}),Re(void 0);},[e.doc,Fe]),$r=useCallback(()=>{ye(false),_e(""),Re(void 0);},[]);return jsxs(Box,{flexDirection:"column",children:[jsx(No,{roomCode:e.roomCode,sessionName:s.settings.name,status:u,isHost:ke}),ge.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:ge.notice})}),ie.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ie.notice.startsWith("Copy failed")?"red":"green",children:ie.notice})}),me.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:me.notice.startsWith("Clipboard write failed")?"red":"green",children:me.notice})}),R?jsx(Ho,{sessionName:s.settings.name,displayName:f,currentScale:s.settings.defaultScale,accessMode:H,presetOverrides:r,customScales:i,isHost:ke,onChangeName:vr,onChangeScale:Cr,onChangeDisplayName:Ir,onChangeAccess:br,onClose:Tr}):Ee==="lobby"?jsx(Go,{projection:s,onlineIds:d,isHost:ke,participantId:t,rounds:s.rounds,currentRound:Er,settingsOpen:R,onStartRound:x,onNewRound:wr,roundTitlePromptActive:w,roundTitleInput:S,onRoundTitleChange:_,onRoundTitleSubmit:ee,onRoundTitleCancel:cr,roundTicketIdPromptActive:pe,roundTicketIdInput:re,onRoundTicketIdChange:J,onRoundTicketIdSubmit:lr,onRoundTicketIdCancel:ur,onRevote:yr,onOpenSettings:Un,onHandoffHost:Ar,onEndSession:Rr,onShare:Bn,shareOpen:ve,onSetShareOpen:et,roomCode:e.roomCode,confirmingQuit:v,myRole:tt,onToggleRole:$n,descriptorPromptActive:O,descriptorInput:M,onDescriptorChange:L,onDescriptorSubmit:mr,onDescriptorCancel:fr,onEditDescriptor:pr,canExport:kr,onExportResults:Nr,onAgendaAdd:Pr,agendaAddPromptActive:Te,agendaAddTitleInput:tn,onAgendaAddTitleChange:je,onAgendaAddTitleSubmit:Dr,onAgendaAddTitleCancel:Or,agendaAddTicketIdPromptActive:St,agendaAddTicketIdInput:nn,onAgendaAddTicketIdChange:_e,onAgendaAddTicketIdSubmit:Mr,onAgendaAddTicketIdCancel:$r}):Ee==="voting"&&Ce?jsx(zo,{projection:s,round:Ce,onlineIds:d,isHost:ke,myId:t,myRole:tt,elapsedMs:b,onVote:gr,onClearVote:hr,onReveal:Sr,onSkip:xr,onToggleRole:$n,onShare:Bn,onSetShareOpen:et,shareOpen:ve,settingsOpen:R,onOpenSettings:Un,roomCode:e.roomCode,confirmingQuit:v}):null,v&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function Zo({presetOverrides:e,customScales:t}){let{exit:n}=useApp(),[o,r]=useState("main-menu"),[i,a]=useState(Ne()),[s,l]=useState(i.displayName??""),[u,c]=useState(i.relayUrl??""),[d,p]=useState(i.defaultSessionName??""),[b,E]=useState(t??[]),[R,A]=useState(e??{});useInput(I=>{(I==="q"||I==="Q")&&n();},{isActive:o==="main-menu"});let H=useMemo(()=>Pt(R,b),[R,b]),m=i.defaultScale,f=m?H.find(I=>I.id===m):void 0,y=[{label:"Display name",value:"display-name",detail:`[${i.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${i.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${f?Me(f.id,b):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${i.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${i.defaultPassword?"on":"off"}]`}];function v(I){I==="display-name"?(l(i.displayName??""),r("editing-display-name")):I==="relay-url"?(c(i.relayUrl??""),r("editing-relay-url")):I==="default-scale"?r("picking-scale"):I==="default-session-name"?(p(i.defaultSessionName??""),r("editing-session-name")):I==="default-password"&&r("picking-default-password");}function N(I){let T=I.trim();if(T.length>0){let O={...i,displayName:T};a(O),G({displayName:T});}r("main-menu");}function w(I){let T=I.trim();if(T.length>0){let O={...i,relayUrl:T};a(O),G({relayUrl:T});}r("main-menu");}function D(I){let T=I.trim(),O=T.length>0?{...i,defaultSessionName:T}:{...i};T.length===0?(delete O.defaultSessionName,a(O),ot({defaultSessionName:""})):(a(O),G({defaultSessionName:T})),r("main-menu");}function S(I){let T=I.length>0?{...i,defaultScale:I}:{...i};I.length===0?(delete T.defaultScale,a(T),ot({defaultScale:""})):(a(T),G({defaultScale:I})),r("main-menu");}function _(I,T){let O={...R};T.length===0?delete O[I]:O[I]=T,A(O),G({presetOverrides:Object.keys(O).length>0?O:void 0});}function pe(I){let T=I==="on",O={...i,defaultPassword:T};a(O),G({defaultPassword:T}),r("main-menu");}function oe(I,T){let O=`custom-${randomUUID()}`,F=[...b,{id:O,label:I,cards:T}];E(F),a({...i,customScales:F}),G({customScales:F});}function re(I,T,O){let F=b.map(M=>M.id===I?{id:I,label:T,cards:O}:M);E(F),a({...i,customScales:F}),G({customScales:F});}function J(I){let T=b.filter(F=>F.id!==I);E(T);let O={...i,customScales:T};i.defaultScale===I?(O.defaultScale="fibonacci",G({customScales:T,defaultScale:"fibonacci"})):G({customScales:T}),a(O);}if(o==="main-menu")return jsx(he,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:y,onSelect:v,onClose:()=>n()});if(o==="editing-display-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(Y,{value:s,onChange:l,onSubmit:N,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-relay-url")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Relay URL: "}),jsx(Y,{value:u,onChange:c,onSubmit:w,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-session-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Default session name: "}),jsx(Y,{value:d,onChange:p,onSubmit:D,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="picking-scale"){let I=[{id:"",cards:[]},...H];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Ft,{scales:I,selectedScaleId:m??"",presetOverrides:R,customScales:b,onSelect:S,onOverrideChange:_,onCustomScaleCreate:oe,onCustomScaleEdit:re,onCustomScaleDelete:J,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(o==="picking-default-password"){let I=[{label:"On",value:"on",detail:i.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:i.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(he,{title:"Default password:",items:I,onSelect:pe,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}var Is={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"};function bs(e){let t=Is[e.state]??"?",n=[];e.ticketId&&n.push(`[${e.ticketId}]`),e.title&&n.push(e.title);let o=n.join(" ")||e.id;return `${t} ${o}`}async function gt(e){let t=new De.Doc,n=new Awareness(t);Ye(t,{participantId:e.participantId,displayName:e.displayName}),n.setLocalStateField("participantId",e.participantId);let o=We({doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}});return await new Promise(r=>{let i=setTimeout(r,2e3),a=o.onStatusChange(s=>{s==="connected"&&setTimeout(()=>{clearTimeout(i),a(),r();},200);});}),{doc:t,disconnect:()=>o.disconnect()}}async function ht(){let e=Dt();return e||(console.error("No active session. Join a room first with: hnch join <code>"),process.exit(1)),{roomCode:e.roomCode,roomUuid:e.roomUuid,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}}}async function tr(e){!e.title?.trim()&&!e.ticket?.trim()&&(console.error("At least one of --title or --ticket is required"),process.exit(1));let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{let i=Et(o,{...e.title?.trim()?{title:e.title.trim()}:{},...e.ticket?.trim()?{ticketId:e.ticket.trim()}:{},...e.description?.trim()?{description:e.description.trim()}:{},createdAt:Date.now()});await new Promise(a=>{setTimeout(a,300);}),console.log(`Added agenda item: ${i}`);}finally{r();}}async function nr(){let e=await se(),t=await ht();try{await de(e.relayUrl,t.roomCode);}catch{console.error(`Room ${t.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:n,disconnect:o}=await gt({relayUrl:e.relayUrl,participantId:e.participantId,displayName:e.displayName,roomCode:t.roomCode,roomUuid:t.roomUuid,...t.passwordHash!==void 0&&{passwordHash:t.passwordHash}});try{let i=q(n).agenda;if(i.length===0){console.log("No agenda items.");return}i.forEach((a,s)=>{console.log(`${String(s+1).padStart(2)}. ${bs(a)}`);});}finally{o();}}async function or(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{kt(o,e.id,"skipped",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Skipped agenda item: ${e.id}`);}catch(i){console.error(`Skip failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function rr(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{kt(o,e.id,"cancelled",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Cancelled agenda item: ${e.id}`);}catch(i){console.error(`Cancel failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function ir(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{ro(o,e.id,e.before,e.after),await new Promise(i=>{setTimeout(i,300);}),console.log(`Reordered agenda item: ${e.id}`);}catch(i){console.error(`Move failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function Mn(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",n=>{t.close(),e(n);});})}async function Es(e){let t=await se(),n=e.scale??t.defaultScale??"fibonacci",o=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,i;r&&(i=await Mn());let a=Nt(n,t.presetOverrides,t.customScales);if(!a){let d=Object.keys(ae).join(", ");console.error(`Unknown or fully-disabled scale: "${n}". Builtin IDs: ${d}`),process.exit(1);}let s=await Io({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:o,password:i,defaultScale:a}),l;i&&(l=await Oe(i,s.roomUuid)),Ot({roomCode:s.roomCode,roomUuid:s.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Room created: ${s.roomCode}`),console.error(`Share: hnch join ${s.roomCode}`),console.error("");let{waitUntilExit:u,unmount:c}=render(Wt.createElement(Qt,{session:s,participantId:t.participantId,displayName:t.displayName,accessMode:i?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));$t({doc:s.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),c();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}s.disconnect(),process.exit(0);}}),await u(),s.disconnect(),V(),process.exit(0);}async function ks(e){let t=await se(),n=Ao(e.code);n===null&&(console.error("invalid room code"),process.exit(1));let o;e.password&&(o=await Mn());let r=await de(t.relayUrl,n),i;r.accessMode==="password"&&!e.password?i=await Mn():e.password&&(i=o);let a,s=false,l=await bo({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:n,password:i,onRejection(d){if(d==="unknown-room"){Mt({clearLastSession:V,logger:console,exit:process.exit});return}d==="room-full"&&(s=true,a?.());}}),u;i&&(u=await Oe(i,l.roomUuid)),Ot({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Joined room: ${l.roomCode}`),console.error("");let c=render(Wt.createElement(Qt,{session:l,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));a=c.unmount,$t({doc:l.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),a?.();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}l.disconnect(),process.exit(0);}}),await c.waitUntilExit(),s&&(console.error("This room is full (max 20 participants)."),l.disconnect(),V(),process.exit(1)),l.disconnect(),V(),process.exit(0);}async function Ns(){let e=await se(),t=Dt();t||(console.error("No recent session to resume."),process.exit(0));let n;try{n=await de(e.relayUrl,t.roomCode);}catch(c){if((c instanceof Error?c.message:String(c)).includes("Room not found"))return await Mt({clearLastSession:V,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}n.accessMode==="password"&&!t.passwordHash&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let o=new De.Doc,r=new Awareness(o);Ye(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let i=false,a=false,s,l=We({doc:o,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(c){if(c==="unknown-room"){Mt({clearLastSession:V,logger:console,exit:process.exit});return}c==="wrong-password"&&(i=true,s?.()),c==="room-full"&&(a=true,s?.());}});Ot({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let u=render(Wt.createElement(Qt,{session:l,participantId:e.participantId,displayName:e.displayName,accessMode:n.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));s=u.unmount,$t({doc:l.doc,localParticipantId:e.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),s?.();try{await V();}catch(d){console.error(`Failed to clear cached session: ${d instanceof Error?d.message:String(d)}`);}l.disconnect(),process.exit(0);}}),await u.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),V(),process.exit(1)),i&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),l.disconnect(),V(),process.exit(0);}async function Ps(e){if(!(e.name!==void 0||e.relayUrl!==void 0||e.scale!==void 0||e.sessionName!==void 0||e.password!==void 0)){let o=await se(),{waitUntilExit:r}=render(Wt.createElement(Zo,{presetOverrides:o.presetOverrides,customScales:o.customScales}));await r(),process.exit(0);}let n={};if(e.name!==void 0&&(n.displayName=e.name),e.relayUrl!==void 0&&(n.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let o=Ne();if(!Nt(e.scale,o.presetOverrides,o.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(ae).join(", ")}`);return}}n.defaultScale=e.scale;}e.sessionName!==void 0&&(n.defaultSessionName=e.sessionName),e.password!==void 0&&(n.defaultPassword=e.password),ot(n),console.log("Config updated.");}var dr=As(hideBin(process.argv)).scriptName("hnch").usage("$0 <command> \u2014 terminal pointing poker").command("create","Create a new room",e=>e.option("name",{type:"string",describe:"Session name"}).option("password",{type:"boolean",describe:"Protect room with a password"}).option("scale",{type:"string",describe:"Estimation scale ID (fibonacci, t-shirt, powers-of-2, linear, risk, or custom-<id>)"}),e=>{Es(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("join <code>","Join an existing room",e=>e.positional("code",{type:"string",demandOption:true,describe:"6-character room code"}).option("password",{type:"boolean",describe:"Room requires a password",default:false}),e=>{ks(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Ns().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1);});}).command("config","View or update CLI config",e=>e.option("name",{type:"string",describe:"Set display name"}).option("relay-url",{type:"string",describe:"Set relay URL"}).option("scale",{type:"string",describe:"Set default estimation scale ID (empty string clears)"}).option("session-name",{type:"string",describe:"Set default session name (empty string clears)"}).option("password",{type:"boolean",describe:"Set default password prompt on (--password) or off (--no-password)"}),e=>{Ps(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("agenda","Manage the pre-session story agenda",e=>e.command("add","Add an agenda item",t=>t.option("title",{type:"string",describe:"Story title"}).option("ticket",{type:"string",describe:"Issue tracker reference (e.g. PROJ-123)"}).option("description",{type:"string",describe:"Story description"}).check(n=>{if(!n.title?.trim()&&!n.ticket?.trim())throw new Error("At least one of --title or --ticket is required");return true}),t=>{tr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("list","List agenda items in order",t=>t,()=>{nr().catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("skip <id>","Mark an agenda item as skipped",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{or(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("cancel <id>","Soft-delete (cancel) an agenda item",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{rr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("mv <id>","Reorder an agenda item (--before <id> | --after <id>)",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID to move"}).option("before",{type:"string",describe:"sortKey of item that should come before the moved item"}).option("after",{type:"string",describe:"sortKey of item that should come after the moved item"}).check(n=>{if(n.before!==void 0&&n.after!==void 0)throw new Error("--before and --after are mutually exclusive");if(n.before===void 0&&n.after===void 0)throw new Error("Specify either --before <id> or --after <id>");return true}),t=>{ir(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).demandCommand(1,"Specify an agenda subcommand: add, list, skip, cancel, mv").strict().help(),()=>{}).demandCommand(1,"Specify a command: create, join, resume, config, or agenda").strict().help(),On=hideBin(process.argv);(On.length===0||On.length===1&&On[0]==="--")&&(dr.showHelp(),process.exit(0));dr.parse();
18
+ `}function Ot(e,t,n){if(e.startsWith("custom-")){let r=(n??[]).find(i=>i.id===e);return r?{id:r.id,cards:r.cards}:void 0}let o=se[e];if(o){let r=(t??{})[e]??[];if(r.length===0)return o;let i=o.cards.filter((s,a)=>!r.includes(a));return i.length===0?void 0:{id:e,cards:i}}}function Mt(e,t){let n=Object.keys(se).map(r=>Ot(r,e,t)).filter(r=>r!==void 0),o=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...n,...o]}function Ue(e,t){if(e.startsWith("custom-")){let n=(t??[]).find(o=>o.id===e);if(n&&n.label.trim().length>0)return n.label}return Gn(e)}var Ri="https://hnch.dev";function lt(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function wn(){return join(lt(),"config.json")}function vo(){let e=lt();existsSync(e)||mkdirSync(e,{recursive:true});}function He(){let e=wn();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function _(e){vo();let n={...He(),...e};writeFileSync(wn(),JSON.stringify(n,null,2)+`
19
+ `,"utf-8");}async function Ei(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,o=>{t.close(),n(o.trim());});})}function ki(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function ae(){let e=He(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let o=await Ei("Enter your display name: ");e.displayName=o||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=Ri,t=true),(!e.avatarColor||Oe(e.avatarColor)===null)&&(e.avatarColor=Fn(e.participantId),t=true),t&&_(e);let n=process.env.HNCH_RELAY_URL||e.relayUrl;return n=ki(n),{participantId:e.participantId,displayName:e.displayName,relayUrl:n,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales,avatarColor:e.avatarColor}}function ut(e){vo();let n={...He()};for(let[o,r]of Object.entries(e))r===""?delete n[o]:r!==void 0&&(n[o]=r);writeFileSync(wn(),JSON.stringify(n,null,2)+`
20
+ `,"utf-8");}async function bo(e,t){let n=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!n.ok)throw new Error(`POST /rooms failed: ${n.status}`);return await n.json()}async function de(e,t){let n=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(n.status===404){let o=await n.json().catch(()=>null);throw new Error(`Room not found: ${o?.reason??"unknown-room"}`)}if(!n.ok)throw new Error(`GET /rooms/:code failed: ${n.status}`);return await n.json()}async function yn(e,t,n){let o=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:n})});if(!o.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${o.status}`)}function Io(e){let n=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,o={did:e.deviceId};e.passwordHash!==void 0&&(o.pw=e.passwordHash);let r=new WebsocketProvider(n,e.roomUuid,e.doc,{params:o,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:Pi}),i=u=>{e.onStatusChange?.(u.status);},s=u=>{if(u===null)return;let c=_n.get(u.code);c!==void 0&&(e.onRejection?.(c),r.shouldConnect=false,r.disconnect());};r.on("status",i),r.on("connection-close",s);let a=false,l=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(u){if(u.passwordHash===l)return;l=u.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let d={did:r.params.did??""};l!==void 0&&(d.pw=l),r.params=d,r.connect();},disconnect(){a||(a=true,r.off("status",i),r.off("connection-close",s),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Di=5e3;function Ao(e,t,n){let o=null,r=null;function i(){let c=new Set;return t.getStates().forEach(d=>{let p=d.participantId;typeof p=="string"&&c.add(p);}),c}function s(){return e.getMap(at).get("hostParticipantId")}function a(){r!==null&&(clearTimeout(r),r=null),o=null;}function l(){let c=s(),d=o;if(o=null,!d||c!==d)return;let p=i();if(p.has(c))return;let R=[...p].toSorted();if(R.length===0)return;let k=R[0];k===n&&ze(e,{hostParticipantId:k});}function u(){let c=s();if(!c)return;if(i().has(c)){a();return}o!==c&&(a(),o=c,r=setTimeout(()=>{r=null,l();},Di));}return t.on("change",u),e.getMap(at).observe(u),u(),{stop(){a(),t.off("change",u),e.getMap(at).unobserve(u);}}}async function Eo(e){let t,n=await bo(e.relayUrl);e.password&&(t=await Be(e.password,n.uuid),await yn(e.relayUrl,n.uuid,t));let o=new $e.Doc,r=new Awareness(o),i=Date.now();return zn(o,{roomUuid:n.uuid,createdAt:i,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??At,...e.sessionName!==void 0&&{sessionName:e.sessionName},...e.avatarColor!==void 0&&{avatarColor:e.avatarColor}}),r.setLocalStateField("participantId",e.participantId),Qe({doc:o,awareness:r,roomCode:n.code,roomUuid:n.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function ko(e){let t=await de(e.relayUrl,e.roomCode),n;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");n=await Be(e.password,t.uuid);}let o=new $e.Doc,r=new Awareness(o);return qe(o,{participantId:e.participantId,displayName:e.displayName,...e.avatarColor!==void 0&&{avatarColor:e.avatarColor}}),r.setLocalStateField("participantId",e.participantId),Qe({doc:o,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:n,onRejection:e.onRejection})}function Qe(e){let{doc:t,awareness:n,participantId:o,relayUrl:r,roomUuid:i}=e,s=new Set,a=new Set,l=new Set,u=Io({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:o,passwordHash:e.passwordHash,awareness:n,onStatusChange(f){s.forEach(g=>g(f));},onRejection(f){console.error(`Connection rejected: ${f}`),e.onRejection?.(f);}}),c=Ao(t,n,o),d=()=>{a.forEach(f=>f());};t.getMap("meta").observeDeep(d),t.getMap("settings").observeDeep(d),t.getMap("participants").observeDeep(d),t.getArray("rounds").observeDeep(d);function p(){let f=new Set;return n.getStates().forEach(g=>{let y=g.participantId;typeof y=="string"&&f.add(y);}),f}let R=new Set,k=setInterval(()=>{let f=K(t),g=te(f);if(!g||g.revealedAt!==void 0||R.has(g.id))return;let y=p();if(y.size===0)return;let v=f.participants.filter(b=>y.has(b.id)&&Me(b)==="voter");if(v.length===0)return;v.filter(b=>b.id in g.votes).length>=v.length&&(R.add(g.id),mn(t,g.id,Date.now()));},250),T=t.getMap("settings").get("hostParticipantId"),A=()=>{let f=t.getMap("settings").get("hostParticipantId");f!==T&&f!==void 0&&l.forEach(g=>g(f)),T=f;};t.getMap("settings").observe(A);let B=false;return {doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return K(t)},current(){return te(K(t))},isHost(){return K(t).settings.hostParticipantId===o},onlineIds:p,vote(f){let g=te(K(t));g&&Qn(t,g.id,o,f);},unvote(){let f=te(K(t));f&&Zn(t,f.id,o);},reveal(){let f=te(K(t));f&&mn(t,f.id,Date.now());},skip(){let f=te(K(t));f&&eo(t,f.id,Date.now());},newRound(f,g,y){let v=randomUUID(),P=Date.now();return t.transact(()=>{fn(t,{id:v,createdAt:P,createdBy:o,...f!==void 0&&{title:f},...g!==void 0&&{ticketId:g},...y!==void 0&&{agendaItemId:y}}),y!==void 0&&ro(t,y,v,P);}),v},revote(){let f=te(K(t)),g=randomUUID();return fn(t,{id:g,createdAt:Date.now(),createdBy:o,...f?.id!==void 0&&{parentRoundId:f.id},...f?.title!==void 0&&{title:f.title},...f?.description!==void 0&&{description:f.description},...f?.ticketId!==void 0&&{ticketId:f.ticketId},...f?.agendaItemId!==void 0&&{agendaItemId:f.agendaItemId}}),g},updateRoundDescriptor(f,g){Xn(t,f,g);},updateName(f){ze(t,{name:f});},updateScale(f){ze(t,{defaultScale:f});},updateDisplayName(f){let v=K(t).participants.find(P=>P.id===o)?.joinedAt??Date.now();pn(t,o,{displayName:f,joinedAt:v});},async updateAccess(f,g){let y=null;if(f==="password"){if(!g)throw new Error("Password required for password mode");y=await Be(g,i);}await yn(r,i,y),u.updateCredentials({passwordHash:y});},handoffHost(f){if(!this.isHost())throw new Error("Only the current host can hand off");if(!p().has(f))throw new Error("Target participant is not online");if(!K(t).participants.some(P=>P.id===f))throw new Error("Target participant does not exist");ze(t,{hostParticipantId:f});},toggleRole(){let g=K(t).participants.find(b=>b.id===o),v=Me(g??{})==="viewer"?"voter":"viewer",P=g?.joinedAt??Date.now();pn(t,o,{displayName:g?.displayName??"",joinedAt:P,role:v});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");to(t);},onChange(f){return a.add(f),()=>a.delete(f)},onStatusChange(f){return s.add(f),()=>s.delete(f)},onHostChange(f){return l.add(f),()=>l.delete(f)},disconnect(){B||(B=true,clearInterval(k),c.stop(),t.getMap("meta").unobserveDeep(d),t.getMap("settings").unobserveDeep(d),t.getMap("settings").unobserve(A),t.getMap("participants").unobserveDeep(d),t.getArray("rounds").unobserveDeep(d),u.disconnect());}}}function No(e){let t=gn(e);return t===""?null:t}var Li=1440*60*1e3;function vn(){return join(lt(),"last-session.json")}function ji(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.roomCode=="string"&&typeof t.roomUuid=="string"&&typeof t.lastSeenAt=="number"&&(t.passwordHash===void 0||typeof t.passwordHash=="string")}function $t(){let e=vn();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !ji(t)||Date.now()-t.lastSeenAt>Li?(F(),null):t}catch{return F(),null}}function Bt(e){let t=lt();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let n=vn();writeFileSync(n,JSON.stringify(e,null,2)+`
21
+ `,{encoding:"utf-8",mode:384}),chmodSync(n,384);}function F(){let e=vn();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function Ut(e){let t=true;try{await e.clearLastSession();}catch(n){t=false,e.logger.error(`Failed to clear cached session: ${n instanceof Error?n.message:String(n)}`);}return t?e.logger.error("Session expired (room no longer exists). Cached session cleared."):e.logger.error("Session expired. Could not delete ~/.config/hnch/last-session.json \u2014 please remove it manually."),e.exit(1)}function Ht(e){let t=e.doc.getMap("meta"),n=null,o=false;function r(){if(o)return;let i=t.get("sessionEndedAt");if(i==null||i===n)return;n=i;let s=t.get("createdBy"),a=s===e.localParticipantId,l=e.doc.getMap("participants"),u=e.doc.getMap("settings").get("hostParticipantId")??s,c="host";if(u){let p=l.get(u)?.get("displayName");typeof p=="string"&&p.length>0&&(c=p);}setImmediate(()=>{o||e.onEnded({isLocal:a,hostName:c,timestamp:i});});}return t.observe(r),r(),()=>{o=true,t.unobserve(r);}}var _i="@xauyxau/hnch";function Lt(e){return fo(e)}function jt(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function _t(e){return `npx ${_i} join ${e}`}function bn(e){let t=e.trim();return t===""?void 0:t}function Ft(e){return e?{title:e.title??"",ticketId:e.ticketId??"",agendaItemId:e.id}:{title:"",ticketId:"",agendaItemId:void 0}}function Do(e,t,n){return [e,bn(t),n]}var Fi={connecting:"yellow",connected:"green",disconnected:"red"};function $o({roomCode:e,sessionName:t,status:n,isHost:o}){let r=t?`${e} \xB7 ${t}`:e;return jsxs(Box,{borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[jsxs(Text,{bold:true,children:["hnch \xB7 ",r]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:Fi[n],children:n})]})]})}function ge({items:e,onSelect:t,onClose:n,title:o}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(a=>!a.disabled),[i,s]=useState(Math.max(r,0));return useInput((a,l)=>{if(l.upArrow)s(u=>{let c=(u-1+e.length)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c-1+e.length)%e.length,d++;return c});else if(l.downArrow)s(u=>{let c=(u+1)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c+1)%e.length,d++;return c});else if(l.return){let u=e[i];u&&!u.disabled&&t(u.value);}else l.escape&&n?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Box,{flexDirection:"column",children:e.map((a,l)=>{let u=l===i,c=a.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...u&&{color:"cyan"},dimColor:c,children:u?">":" "}),jsx(Text,{bold:u,dimColor:c,children:a.label}),a.detail&&jsx(Text,{dimColor:true,children:a.detail})]},a.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function L({value:e,onChange:t,onSubmit:n,onCancel:o,placeholder:r,isActive:i=true,mask:s=false}){useInput((c,d)=>{d.escape?o?.():d.return?n(e):d.backspace||d.delete?t(e.slice(0,-1)):c&&!d.ctrl&&!d.meta&&t(e+c);},{isActive:i});let a=s&&e.length>0?"*".repeat(e.length):e,l=a.length>0?a:r??"",u=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:u,children:l}),jsx(Text,{inverse:true,children:" "})]})}function Lo({mode:e,password:t,onModeChange:n,onPasswordChange:o,onClose:r}){let[i,s]=useState(e==="open"?0:1),[a,l]=useState(false);return useEffect(()=>{s(e==="open"?0:1);},[e]),useInput((u,c)=>{if(c.leftArrow)s(d=>Math.max(0,d-1));else if(c.rightArrow)s(d=>Math.min(1,d+1));else if(c.return){let d=i===0?"open":"password";d!==e&&n(d),d==="password"&&l(true);}else c.escape&&r?.();},{isActive:!a}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((u,c)=>{let d=c===i,p=u===e,R=u==="open"?"Open":"Password";return jsx(Text,{inverse:d,bold:p,...p&&{color:"cyan"},children:p?`[${R}]`:` ${R} `},u)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(L,{value:t,onChange:o,onSubmit:()=>l(false),onCancel:()=>l(false),placeholder:"(required to join)",isActive:a,mask:true}),!a&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),a&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function Fo({scaleId:e,cards:t,disabledIndices:n,onOverrideChange:o,onClose:r}){let i=useMemo(()=>new Set(n),[n]),[s,a]=useState(0),l=u=>{let c=new Set(i);if(c.has(u))c.delete(u);else {if(c.size>=t.length-1)return;c.add(u);}let d=Array.from(c).toSorted((p,R)=>p-R);o(e,d);};return useInput((u,c)=>{c.leftArrow?a(d=>Math.max(0,d-1)):c.rightArrow?a(d=>Math.min(t.length-1,d+1)):u===" "?l(s):(c.return||c.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((u,c)=>{let d=c===s,p=i.has(c);return jsx(Text,{inverse:d,bold:!p,...!p&&{color:"cyan"},strikethrough:p,dimColor:p,children:u},u)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function Pn({initialName:e="",initialCards:t=[],onSave:n,onCancel:o}){let r=e.length>0,[i,s]=useState(e),[a,l]=useState(t.length>0?t:[""]),[u,c]=useState(0),[d,p]=useState("editing-name"),[R,k]=useState(""),T=()=>{let f=i.trim();if(f.length===0||f.length>40){k("Name must be 1-40 characters");return}s(f),k(""),p("editing-cards");},A=()=>{let f=i.trim();if(f.length===0||f.length>40){k("Name must be 1-40 characters");return}let g=a.map(v=>v.trim()).filter(v=>v.length>0),y=Array.from(new Set(g));if(y.length<2){k("Need at least 2 unique non-empty cards");return}k(""),n(f,y);};return useInput((f,g)=>{if(d==="editing-cards"){if(g.leftArrow)c(y=>Math.max(0,y-1));else if(g.rightArrow)c(y=>{let v=y+1;return v>=a.length&&a.length<25?(l(P=>[...P,""]),v):Math.min(v,a.length-1)});else if(g.return)A();else if(g.escape)o();else if(g.tab)p("editing-name");else if(g.backspace){let y=a[u]||"";if(y.length===0){if(a.length>2){let v=a.filter((P,b)=>b!==u);l(v),c(Math.max(0,u-1));}}else {let v=[...a];v[u]=y.slice(0,-1),l(v);}}else if(f&&!g.ctrl&&!g.meta){let y=a[u]||"";if(y.length<10){let v=[...a];v[u]=y+f,l(v);}}}},{isActive:d==="editing-cards"}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r?"\u2500\u2500 Edit Custom Scale \u2500\u2500":"\u2500\u2500 Create Custom Scale \u2500\u2500"}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Name:"}),jsx(L,{value:i,onChange:s,onSubmit:T,onCancel:o,placeholder:"Scale name",isActive:d==="editing-name"})]}),d==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:a.map((f,g)=>{let y=g===u;return jsx(Text,{inverse:y,...!y&&{color:"cyan"},children:f.length>0?f:"\xB7"},g)})})]}),R&&jsx(Text,{color:"red",children:R}),jsx(Text,{dimColor:true,children:d==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function Jt({scales:e,selectedScaleId:t,presetOverrides:n,customScales:o=[],onSelect:r,onOverrideChange:i,onCustomScaleCreate:s,onCustomScaleEdit:a,onCustomScaleDelete:l,onClose:u,showNoneOption:c=false}){let[d,p]=useState(0),[R,k]=useState(null),[T,A]=useState("browsing"),[B,f]=useState(null),[g,y]=useState(null),v=s?[...e,{id:"__create-custom__",cards:[]}]:e,P=v.length;if(useInput((b,O)=>{if(T==="browsing"){if(O.escape){u();return}if(P===0)return;if(O.upArrow)p(w=>(w-1+P)%P);else if(O.downArrow)p(w=>(w+1)%P);else if(O.return){let w=v[d];if(!w)return;if(w.id==="__create-custom__"){A("creating");return}w.id in se?k(R===w.id?null:w.id):r(w.id);}else if(b===" "){let w=v[d];w&&w.id!=="__create-custom__"&&r(w.id);}else if(b==="e"||b==="E"){let w=v[d];a&&w?.id.startsWith("custom-")&&(f(w.id),A("editing"));}else if(b==="d"||b==="D"){let w=v[d];l&&w?.id.startsWith("custom-")&&(y(w.id),A("confirming-delete"));}}else T==="confirming-delete"&&(b==="y"||b==="Y"?(g&&l&&l(g),y(null),A("browsing")):(b==="n"||b==="N"||O.escape)&&(y(null),A("browsing")));},{isActive:T==="browsing"&&R===null||T==="confirming-delete"}),T==="creating")return jsx(Pn,{onSave:(b,O)=>{s&&s(b,O),A("browsing");},onCancel:()=>A("browsing")});if(T==="editing"&&B){let b=o?.find(w=>w.id===B);if(e.find(w=>w.id===B)&&b)return jsx(Pn,{initialName:b.label,initialCards:b.cards,onSave:(w,j)=>{a&&a(B,w,j),f(null),A("browsing");},onCancel:()=>{f(null),A("browsing");}})}if(T==="confirming-delete"&&g){let b=v.find(w=>w.id===g),O=b?Ue(b.id,o):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",O,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return v.length===0?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"(no scales available)"}),jsx(Text,{dimColor:true,children:"esc back"})]}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{flexDirection:"column",children:v.map((b,O)=>{let w=O===d,j=b.id===t,ue=R===b.id,oe=b.id in se,re=b.id==="__create-custom__",V=b.cards.join(", "),z=c&&b.id==="",X=z?"(none)":re?"[+ Create custom scale]":Ue(b.id,o);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...w&&{color:"cyan"},children:w?">":" "}),jsx(Text,{bold:w,children:X}),!z&&!re&&jsx(Text,{dimColor:true,children:V}),j&&jsx(Text,{color:"cyan",children:"[current]"})]}),ue&&!z&&!re&&jsx(Box,{paddingLeft:2,children:oe?jsx(Fo,{scaleId:b.id,cards:se[b.id]?.cards??[],disabledIndices:n?.[b.id]??[],onOverrideChange:i,onClose:()=>k(null)}):null})]},b.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let b=d<v.length?v[d]:null;return b?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${a?" [e] edit":""}${l?" [d] delete":""} esc back`:b&&b.id in se?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function ns(e,t){return t?[...e]:e.filter(n=>n.value==="display-name")}function Vo({sessionName:e,displayName:t,currentScale:n,accessMode:o,presetOverrides:r,customScales:i,isHost:s=true,onChangeName:a,onChangeScale:l,onChangeDisplayName:u,onChangeAccess:c,onClose:d}){let[p,R]=useState(r??{}),k=useMemo(()=>Mt(p,i),[p,i]),[T,A]=useState("main-menu"),[B,f]=useState(e??""),[g,y]=useState(t),[v,P]=useState(o==="password"?"password":"open"),[b,O]=useState(""),[w,j]=useState(false),ue=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Ue(n.id,i)}]`},{label:"Access",value:"access",detail:`[${o==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],oe=ns(ue,s);function re(m){!s&&m!=="display-name"||(m==="room-name"?(f(e??""),A("editing-room-name")):m==="scale"?A("picking-scale"):m==="access"?A("picking-access"):m==="display-name"&&(y(t),A("editing-display-name")));}function V(m){let S=m.trim()===""?void 0:m.trim();a(S),A("main-menu");}function z(m){let S=m.trim();S.length>0&&(u(S),process.nextTick(()=>_({displayName:S}))),A("main-menu");}function X(m){let S=k.find(E=>E.id===m);S&&l(S),A("main-menu");}function Ce(m,S){let E={...p};S.length===0?delete E[m]:E[m]=S,R(E),_({presetOverrides:Object.keys(E).length>0?E:void 0});}async function he(m,S){j(true);try{await c(m,S),P(m),O(m==="password"?S??"":"");}catch(E){console.error(`Failed to update access: ${E}`);}finally{j(false),A("main-menu");}}return T==="main-menu"?jsx(ge,{title:"\u2500\u2500 Settings \u2500\u2500",items:oe,onSelect:re,onClose:d}):T==="editing-room-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Room name: "}),jsx(L,{value:B,onChange:f,onSubmit:V,onCancel:()=>A("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):T==="editing-display-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(L,{value:g,onChange:y,onSubmit:z,onCancel:()=>A("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):T==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Jt,{scales:k,selectedScaleId:n.id,presetOverrides:p,onSelect:X,onOverrideChange:Ce,onClose:()=>A("main-menu")})]}):T==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),w&&jsx(Text,{dimColor:true,children:"Updating access..."}),!w&&jsx(Lo,{mode:v,password:b,onModeChange:m=>{m==="open"&&he("open");},onPasswordChange:O,onClose:()=>A("main-menu")})]}):jsx(Box,{})}function Gt({participants:e,onlineIds:t,hostId:n,votes:o,revealed:r,participantId:i}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(s=>{let a=t.has(s.id),l=a?"\u25CF":"\u25CB",u=a?"green":"gray",c=s.id===n,d=Me(s)==="viewer",p=s.id===i,R=s.id in o,k=d?" (viewer)":r?o[s.id]?` \u2192 ${o[s.id]}`:"":R?" \u2713":" \xB7",T=p&&!d&&!(r&&o[s.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:u,children:l}),jsxs(Text,{children:[s.displayName,c?" (host)":""]}),T?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:d?"gray":R?"green":"gray",children:k})]},s.id)})]})}var os=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function Jo({onPick:e,onClose:t}){return jsx(ge,{title:"Host Actions",items:os,onSelect:e,onClose:t})}function qt({roomCode:e,onPick:t,onClose:n}){let o=[{label:"Copy code",value:"code",detail:Lt(e)},{label:"Copy share link",value:"url",detail:jt(e)},{label:"Copy npx command",value:"npx",detail:_t(e)}];return jsx(ge,{title:"Share",items:o,onSelect:r=>t(r),onClose:n})}function ss(e){let t=e.rounds.filter(o=>J(o)!==null),n=Object.fromEntries(e.participants.map(o=>[o.id,o]));return wo({rounds:t,participants:n})}async function Ko(e,t,n){let o=ss(e);try{await t(o),n("Results copied to clipboard");}catch{n("Clipboard write failed");}}function Wo(e,t,n){let o=co(e.id,n);return o===null?`Round ${t}`:`Round ${o.depth}/${o.total} [re-vote]`}function Go(e,t,n){let o=Wo(e,t,n),r=e.title?` \u2014 ${e.title}`:"",i=e.ticketId?` [${e.ticketId}]`:"",s=J(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${o}${r}${i}${s}`}function qo(e){let t=Object.values(e).filter(c=>!me(c)).map(c=>parseFloat(c)).filter(c=>!isNaN(c)).toSorted((c,d)=>c-d);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let o=t.reduce((c,d)=>c+d,0)/t.length,r=Math.floor(t.length/2),i=t.length%2===0?(t[r-1]+t[r])/2:t[r],s=Object.values(e).filter(c=>!me(c)),a=new Map;for(let c of s)a.set(c,(a.get(c)??0)+1);let l=Math.max(...a.values()),u=s.length>0?Math.round(l/s.length*100):0;return {average:o.toFixed(1),median:i.toFixed(1),agreement:`${u}%`}}function On(e,t){let n=Math.floor((t-e)/1e3),o=Math.floor(n/60),r=n%60;return `${o}:${r.toString().padStart(2,"0")}`}function zo(e,t,n=[]){let o=Wo(e,t,n);if(J(e)==="skipped"){let d=e.title?` ${e.title}`:"",p=e.ticketId?` [${e.ticketId}]`:"";return `${o}:${d}${p} \u2014 Skipped`}let r=new Map;for(let d of Object.values(e.votes))me(d)||r.set(d,(r.get(d)??0)+1);let i=[...r.entries()].toSorted((d,p)=>p[1]-d[1]||d[0].localeCompare(p[0])).map(([d,p])=>`${d}\xD7${p}`).join(", "),s=Object.values(e.votes).filter(me).length,a=s>0?` (${s} abstained)`:"",l=e.title?` ${e.title}`:"",u=e.ticketId?` [${e.ticketId}]`:"",c=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${On(e.timerStartedAt,e.revealedAt)}`:"";return `${o}:${l}${u} \u2014 ${i||"(no votes)"}${a}${c}`}function Xo({projection:e,onlineIds:t,isHost:n,participantId:o,rounds:r,currentRound:i,settingsOpen:s,onStartRound:a,onNewRound:l,onRevote:u,onOpenSettings:c,onHandoffHost:d,onEndSession:p,onShare:R,shareOpen:k,onSetShareOpen:T,roomCode:A,confirmingQuit:B,myRole:f,onToggleRole:g,roundTitlePromptActive:y,roundTitleInput:v,onRoundTitleChange:P,onRoundTitleSubmit:b,onRoundTitleCancel:O,roundTicketIdPromptActive:w,roundTicketIdInput:j,onRoundTicketIdChange:ue,onRoundTicketIdSubmit:oe,onRoundTicketIdCancel:re,descriptorPromptActive:V,descriptorInput:z,onDescriptorChange:X,onDescriptorSubmit:Ce,onDescriptorCancel:he,onEditDescriptor:m,canExport:S,onExportResults:E,onAgendaAdd:Y,agendaAddPromptActive:pe,agendaAddTitleInput:nt,onAgendaAddTitleChange:rn,onAgendaAddTitleSubmit:Ye,onAgendaAddTitleCancel:yt,agendaAddTicketIdPromptActive:ve,agendaAddTicketIdInput:sn,onAgendaAddTicketIdChange:Je,onAgendaAddTicketIdSubmit:Ke,onAgendaAddTicketIdCancel:Ne}){let[Q,Z]=zt.useState("idle"),[xe,be]=zt.useState(null),[ot,ie]=zt.useState(false),[fe,Pe]=zt.useState(false);useEffect(()=>{n||(Z("idle"),be(null),ie(false),Pe(false));},[n]),useInput(C=>{if(C==="c"||C==="C"){T(true);return}if(C==="w"||C==="W"){g();return}if((C==="x"||C==="X")&&S){E();return}if(n){if(C==="a"||C==="A"){Y();return}(C==="e"||C==="E")&&c(),(C==="s"||C==="S")&&a(),(C==="h"||C==="H")&&Z("picking"),(C==="m"||C==="M")&&ie(true),i!==null&&J(i)!==null&&((C==="n"||C==="N")&&l(),(C==="v"||C==="V")&&J(i)!=="skipped"&&u(),(C==="t"||C==="T")&&m());}},{isActive:!s&&!B&&Q==="idle"&&!y&&!w&&!ot&&!fe&&!k&&!V&&!pe&&!ve}),useInput((C,ee)=>{C==="y"||C==="Y"?(p(),Pe(false)):(C==="n"||C==="N"||ee.escape)&&Pe(false);},{isActive:fe});let Ie=e.participants.filter(C=>C.id!==o&&t.has(C.id));useInput(C=>{if(Q==="picking"){let ee=parseInt(C,10);!isNaN(ee)&&ee>=1&&ee<=Ie.length?(be(Ie[ee-1].id),Z("confirming")):(C==="Escape"||C==="q"||C==="Q")&&Z("idle");}},{isActive:Q==="picking"}),useInput(C=>{Q==="confirming"&&xe&&(C==="y"||C==="Y"?(d(xe),Z("idle"),be(null)):(C==="n"||C==="N"||C==="Escape")&&(Z("idle"),be(null)));},{isActive:Q==="confirming"});let De=r.length>0,Ct=r.filter(C=>J(C)!==null),rt=i!==null?Ct.slice(0,-1):Ct;return ot?jsx(Jo,{onPick:C=>{ie(false),C==="end-session"&&Pe(true);},onClose:()=>ie(false)}):k?jsx(qt,{roomCode:A,onPick:C=>{T(false),R(C);},onClose:()=>T(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:De?"Session":"Waiting for participants..."}),!De&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(Gt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:o}),e.agenda.length>0&&jsx(us,{items:e.agenda,nextPending:Xe(e)}),i!==null&&J(i)!==null&&jsx(ds,{projection:e,round:i,rounds:r}),rt.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),rt.map(C=>{let ee=r.indexOf(C)+1;return jsx(Text,{dimColor:true,children:zo(C,ee,r)},C.id)})]}),Q==="picking"&&Ie.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),Ie.map((C,ee)=>jsxs(Text,{children:["[",ee+1,"] ",C.displayName]},C.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="picking"&&Ie.length===0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"No other online participants"}),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="confirming"&&xe&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(C=>C.id===xe)?.displayName,"? [y/n]"]})}),y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(L,{value:v,onChange:P,onSubmit:b,onCancel:O,placeholder:"Enter to skip",isActive:y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(L,{value:j,onChange:ue,onSubmit:oe,onCancel:re,placeholder:"e.g. PROJ-1234",isActive:w})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),V&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(L,{value:z,onChange:X,onSubmit:Ce,onCancel:he,placeholder:"Enter to save",isActive:V})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),fe&&jsxs(Box,{children:[jsx(Text,{color:"red",children:"End session for everyone? This cannot be undone. "}),jsx(Text,{dimColor:true,children:"y/n [Esc] Cancel"})]}),pe&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda title (optional, Enter to skip):"}),jsx(L,{value:nt,onChange:rn,onSubmit:Ye,onCancel:yt,placeholder:"Enter to skip",isActive:pe})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),ve&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda ticket ID (optional, Enter to skip):"}),jsx(L,{value:sn,onChange:Je,onSubmit:Ke,onCancel:Ne,placeholder:"e.g. PROJ-1234",isActive:ve})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),Q==="idle"&&!y&&!w&&!V&&!fe&&!pe&&!ve&&jsxs(Box,{gap:2,children:[n?jsx(Fragment,{children:i!==null&&J(i)!==null?jsxs(Fragment,{children:[J(i)!=="skipped"&&jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[t] Edit title"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),S&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]}):jsxs(Fragment,{children:[jsx(Text,{color:"yellow",children:"[s] Start round"}),jsx(Text,{color:"yellow",children:"[a] Agenda"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),S&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]})}):jsxs(Fragment,{children:[jsx(Text,{dimColor:true,children:"Waiting for host to start a round..."}),jsx(Text,{children:"[c] Share"}),S&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function ds({projection:e,round:t,rounds:n}){let o=n.indexOf(t)+1,r=Go(t,o,n);if(J(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let i=qo(t.votes),s=new Map(e.participants.map(p=>[p.id,p.displayName])),a=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?On(t.timerStartedAt,t.revealedAt):null,l=Object.entries(t.votes),u=l.filter(([,p])=>!me(p)),c=l.filter(([,p])=>me(p)).map(([p])=>p),d=u[0]?.[1];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),no(t)&&d!==void 0&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",d]}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:2,children:[jsx(Text,{bold:true,underline:true,children:"Name".padEnd(20)}),jsx(Text,{bold:true,underline:true,children:"Estimate".padEnd(10)})]}),u.map(([p,R])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(s.get(p)??p).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:R.padEnd(10)})]},p)),c.map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:(s.get(p)??p).padEnd(20)}),jsx(Text,{dimColor:true,children:"(abstained)".padEnd(10)})]},p)),e.participants.filter(p=>!(p.id in t.votes)).map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:p.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},p.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:i.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:i.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:i.agreement})]}),a!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",a]})]})]})}var cs={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"},ls={consumed:"green",skipped:"yellow",cancelled:"red"};function us({items:e,nextPending:t}){let n=e.filter(o=>o.state!=="cancelled");return jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 Agenda \u2500\u2500"}),n.map(o=>{let r=cs[o.state]??"?",i=ls[o.state],s=t!==null&&o.id===t.id,a=[o.ticketId?`[${o.ticketId}]`:"",o.title??""].filter(Boolean).join(" ").trim()||o.id;return jsxs(Box,{gap:1,children:[i!==void 0?jsx(Text,{color:i,children:r}):jsx(Text,{children:r}),i!==void 0?jsx(Text,{color:i,children:a}):jsx(Text,{children:a}),s&&jsx(Text,{color:"cyan",children:"(next)"})]},o.id)}),n.length===0&&jsx(Text,{dimColor:true,children:"No pending items."})]})}function er({scale:e,selected:t,onSelect:n,onClear:o,disabled:r}){let[i,s]=useState(0);return useInput((a,l)=>{if(!r)if(l.leftArrow)s(u=>Math.max(0,u-1));else if(l.rightArrow)s(u=>Math.min(e.cards.length-1,u+1));else if(l.return){let u=e.cards[i];u===t?o():n(u);}else (l.backspace||l.delete)&&o();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((a,l)=>{let u=l===i,c=a===t;return jsx(Text,{inverse:u,bold:c,...c&&{color:"cyan"},children:c?`[${a}]`:` ${a} `},a)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function hs(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function tr({projection:e,round:t,onlineIds:n,isHost:o,myId:r,myRole:i,elapsedMs:s,roomCode:a,shareOpen:l,settingsOpen:u,onVote:c,onClearVote:d,onReveal:p,onSkip:R,onToggleRole:k,onShare:T,onSetShareOpen:A,onOpenSettings:B,confirmingQuit:f}){let g=t.votes[r],y=g!==void 0&&me(g);if(useInput(w=>{if(w==="e"||w==="E"){B();return}if(w==="c"||w==="C"){A(true);return}if(i==="voter"&&(w==="a"||w==="A")){y?d():c(It);return}o&&(w==="r"||w==="R")&&p(),o&&(w==="s"||w==="S")&&R(),(w==="w"||w==="W")&&k();},{isActive:!f&&!u&&!l}),l)return jsx(qt,{roomCode:a,onPick:w=>{A(false),T(w);},onClose:()=>A(false)});let v=g,P=e.rounds.indexOf(t)+1,b=t.title?` \u2014 ${t.title}`:"",O=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",P,b,O]}),s!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",hs(s)]})]}),jsxs(Box,{gap:4,children:[jsx(Gt,{participants:e.participants,onlineIds:n,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),i==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsxs(Box,{flexDirection:"column",gap:1,children:[y&&jsx(Text,{dimColor:true,children:"(abstaining this round \u2014 press [a] to vote)"}),jsx(er,{scale:t.scale,selected:y?void 0:v,onSelect:c,onClear:d,disabled:f||y})]})]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),o&&jsx(Text,{color:"yellow",children:"[s] Skip"}),i==="voter"&&jsxs(Text,{color:"yellow",children:["[a] ",y?"Vote":"Abstain"]}),jsxs(Text,{color:"yellow",children:["[w] ",i==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var ys=3e3;function Zt(e=ys){let[t,n]=useState(null),o=useRef(null),r=useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null);},[]),i=useCallback(a=>{r(),n(a),o.current=setTimeout(()=>{n(null),o.current=null;},e);},[r,e]),s=useCallback(()=>{r(),n(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:i,dismiss:s}}function bs(e){let t=te(e);return !t||J(t)!==null?"lobby":"voting"}function tn({session:e,participantId:t,displayName:n,accessMode:o,presetOverrides:r,customScales:i}){let{exit:s}=useApp(),[a,l]=useState(e.projection()),[u,c]=useState("connecting"),[d,p]=useState(e.onlineIds()),[R,k]=useState(),[T,A]=useState(false),[B,f]=useState(o==="password"?"password":"open"),[g,y]=useState(n),[v,P]=useState(false),[b,O]=useState(false),[w,j]=useState(""),[ue,oe]=useState(false),[re,V]=useState(""),[z,X]=useState(),[Ce,he]=useState(false),[m,S]=useState(""),[E,Y]=useState(null),[pe,nt]=useState(false),[rn,Ye]=useState(""),[yt,ve]=useState(false),[sn,Je]=useState(""),[Ke,Ne]=useState(),[Q,Z]=useState(),xe=Zt(3e3),[be,ot]=useState(false),ie=Zt(3e3),fe=Zt(3e3);useEffect(()=>{let I=e.onChange(()=>{l(e.projection()),p(e.onlineIds());}),$=e.onStatusChange(c),We=e.onHostChange(vt=>{let _r=e.projection().participants.find(Vr=>Vr.id===vt),Fr=vt===t?"You are now the host":`${_r?.displayName||"Unknown"} is now the host`;xe.show(Fr);}),dn=setInterval(()=>{p(e.onlineIds());let vt=e.projection(),bt=te(vt);bt?.timerStartedAt!==void 0&&bt.revealedAt===void 0?k(Date.now()-bt.timerStartedAt):k(void 0);},1e3);return ()=>{I(),$(),We(),clearInterval(dn);}},[e,t,xe.show]),useInput(I=>{(I==="q"||I==="Q")&&P(true);},{isActive:!T&&!v&&!b&&!ue&&!Ce&&!be&&!pe&&!yt}),useInput((I,$)=>{I==="y"||I==="Y"?(e.disconnect(),s()):(I==="n"||I==="N"||$.escape)&&P(false);},{isActive:v});let Pe=bs(a),Ie=te(a),De=a.settings.hostParticipantId===t,Ct=a.participants.find(I=>I.id===t),rt=Me(Ct??{}),C=useCallback(()=>{let I=Ft(Xe(a));j(I.title),Z(I.agendaItemId),O(true);},[a]),ee=useCallback(I=>{O(false),j(""),X(bn(I));let $=Ft(Xe(a));V($.ticketId),oe(true);},[a]),mr=useCallback(()=>{O(false),j(""),X(void 0),Z(void 0);},[]),gr=useCallback(I=>{oe(false),V("");let[$,We,dn]=Do(z,I,Q);e.newRound($,We,dn),X(void 0),Z(void 0);},[e,z,Q]),hr=useCallback(()=>{oe(false),V(""),X(void 0),Z(void 0);},[]),xr=useCallback(()=>{let I=e.current();!I||I.revealedAt===void 0||(Y(I.id),S(I.title??""),he(true));},[e]),Sr=useCallback(I=>{let $=E;if(he(false),Y(null),!$)return;let We=I.trim();We!==""&&e.updateRoundDescriptor($,{title:We});},[e,E]),wr=useCallback(()=>{he(false),Y(null);},[]),yr=useCallback(I=>{e.vote(I);},[e]),Cr=useCallback(()=>{e.unvote();},[e]),vr=useCallback(()=>{e.reveal();},[e]),br=useCallback(()=>{e.skip();},[e]),Ir=useCallback(()=>{let I=Ft(Xe(a));j(I.title),Z(I.agendaItemId),O(true);},[a]),Ar=useCallback(()=>{e.revote();},[e]),Hn=useCallback(()=>{e.toggleRole();},[e]),Tr=useCallback(I=>{e.updateName(I);},[e]),Rr=useCallback(I=>{e.updateScale(I);},[e]),Er=useCallback(I=>{e.updateDisplayName(I),y(I);},[e]),kr=useCallback(async(I,$)=>{await e.updateAccess(I,$),f(I);},[e]),Nr=useCallback(I=>{try{e.handoffHost(I);}catch($){console.error(`Handoff failed: ${$ instanceof Error?$.message:String($)}`);}},[e]),Ln=useCallback(()=>{A(true);},[]),Pr=useCallback(()=>{A(false);},[]),Dr=useCallback(()=>{e.endSessionForEveryone();},[e]),jn=useCallback(async I=>{let $=I==="code"?Lt(e.roomCode):I==="url"?jt(e.roomCode):_t(e.roomCode);try{await or.write($),ie.show("Copied!");}catch{ie.show(`Copy failed \u2014 ${$}`);}},[e.roomCode,ie]),an=a.rounds.filter(I=>J(I)!==null),Or=an.length>0?an.at(-1):null,Mr=an.length>0,$r=useCallback(()=>Ko(a,I=>or.write(I),fe.show),[a,fe.show]),Br=useCallback(()=>{Ye(""),nt(true);},[]),Ur=useCallback(I=>{nt(false),Ye("");let $=I.trim()===""?void 0:I.trim();Ne($),Je(""),ve(true);},[]),Hr=useCallback(()=>{nt(false),Ye(""),Ne(void 0);},[]),Lr=useCallback(I=>{ve(false),Je("");let $=I.trim()===""?void 0:I.trim();if(!Ke&&!$){Ne(void 0);return}Pt(e.doc,{...Ke!==void 0&&{title:Ke},...$!==void 0&&{ticketId:$},createdAt:Date.now()}),Ne(void 0);},[e.doc,Ke]),jr=useCallback(()=>{ve(false),Je(""),Ne(void 0);},[]);return jsxs(Box,{flexDirection:"column",children:[jsx($o,{roomCode:e.roomCode,sessionName:a.settings.name,status:u,isHost:De}),xe.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:xe.notice})}),ie.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ie.notice.startsWith("Copy failed")?"red":"green",children:ie.notice})}),fe.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:fe.notice.startsWith("Clipboard write failed")?"red":"green",children:fe.notice})}),T?jsx(Vo,{sessionName:a.settings.name,displayName:g,currentScale:a.settings.defaultScale,accessMode:B,presetOverrides:r,customScales:i,isHost:De,onChangeName:Tr,onChangeScale:Rr,onChangeDisplayName:Er,onChangeAccess:kr,onClose:Pr}):Pe==="lobby"?jsx(Xo,{projection:a,onlineIds:d,isHost:De,participantId:t,rounds:a.rounds,currentRound:Or,settingsOpen:T,onStartRound:C,onNewRound:Ir,roundTitlePromptActive:b,roundTitleInput:w,onRoundTitleChange:j,onRoundTitleSubmit:ee,onRoundTitleCancel:mr,roundTicketIdPromptActive:ue,roundTicketIdInput:re,onRoundTicketIdChange:V,onRoundTicketIdSubmit:gr,onRoundTicketIdCancel:hr,onRevote:Ar,onOpenSettings:Ln,onHandoffHost:Nr,onEndSession:Dr,onShare:jn,shareOpen:be,onSetShareOpen:ot,roomCode:e.roomCode,confirmingQuit:v,myRole:rt,onToggleRole:Hn,descriptorPromptActive:Ce,descriptorInput:m,onDescriptorChange:S,onDescriptorSubmit:Sr,onDescriptorCancel:wr,onEditDescriptor:xr,canExport:Mr,onExportResults:$r,onAgendaAdd:Br,agendaAddPromptActive:pe,agendaAddTitleInput:rn,onAgendaAddTitleChange:Ye,onAgendaAddTitleSubmit:Ur,onAgendaAddTitleCancel:Hr,agendaAddTicketIdPromptActive:yt,agendaAddTicketIdInput:sn,onAgendaAddTicketIdChange:Je,onAgendaAddTicketIdSubmit:Lr,onAgendaAddTicketIdCancel:jr}):Pe==="voting"&&Ie?jsx(tr,{projection:a,round:Ie,onlineIds:d,isHost:De,myId:t,myRole:rt,elapsedMs:R,onVote:yr,onClearVote:Cr,onReveal:vr,onSkip:br,onToggleRole:Hn,onShare:jn,onSetShareOpen:ot,shareOpen:be,settingsOpen:T,onOpenSettings:Ln,roomCode:e.roomCode,confirmingQuit:v}):null,v&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function rr({presetOverrides:e,customScales:t}){let{exit:n}=useApp(),[o,r]=useState("main-menu"),[i,s]=useState(He()),[a,l]=useState(i.displayName??""),[u,c]=useState(i.relayUrl??""),[d,p]=useState(i.defaultSessionName??""),[R,k]=useState(i.avatarColor?.startsWith("#")?i.avatarColor:""),[T,A]=useState(t??[]),[B,f]=useState(e??{});useInput(m=>{(m==="q"||m==="Q")&&n();},{isActive:o==="main-menu"});let g=useMemo(()=>Mt(B,T),[B,T]),y=i.defaultScale,v=y?g.find(m=>m.id===y):void 0,P=[{label:"Display name",value:"display-name",detail:`[${i.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${i.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${v?Ue(v.id,T):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${i.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${i.defaultPassword?"on":"off"}]`},{label:"Avatar color",value:"avatar-color",detail:`[${ks(i.avatarColor)}]`}];function b(m){m==="display-name"?(l(i.displayName??""),r("editing-display-name")):m==="relay-url"?(c(i.relayUrl??""),r("editing-relay-url")):m==="default-scale"?r("picking-scale"):m==="default-session-name"?(p(i.defaultSessionName??""),r("editing-session-name")):m==="default-password"?r("picking-default-password"):m==="avatar-color"&&r("picking-avatar-color");}function O(m){if(m==="custom-hex"){k(i.avatarColor?.startsWith("#")?i.avatarColor:""),r("editing-avatar-hex");return}if(Oe(m)===null){r("main-menu");return}s({...i,avatarColor:m}),_({avatarColor:m}),r("main-menu");}function w(m){let S=m.trim();if(S.length===0){r("picking-avatar-color");return}let E=S.startsWith("#")?S.toLowerCase():`#${S.toLowerCase()}`;Oe(E)!==null&&(s({...i,avatarColor:E}),_({avatarColor:E}),r("main-menu"));}function j(m){let S=m.trim();if(S.length>0){let E={...i,displayName:S};s(E),_({displayName:S});}r("main-menu");}function ue(m){let S=m.trim();if(S.length>0){let E={...i,relayUrl:S};s(E),_({relayUrl:S});}r("main-menu");}function oe(m){let S=m.trim(),E=S.length>0?{...i,defaultSessionName:S}:{...i};S.length===0?(delete E.defaultSessionName,s(E),ut({defaultSessionName:""})):(s(E),_({defaultSessionName:S})),r("main-menu");}function re(m){let S=m.length>0?{...i,defaultScale:m}:{...i};m.length===0?(delete S.defaultScale,s(S),ut({defaultScale:""})):(s(S),_({defaultScale:m})),r("main-menu");}function V(m,S){let E={...B};S.length===0?delete E[m]:E[m]=S,f(E),_({presetOverrides:Object.keys(E).length>0?E:void 0});}function z(m){let S=m==="on",E={...i,defaultPassword:S};s(E),_({defaultPassword:S}),r("main-menu");}function X(m,S){let E=`custom-${randomUUID()}`,Y=[...T,{id:E,label:m,cards:S}];A(Y),s({...i,customScales:Y}),_({customScales:Y});}function Ce(m,S,E){let Y=T.map(pe=>pe.id===m?{id:m,label:S,cards:E}:pe);A(Y),s({...i,customScales:Y}),_({customScales:Y});}function he(m){let S=T.filter(Y=>Y.id!==m);A(S);let E={...i,customScales:S};i.defaultScale===m?(E.defaultScale="fibonacci",_({customScales:S,defaultScale:"fibonacci"})):_({customScales:S}),s(E);}if(o==="main-menu")return jsx(ge,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:P,onSelect:b,onClose:()=>n()});if(o==="editing-display-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(L,{value:a,onChange:l,onSubmit:j,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-relay-url")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Relay URL: "}),jsx(L,{value:u,onChange:c,onSubmit:ue,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-session-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Default session name: "}),jsx(L,{value:d,onChange:p,onSubmit:oe,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="picking-scale"){let m=[{id:"",cards:[]},...g];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Jt,{scales:m,selectedScaleId:y??"",presetOverrides:B,customScales:T,onSelect:re,onOverrideChange:V,onCustomScaleCreate:X,onCustomScaleEdit:Ce,onCustomScaleDelete:he,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(o==="picking-avatar-color"){let m=it.map(S=>({label:Ge[S].label,value:S,detail:i.avatarColor===S?"[current]":Ge[S].base}));return m.push({label:"Custom hex\u2026",value:"custom-hex",detail:i.avatarColor?.startsWith("#")?`[${i.avatarColor}]`:void 0}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(ge,{title:"Avatar color:",items:m,onSelect:O,onClose:()=>r("main-menu")})]})}if(o==="editing-avatar-hex")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Custom hex color: "}),jsx(L,{value:R,onChange:k,onSubmit:w,onCancel:()=>r("picking-avatar-color"),placeholder:"#rrggbb",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="picking-default-password"){let m=[{label:"On",value:"on",detail:i.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:i.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(ge,{title:"Default password:",items:m,onSelect:z,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}function ks(e){return e?e.startsWith("#")?e:it.includes(e)?Ge[e].label:e:"(auto)"}var Ps={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"};function Ds(e){let t=Ps[e.state]??"?",n=[];e.ticketId&&n.push(`[${e.ticketId}]`),e.title&&n.push(e.title);let o=n.join(" ")||e.id;return `${t} ${o}`}async function St(e){let t=new $e.Doc,n=new Awareness(t);qe(t,{participantId:e.participantId,displayName:e.displayName}),n.setLocalStateField("participantId",e.participantId);let o=Qe({doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}});return await new Promise(r=>{let i=setTimeout(r,2e3),s=o.onStatusChange(a=>{a==="connected"&&setTimeout(()=>{clearTimeout(i),s(),r();},200);});}),{doc:t,disconnect:()=>o.disconnect()}}async function wt(){let e=$t();return e||(console.error("No active session. Join a room first with: hnch join <code>"),process.exit(1)),{roomCode:e.roomCode,roomUuid:e.roomUuid,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}}}async function sr(e){!e.title?.trim()&&!e.ticket?.trim()&&(console.error("At least one of --title or --ticket is required"),process.exit(1));let t=await ae(),n=await wt();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await St({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{let i=Pt(o,{...e.title?.trim()?{title:e.title.trim()}:{},...e.ticket?.trim()?{ticketId:e.ticket.trim()}:{},...e.description?.trim()?{description:e.description.trim()}:{},createdAt:Date.now()});await new Promise(s=>{setTimeout(s,300);}),console.log(`Added agenda item: ${i}`);}finally{r();}}async function ar(){let e=await ae(),t=await wt();try{await de(e.relayUrl,t.roomCode);}catch{console.error(`Room ${t.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:n,disconnect:o}=await St({relayUrl:e.relayUrl,participantId:e.participantId,displayName:e.displayName,roomCode:t.roomCode,roomUuid:t.roomUuid,...t.passwordHash!==void 0&&{passwordHash:t.passwordHash}});try{let i=K(n).agenda;if(i.length===0){console.log("No agenda items.");return}i.forEach((s,a)=>{console.log(`${String(a+1).padStart(2)}. ${Ds(s)}`);});}finally{o();}}async function dr(e){let t=await ae(),n=await wt();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await St({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{Dt(o,e.id,"skipped",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Skipped agenda item: ${e.id}`);}catch(i){console.error(`Skip failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function cr(e){let t=await ae(),n=await wt();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await St({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{Dt(o,e.id,"cancelled",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Cancelled agenda item: ${e.id}`);}catch(i){console.error(`Cancel failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function lr(e){let t=await ae(),n=await wt();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await St({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{io(o,e.id,e.before,e.after),await new Promise(i=>{setTimeout(i,300);}),console.log(`Reordered agenda item: ${e.id}`);}catch(i){console.error(`Move failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function Un(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",n=>{t.close(),e(n);});})}async function Bs(e){let t=await ae(),n=e.scale??t.defaultScale??"fibonacci",o=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,i;r&&(i=await Un());let s=Ot(n,t.presetOverrides,t.customScales);if(!s){let d=Object.keys(se).join(", ");console.error(`Unknown or fully-disabled scale: "${n}". Builtin IDs: ${d}`),process.exit(1);}let a=await Eo({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:o,password:i,defaultScale:s,...t.avatarColor!==void 0&&{avatarColor:t.avatarColor}}),l;i&&(l=await Be(i,a.roomUuid)),Bt({roomCode:a.roomCode,roomUuid:a.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Room created: ${a.roomCode}`),console.error(`Share: hnch join ${a.roomCode}`),console.error("");let{waitUntilExit:u,unmount:c}=render(zt.createElement(tn,{session:a,participantId:t.participantId,displayName:t.displayName,accessMode:i?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));Ht({doc:a.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),c();try{await F();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}a.disconnect(),process.exit(0);}}),await u(),a.disconnect(),F(),process.exit(0);}async function Us(e){let t=await ae(),n=No(e.code);n===null&&(console.error("invalid room code"),process.exit(1));let o;e.password&&(o=await Un());let r=await de(t.relayUrl,n),i;r.accessMode==="password"&&!e.password?i=await Un():e.password&&(i=o);let s,a=false,l=await ko({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:n,password:i,...t.avatarColor!==void 0&&{avatarColor:t.avatarColor},onRejection(d){if(d==="unknown-room"){Ut({clearLastSession:F,logger:console,exit:process.exit});return}d==="room-full"&&(a=true,s?.());}}),u;i&&(u=await Be(i,l.roomUuid)),Bt({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Joined room: ${l.roomCode}`),console.error("");let c=render(zt.createElement(tn,{session:l,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));s=c.unmount,Ht({doc:l.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),s?.();try{await F();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}l.disconnect(),process.exit(0);}}),await c.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),l.disconnect(),F(),process.exit(1)),l.disconnect(),F(),process.exit(0);}async function Hs(){let e=await ae(),t=$t();t||(console.error("No recent session to resume."),process.exit(0));let n;try{n=await de(e.relayUrl,t.roomCode);}catch(c){if((c instanceof Error?c.message:String(c)).includes("Room not found"))return await Ut({clearLastSession:F,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}n.accessMode==="password"&&!t.passwordHash&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),F(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let o=new $e.Doc,r=new Awareness(o);qe(o,{participantId:e.participantId,displayName:e.displayName,...e.avatarColor!==void 0&&{avatarColor:e.avatarColor}}),r.setLocalStateField("participantId",e.participantId);let i=false,s=false,a,l=Qe({doc:o,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(c){if(c==="unknown-room"){Ut({clearLastSession:F,logger:console,exit:process.exit});return}c==="wrong-password"&&(i=true,a?.()),c==="room-full"&&(s=true,a?.());}});Bt({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let u=render(zt.createElement(tn,{session:l,participantId:e.participantId,displayName:e.displayName,accessMode:n.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));a=u.unmount,Ht({doc:l.doc,localParticipantId:e.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),a?.();try{await F();}catch(d){console.error(`Failed to clear cached session: ${d instanceof Error?d.message:String(d)}`);}l.disconnect(),process.exit(0);}}),await u.waitUntilExit(),s&&(console.error("This room is full (max 20 participants)."),F(),process.exit(1)),i&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),F(),process.exit(0)),l.disconnect(),F(),process.exit(0);}async function Ls(e){if(!(e.name!==void 0||e.relayUrl!==void 0||e.scale!==void 0||e.sessionName!==void 0||e.password!==void 0||e.color!==void 0)){let o=await ae(),{waitUntilExit:r}=render(zt.createElement(rr,{presetOverrides:o.presetOverrides,customScales:o.customScales}));await r(),process.exit(0);}let n={};if(e.name!==void 0&&(n.displayName=e.name),e.relayUrl!==void 0&&(n.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let o=He();if(!Ot(e.scale,o.presetOverrides,o.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(se).join(", ")}`);return}}n.defaultScale=e.scale;}if(e.sessionName!==void 0&&(n.defaultSessionName=e.sessionName),e.password!==void 0&&(n.defaultPassword=e.password),e.color!==void 0){let o=e.color.startsWith("#")||e.color===""?e.color:e.color.toLowerCase();o!==""&&Oe(o)===null&&(console.error(`Invalid color: "${e.color}". Pass a palette key or #rrggbb hex literal.`),process.exit(1)),n.avatarColor=o;}ut(n),console.log("Config updated.");}var fr=Os(hideBin(process.argv)).scriptName("hnch").usage("$0 <command> \u2014 terminal pointing poker").command("create","Create a new room",e=>e.option("name",{type:"string",describe:"Session name"}).option("password",{type:"boolean",describe:"Protect room with a password"}).option("scale",{type:"string",describe:"Estimation scale ID (fibonacci, t-shirt, powers-of-2, linear, risk, or custom-<id>)"}),e=>{Bs(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("join <code>","Join an existing room",e=>e.positional("code",{type:"string",demandOption:true,describe:"6-character room code"}).option("password",{type:"boolean",describe:"Room requires a password",default:false}),e=>{Us(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Hs().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1);});}).command("config","View or update CLI config",e=>e.option("name",{type:"string",describe:"Set display name"}).option("relay-url",{type:"string",describe:"Set relay URL"}).option("scale",{type:"string",describe:"Set default estimation scale ID (empty string clears)"}).option("session-name",{type:"string",describe:"Set default session name (empty string clears)"}).option("password",{type:"boolean",describe:"Set default password prompt on (--password) or off (--no-password)"}).option("color",{type:"string",describe:'Set avatar color: a palette key (e.g. "blue", "racing-green") or a #rrggbb hex literal'}),e=>{Ls(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("agenda","Manage the pre-session story agenda",e=>e.command("add","Add an agenda item",t=>t.option("title",{type:"string",describe:"Story title"}).option("ticket",{type:"string",describe:"Issue tracker reference (e.g. PROJ-123)"}).option("description",{type:"string",describe:"Story description"}).check(n=>{if(!n.title?.trim()&&!n.ticket?.trim())throw new Error("At least one of --title or --ticket is required");return true}),t=>{sr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("list","List agenda items in order",t=>t,()=>{ar().catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("skip <id>","Mark an agenda item as skipped",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{dr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("cancel <id>","Soft-delete (cancel) an agenda item",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{cr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("mv <id>","Reorder an agenda item (--before <id> | --after <id>)",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID to move"}).option("before",{type:"string",describe:"sortKey of item that should come before the moved item"}).option("after",{type:"string",describe:"sortKey of item that should come after the moved item"}).check(n=>{if(n.before!==void 0&&n.after!==void 0)throw new Error("--before and --after are mutually exclusive");if(n.before===void 0&&n.after===void 0)throw new Error("Specify either --before <id> or --after <id>");return true}),t=>{lr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).demandCommand(1,"Specify an agenda subcommand: add, list, skip, cancel, mv").strict().help(),()=>{}).demandCommand(1,"Specify a command: create, join, resume, config, or agenda").strict().help(),Bn=hideBin(process.argv);(Bn.length===0||Bn.length===1&&Bn[0]==="--")&&(fr.showHelp(),process.exit(0));fr.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xauyxau/hnch",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "Pointing poker CLI for agile teams",
5
5
  "keywords": [
6
6
  "pointing-poker",