@xauyxau/hnch 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +12 -12
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf-8");}async function
|
|
4
|
-
`,"utf-8");}var ir={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},mn=new Map(Object.entries(ir).map(([e,t])=>[t,e]));function be(e){return e.role??"voter"}function W(e){let{revealedAt:t,skippedAt:o}=e;return t===void 0&&o===void 0?null:t===void 0?"skipped":o===void 0||t<=o?"revealed":"skipped"}var ot={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},gn={id:"t-shirt",cards:["XS","S","M","L","XL"]},hn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},Sn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},xn={id:"risk",cards:["Low","Medium","High","Critical"]},se={[ot.id]:ot,[gn.id]:gn,[hn.id]:hn,[Sn.id]:Sn,[xn.id]:xn},wn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function yn(e){return e in wn?wn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(o=>o.length===0?o:o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}var ar="meta",Fe="settings",cr="participants",dr="rounds",lr=["roomUuid","createdAt","createdBy","sessionEndedAt"],ur=["name","defaultScale","hostParticipantId"],pr=["displayName","joinedAt","role","leftAt","removedBy"],fr=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt"];function rt(e){return e.getMap(ar)}function st(e){return e.getMap(Fe)}function it(e){return e.getMap(cr)}function Bt(e){return e.getArray(dr)}function at(e,t){let o={};for(let n of t){let r=e.get(n);r!==void 0&&(o[n]=r);}return o}function mr(e){return at(rt(e),lr)}function gr(e){return at(st(e),ur)}function hr(e){let t=it(e),o=[];return t.forEach((n,r)=>{let s=at(n,pr);o.push({id:r,...s});}),o.sort((n,r)=>n.joinedAt-r.joinedAt||n.id.localeCompare(r.id)),o}function Sr(e){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}function xr(e){let t=at(e,fr),o=e.get("votes"),n=o?Sr(o):{};return {...t,votes:n}}function wr(e){let t=Bt(e),o=[];return t.forEach(n=>{o.push(xr(n));}),o}function Q(e){return {meta:mr(e),settings:gr(e),participants:hr(e),rounds:wr(e)}}function vn(e,t){if(rt(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let o=rt(e);o.set("roomUuid",t.roomUuid),o.set("createdAt",t.createdAt),o.set("createdBy",t.participantId);let n=st(e);t.sessionName!==void 0&&n.set("name",t.sessionName),n.set("defaultScale",t.defaultScale),n.set("hostParticipantId",t.participantId);let r=new Oe.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),it(e).set(t.participantId,r);});}function ct(e,t){e.transact(()=>{let o=it(e),n=o.get(t.participantId),r=n??new Oe.Map;r.set("displayName",t.displayName),n===void 0&&r.set("joinedAt",Date.now()),r.delete("leftAt"),r.delete("removedBy"),n===void 0&&o.set(t.participantId,r);});}function Me(e,t){e.transact(()=>{let o=st(e);for(let[n,r]of Object.entries(t))r===void 0?o.delete(n):o.set(n,r);});}function Ht(e,t,o){e.transact(()=>{let n=it(e),r=n.get(t),s=r??new Oe.Map;s.set("displayName",o.displayName),s.set("joinedAt",o.joinedAt),o.role!==void 0&&s.set("role",o.role),r===void 0&&n.set(t,s);});}function Ut(e,t){let o=t.scale??st(e).get("defaultScale");if(!o)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let n=new Oe.Map;n.set("id",t.id),n.set("createdAt",t.createdAt),n.set("createdBy",t.createdBy),n.set("scale",o),t.title!==void 0&&n.set("title",t.title),t.description!==void 0&&n.set("description",t.description),t.ticketId!==void 0&&n.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&n.set("parentRoundId",t.parentRoundId),n.set("timerStartedAt",t.createdAt),n.set("votes",new Oe.Map),Bt(e).push([n]);}),t.id}function Cn(e,t,o){let n=Ve(e,t);if(!n)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{o.title!==void 0&&n.set("title",o.title),o.description!==void 0&&n.set("description",o.description);});}function Ve(e,t){let o=Bt(e);for(let n=0;n<o.length;n+=1){let r=o.get(n);if(r.get("id")===t)return r}}function bn(e,t,o,n){let r=Ve(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(o,n);});}function Rn(e,t,o){let n=Ve(e,t);if(!n)throw new Error(`clearVote: round ${t} not found`);n.get("revealedAt")===void 0&&e.transact(()=>{n.get("votes").delete(o);});}function jt(e,t,o){let n=Ve(e,t);if(!n)throw new Error(`revealRound: round ${t} not found`);if(n.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{n.set("revealedAt",o);});}function In(e,t,o){let n=Ve(e,t);if(!n)throw new Error(`skipRound: round ${t} not found`);if(n.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(n.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{n.set("skippedAt",o);});}function Tn(e){e.transact(()=>{rt(e).set("sessionEndedAt",Date.now());});}function ee(e){let{rounds:t}=e;if(t.length===0)return null;for(let o=t.length-1;o>=0;o-=1){let n=t[o];if(n.revealedAt===void 0)return n}return t.at(-1)}function En(e){let t=Object.values(e.votes);return t.length<2?false:t.every(o=>o===t[0])}function An(e){let t=Math.max(0,Math.floor(e/1e3)),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function Nn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}function Pn(e,t){let o=new Map;for(let d of t)o.set(d.id,d);let n=o.get(e);if(n===void 0||n.parentRoundId===void 0)return null;let r=new Set([n.id]),s=n,c=1;for(;s.parentRoundId!==void 0;){let d=o.get(s.parentRoundId);if(d===void 0||r.has(d.id))return null;r.add(d.id),s=d,c+=1;}let i=s,u=new Map;for(let d of t){if(d.parentRoundId===void 0)continue;let f=u.get(d.parentRoundId);f===void 0?u.set(d.parentRoundId,[d]):f.push(d);}let l=0,a=[i];for(;a.length>0;){let d=a.shift();l+=1;let f=u.get(d.id);f!==void 0&&a.push(...f);}return {chainRoot:i,depth:c,total:l}}var Dn="PBKDF2",yr="SHA-256",kn=new TextEncoder;function vr(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Re(e,t){let o=await crypto.subtle.importKey("raw",kn.encode(e),Dn,false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:Dn,salt:kn.encode(t),iterations:1e5,hash:yr},o,256);return vr(n)}var On="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(On.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${On.length}`);function Lt(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function Mn(e,t=true){let o=Lt(e);return !t||o.length!==6?o:`${o.slice(0,3)}-${o.slice(3)}`}function Cr(e,t){let o=new Map;t.forEach((s,c)=>o.set(s,c));let n=[...new Set(e.filter(s=>!o.has(s)))].toSorted(),r=new Map;return n.forEach((s,c)=>r.set(s,t.length+c)),s=>o.get(s)??r.get(s)??Number.MAX_SAFE_INTEGER}function _t(e,t){let o=new Map;for(let c of e)o.set(c,(o.get(c)??0)+1);let n=null,r=0,s=[...o.keys()].toSorted((c,i)=>t(c)-t(i));for(let c of s){let i=o.get(c);i>r&&(r=i,n=c);}return n}function $n(e,t){let o=Object.values(e);if(o.length===0)return null;let n=Cr(o,t.cards);if(t.cards.every(c=>Number.isFinite(parseFloat(c)))){let c=o.map(parseFloat).filter(Number.isFinite);if(c.length===0)return {kind:"categorical",mode:_t(o,n)};let i=c.reduce((C,A)=>C+A,0)/c.length,u=[...c].toSorted((C,A)=>C-A),l=Math.floor(u.length/2),a=u.length%2===1?u[l]:(u[l-1]+u[l])/2,d=_t(o,n),f;if(new Set(o).size===1)f="unanimous";else {let C=o.map(R=>n(R)),A=Math.min(...C);f=Math.max(...C)-A<=1?"close":"spread";}return {kind:"numeric",mean:i,median:a,mode:d,spread:f}}return {kind:"categorical",mode:_t(o,n)}}function Bn(e){return e.replaceAll(/\|/g,"\\|")}function br(e){return e.replaceAll(/\\/g,"\\\\").replaceAll(/]/g,"\\]")}function Rr(e){let o=(e.match(/`+/g)??[]).reduce((n,r)=>Math.max(n,r.length),0);return "`".repeat(o+1)}function Ft(e){if(!e)return "";if(Nn(e))return ` ([${br(e)}](<${e}>))`;let t=Rr(e);return ` (${t}${e}${t})`}function Ir(e){return e instanceof Map?e:new Map(Object.entries(e))}function Tr(e){let t=new Map;for(let r of e)t.set(r.id,r);function o(r){if(!r.parentRoundId)return r;let s=t.get(r.parentRoundId);return s?o(s):r}let n=new Map;for(let r of e){let s=o(r),c=n.get(s.id);c?c.push(r):n.set(s.id,[r]);}return n}function Hn(e,t){let o=new Map;e.scale.cards.forEach((c,i)=>o.set(c,i));let n=new Map;for(let[c,i]of Object.entries(e.votes)){let u=t.get(c)??c,l=n.get(i);l?l.push(u):n.set(i,[u]);}let r=[...n.entries()].map(([c,i])=>({card:c,scaleIndex:o.get(c)??Number.MAX_SAFE_INTEGER,voters:[...i].toSorted().map(Bn)}));return r.sort((c,i)=>{let u=i.voters.length-c.voters.length;return u!==0?u:c.scaleIndex-i.scaleIndex}),["| Vote | Voters |","|------|--------|",...r.map(c=>`| ${Bn(c.card)} | ${c.voters.join(", ")} |`)].join(`
|
|
5
|
-
`)}function
|
|
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}
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${A}
|
|
8
8
|
|
|
9
|
-
${
|
|
9
|
+
${H}`:`${R}
|
|
10
10
|
|
|
11
|
-
${
|
|
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}
|
|
12
12
|
|
|
13
|
-
${
|
|
13
|
+
${N}
|
|
14
14
|
|
|
15
|
-
${
|
|
15
|
+
${w}`:`${v}
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${N}`;u.push(D);}}return u.join(`
|
|
18
18
|
|
|
19
19
|
`)+`
|
|
20
|
-
`}function
|
|
21
|
-
`,{encoding:"utf-8",mode:384}),chmodSync(o,384);}function F(){let e=Jt();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function ft(e){let t=true;try{await e.clearLastSession();}catch(o){t=false,e.logger.error(`Failed to clear cached session: ${o instanceof Error?o.message:String(o)}`);}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 mt(e){let t=e.doc.getMap("meta"),o=null,n=false;function r(){if(n)return;let s=t.get("sessionEndedAt");if(s==null||s===o)return;o=s;let c=t.get("createdBy"),i=c===e.localParticipantId,u=e.doc.getMap("participants"),l=e.doc.getMap("settings").get("hostParticipantId")??c,a="host";if(l){let f=u.get(l)?.get("displayName");typeof f=="string"&&f.length>0&&(a=f);}setImmediate(()=>{n||e.onEnded({isLocal:i,hostName:a,timestamp:s});});}return t.observe(r),r(),()=>{n=true,t.unobserve(r);}}var Ur="@xauyxau/hnch";function gt(e){return Mn(e)}function ht(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function St(e){return `npx ${Ur} join ${e}`}function Wt(e){let t=e.trim();return t===""?void 0:t}function Xn(e,t){return [e,Wt(t)]}var jr={connecting:"yellow",connected:"green",disconnected:"red"};function Zn({roomCode:e,sessionName:t,status:o,isHost:n}){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:[n&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:jr[o],children:o})]})]})}function pe({items:e,onSelect:t,onClose:o,title:n}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(i=>!i.disabled),[s,c]=useState(Math.max(r,0));return useInput((i,u)=>{if(u.upArrow)c(l=>{let a=(l-1+e.length)%e.length,d=0;for(;e[a]?.disabled&&d<e.length;)a=(a-1+e.length)%e.length,d++;return a});else if(u.downArrow)c(l=>{let a=(l+1)%e.length,d=0;for(;e[a]?.disabled&&d<e.length;)a=(a+1)%e.length,d++;return a});else if(u.return){let l=e[s];l&&!l.disabled&&t(l.value);}else u.escape&&o?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Box,{flexDirection:"column",children:e.map((i,u)=>{let l=u===s,a=i.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...l&&{color:"cyan"},dimColor:a,children:l?">":" "}),jsx(Text,{bold:l,dimColor:a,children:i.label}),i.detail&&jsx(Text,{dimColor:true,children:i.detail})]},i.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function q({value:e,onChange:t,onSubmit:o,onCancel:n,placeholder:r,isActive:s=true,mask:c=false}){useInput((a,d)=>{d.escape?n?.():d.return?o(e):d.backspace||d.delete?t(e.slice(0,-1)):a&&!d.ctrl&&!d.meta&&t(e+a);},{isActive:s});let i=c&&e.length>0?"*".repeat(e.length):e,u=i.length>0?i:r??"",l=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:l,children:u}),jsx(Text,{inverse:true,children:" "})]})}function oo({mode:e,password:t,onModeChange:o,onPasswordChange:n,onClose:r}){let[s,c]=useState(e==="open"?0:1),[i,u]=useState(false);return useEffect(()=>{c(e==="open"?0:1);},[e]),useInput((l,a)=>{if(a.leftArrow)c(d=>Math.max(0,d-1));else if(a.rightArrow)c(d=>Math.min(1,d+1));else if(a.return){let d=s===0?"open":"password";d!==e&&o(d),d==="password"&&u(true);}else a.escape&&r?.();},{isActive:!i}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((l,a)=>{let d=a===s,f=l===e,C=l==="open"?"Open":"Password";return jsx(Text,{inverse:d,bold:f,...f&&{color:"cyan"},children:f?`[${C}]`:` ${C} `},l)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(q,{value:t,onChange:n,onSubmit:()=>u(false),onCancel:()=>u(false),placeholder:"(required to join)",isActive:i,mask:true}),!i&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),i&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function io({scaleId:e,cards:t,disabledIndices:o,onOverrideChange:n,onClose:r}){let s=useMemo(()=>new Set(o),[o]),[c,i]=useState(0),u=l=>{let a=new Set(s);if(a.has(l))a.delete(l);else {if(a.size>=t.length-1)return;a.add(l);}let d=Array.from(a).toSorted((f,C)=>f-C);n(e,d);};return useInput((l,a)=>{a.leftArrow?i(d=>Math.max(0,d-1)):a.rightArrow?i(d=>Math.min(t.length-1,d+1)):l===" "?u(c):(a.return||a.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((l,a)=>{let d=a===c,f=s.has(a);return jsx(Text,{inverse:d,bold:!f,...!f&&{color:"cyan"},strikethrough:f,dimColor:f,children:l},l)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function en({initialName:e="",initialCards:t=[],onSave:o,onCancel:n}){let r=e.length>0,[s,c]=useState(e),[i,u]=useState(t.length>0?t:[""]),[l,a]=useState(0),[d,f]=useState("editing-name"),[C,A]=useState(""),E=()=>{let p=s.trim();if(p.length===0||p.length>40){A("Name must be 1-40 characters");return}c(p),A(""),f("editing-cards");},R=()=>{let p=s.trim();if(p.length===0||p.length>40){A("Name must be 1-40 characters");return}let m=i.map(w=>w.trim()).filter(w=>w.length>0),y=Array.from(new Set(m));if(y.length<2){A("Need at least 2 unique non-empty cards");return}A(""),o(p,y);};return useInput((p,m)=>{if(d==="editing-cards"){if(m.leftArrow)a(y=>Math.max(0,y-1));else if(m.rightArrow)a(y=>{let w=y+1;return w>=i.length&&i.length<25?(u(D=>[...D,""]),w):Math.min(w,i.length-1)});else if(m.return)R();else if(m.escape)n();else if(m.tab)f("editing-name");else if(m.backspace){let y=i[l]||"";if(y.length===0){if(i.length>2){let w=i.filter((D,g)=>g!==l);u(w),a(Math.max(0,l-1));}}else {let w=[...i];w[l]=y.slice(0,-1),u(w);}}else if(p&&!m.ctrl&&!m.meta){let y=i[l]||"";if(y.length<10){let w=[...i];w[l]=y+p,u(w);}}}},{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(q,{value:s,onChange:c,onSubmit:E,onCancel:n,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:i.map((p,m)=>{let y=m===l;return jsx(Text,{inverse:y,...!y&&{color:"cyan"},children:p.length>0?p:"\xB7"},m)})})]}),C&&jsx(Text,{color:"red",children:C}),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 yt({scales:e,selectedScaleId:t,presetOverrides:o,customScales:n=[],onSelect:r,onOverrideChange:s,onCustomScaleCreate:c,onCustomScaleEdit:i,onCustomScaleDelete:u,onClose:l,showNoneOption:a=false}){let[d,f]=useState(0),[C,A]=useState(null),[E,R]=useState("browsing"),[$,p]=useState(null),[m,y]=useState(null),w=c?[...e,{id:"__create-custom__",cards:[]}]:e,D=w.length;if(useInput((g,O)=>{if(E==="browsing"){if(O.escape){l();return}if(D===0)return;if(O.upArrow)f(b=>(b-1+D)%D);else if(O.downArrow)f(b=>(b+1)%D);else if(O.return){let b=w[d];if(!b)return;if(b.id==="__create-custom__"){R("creating");return}b.id in se?A(C===b.id?null:b.id):r(b.id);}else if(g===" "){let b=w[d];b&&b.id!=="__create-custom__"&&r(b.id);}else if(g==="e"||g==="E"){let b=w[d];i&&b?.id.startsWith("custom-")&&(p(b.id),R("editing"));}else if(g==="d"||g==="D"){let b=w[d];u&&b?.id.startsWith("custom-")&&(y(b.id),R("confirming-delete"));}}else E==="confirming-delete"&&(g==="y"||g==="Y"?(m&&u&&u(m),y(null),R("browsing")):(g==="n"||g==="N"||O.escape)&&(y(null),R("browsing")));},{isActive:E==="browsing"&&C===null||E==="confirming-delete"}),E==="creating")return jsx(en,{onSave:(g,O)=>{c&&c(g,O),R("browsing");},onCancel:()=>R("browsing")});if(E==="editing"&&$){let g=n?.find(b=>b.id===$);if(e.find(b=>b.id===$)&&g)return jsx(en,{initialName:g.label,initialCards:g.cards,onSave:(b,j)=>{i&&i($,b,j),p(null),R("browsing");},onCancel:()=>{p(null),R("browsing");}})}if(E==="confirming-delete"&&m){let g=w.find(b=>b.id===m),O=g?Ie(g.id,n):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",O,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return w.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:w.map((g,O)=>{let b=O===d,j=g.id===t,ae=C===g.id,ne=g.id in se,oe=g.id==="__create-custom__",Y=g.cards.join(", "),v=a&&g.id==="",T=v?"(none)":oe?"[+ Create custom scale]":Ie(g.id,n);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...b&&{color:"cyan"},children:b?">":" "}),jsx(Text,{bold:b,children:T}),!v&&!oe&&jsx(Text,{dimColor:true,children:Y}),j&&jsx(Text,{color:"cyan",children:"[current]"})]}),ae&&!v&&!oe&&jsx(Box,{paddingLeft:2,children:ne?jsx(io,{scaleId:g.id,cards:se[g.id]?.cards??[],disabledIndices:o?.[g.id]??[],onOverrideChange:s,onClose:()=>A(null)}):null})]},g.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let g=d<w.length?w[d]:null;return g?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${i?" [e] edit":""}${u?" [d] delete":""} esc back`:g&&g.id in se?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function Zr(e,t){return t?[...e]:e.filter(o=>o.value==="display-name")}function ao({sessionName:e,displayName:t,currentScale:o,accessMode:n,presetOverrides:r,customScales:s,isHost:c=true,onChangeName:i,onChangeScale:u,onChangeDisplayName:l,onChangeAccess:a,onClose:d}){let[f,C]=useState(r??{}),A=useMemo(()=>lt(f,s),[f,s]),[E,R]=useState("main-menu"),[$,p]=useState(e??""),[m,y]=useState(t),[w,D]=useState(n==="password"?"password":"open"),[g,O]=useState(""),[b,j]=useState(false),ae=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Ie(o.id,s)}]`},{label:"Access",value:"access",detail:`[${n==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],ne=Zr(ae,c);function oe(k){!c&&k!=="display-name"||(k==="room-name"?(p(e??""),R("editing-room-name")):k==="scale"?R("picking-scale"):k==="access"?R("picking-access"):k==="display-name"&&(y(t),R("editing-display-name")));}function Y(k){let B=k.trim()===""?void 0:k.trim();i(B),R("main-menu");}function v(k){let B=k.trim();B.length>0&&(l(B),process.nextTick(()=>J({displayName:B}))),R("main-menu");}function T(k){let B=A.find(z=>z.id===k);B&&u(B),R("main-menu");}function P(k,B){let z={...f};B.length===0?delete z[k]:z[k]=B,C(z),J({presetOverrides:Object.keys(z).length>0?z:void 0});}async function L(k,B){j(true);try{await a(k,B),D(k),O(k==="password"?B??"":"");}catch(z){console.error(`Failed to update access: ${z}`);}finally{j(false),R("main-menu");}}return E==="main-menu"?jsx(pe,{title:"\u2500\u2500 Settings \u2500\u2500",items:ne,onSelect:oe,onClose:d}):E==="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(q,{value:$,onChange:p,onSubmit:Y,onCancel:()=>R("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):E==="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(q,{value:m,onChange:y,onSubmit:v,onCancel:()=>R("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):E==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(yt,{scales:A,selectedScaleId:o.id,presetOverrides:f,onSelect:T,onOverrideChange:P,onClose:()=>R("main-menu")})]}):E==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),b&&jsx(Text,{dimColor:true,children:"Updating access..."}),!b&&jsx(oo,{mode:w,password:g,onModeChange:k=>{k==="open"&&L("open");},onPasswordChange:O,onClose:()=>R("main-menu")})]}):jsx(Box,{})}function bt({participants:e,onlineIds:t,hostId:o,votes:n,revealed:r,participantId:s}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(c=>{let i=t.has(c.id),u=i?"\u25CF":"\u25CB",l=i?"green":"gray",a=c.id===o,d=be(c)==="viewer",f=c.id===s,C=c.id in n,A=d?" (viewer)":r?n[c.id]?` \u2192 ${n[c.id]}`:"":C?" \u2713":" \xB7",E=f&&!d&&!(r&&n[c.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:l,children:u}),jsxs(Text,{children:[c.displayName,a?" (host)":""]}),E?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:d?"gray":C?"green":"gray",children:A})]},c.id)})]})}var es=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function lo({onPick:e,onClose:t}){return jsx(pe,{title:"Host Actions",items:es,onSelect:e,onClose:t})}function Rt({roomCode:e,onPick:t,onClose:o}){let n=[{label:"Copy code",value:"code",detail:gt(e)},{label:"Copy share link",value:"url",detail:ht(e)},{label:"Copy npx command",value:"npx",detail:St(e)}];return jsx(pe,{title:"Share",items:n,onSelect:r=>t(r),onClose:o})}function os(e){let t=e.rounds.filter(n=>W(n)!==null),o=Object.fromEntries(e.participants.map(n=>[n.id,n]));return jn({rounds:t,participants:o})}async function uo(e,t,o){let n=os(e);try{await t(n),o("Results copied to clipboard");}catch{o("Clipboard write failed");}}function po(e,t,o){let n=Pn(e.id,o);return n===null?`Round ${t}`:`Round ${n.depth}/${n.total} [re-vote]`}function fo(e,t,o){let n=po(e,t,o),r=e.title?` \u2014 ${e.title}`:"",s=e.ticketId?` [${e.ticketId}]`:"",c=W(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${n}${r}${s}${c}`}function mo(e){let t=Object.values(e).map(a=>parseFloat(a)).filter(a=>!isNaN(a)).toSorted((a,d)=>a-d);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let n=t.reduce((a,d)=>a+d,0)/t.length,r=Math.floor(t.length/2),s=t.length%2===0?(t[r-1]+t[r])/2:t[r],c=Object.values(e),i=new Map;for(let a of c)i.set(a,(i.get(a)??0)+1);let u=Math.max(...i.values()),l=c.length>0?Math.round(u/c.length*100):0;return {average:n.toFixed(1),median:s.toFixed(1),agreement:`${l}%`}}function nn(e,t){let o=Math.floor((t-e)/1e3),n=Math.floor(o/60),r=o%60;return `${n}:${r.toString().padStart(2,"0")}`}function go(e,t,o=[]){let n=po(e,t,o);if(W(e)==="skipped"){let l=e.title?` ${e.title}`:"",a=e.ticketId?` [${e.ticketId}]`:"";return `${n}:${l}${a} \u2014 Skipped`}let r=new Map;for(let l of Object.values(e.votes))r.set(l,(r.get(l)??0)+1);let s=[...r.entries()].toSorted((l,a)=>a[1]-l[1]||l[0].localeCompare(a[0])).map(([l,a])=>`${l}\xD7${a}`).join(", "),c=e.title?` ${e.title}`:"",i=e.ticketId?` [${e.ticketId}]`:"",u=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${nn(e.timerStartedAt,e.revealedAt)}`:"";return `${n}:${c}${i} \u2014 ${s||"(no votes)"}${u}`}function ho({projection:e,onlineIds:t,isHost:o,participantId:n,rounds:r,currentRound:s,settingsOpen:c,onStartRound:i,onNewRound:u,onRevote:l,onOpenSettings:a,onHandoffHost:d,onEndSession:f,onShare:C,shareOpen:A,onSetShareOpen:E,roomCode:R,confirmingQuit:$,myRole:p,onToggleRole:m,roundTitlePromptActive:y,roundTitleInput:w,onRoundTitleChange:D,onRoundTitleSubmit:g,onRoundTitleCancel:O,roundTicketIdPromptActive:b,roundTicketIdInput:j,onRoundTicketIdChange:ae,onRoundTicketIdSubmit:ne,onRoundTicketIdCancel:oe,descriptorPromptActive:Y,descriptorInput:v,onDescriptorChange:T,onDescriptorSubmit:P,onDescriptorCancel:L,onEditDescriptor:k,canExport:B,onExportResults:z}){let[X,re]=It.useState("idle"),[he,we]=It.useState(null),[ue,ce]=It.useState(false),[ye,ve]=It.useState(false);useEffect(()=>{o||(re("idle"),we(null),ce(false),ve(false));},[o]),useInput(h=>{if(h==="c"||h==="C"){E(true);return}if(h==="w"||h==="W"){m();return}if((h==="x"||h==="X")&&B){z();return}o&&((h==="e"||h==="E")&&a(),(h==="s"||h==="S")&&i(),(h==="h"||h==="H")&&re("picking"),(h==="m"||h==="M")&&ce(true),s!==null&&W(s)!==null&&((h==="n"||h==="N")&&u(),(h==="v"||h==="V")&&W(s)!=="skipped"&&l(),(h==="t"||h==="T")&&k()));},{isActive:!c&&!$&&X==="idle"&&!y&&!b&&!ue&&!ye&&!A&&!Y}),useInput((h,Z)=>{h==="y"||h==="Y"?(f(),ve(false)):(h==="n"||h==="N"||Z.escape)&&ve(false);},{isActive:ye});let de=e.participants.filter(h=>h.id!==n&&t.has(h.id));useInput(h=>{if(X==="picking"){let Z=parseInt(h,10);!isNaN(Z)&&Z>=1&&Z<=de.length?(we(de[Z-1].id),re("confirming")):(h==="Escape"||h==="q"||h==="Q")&&re("idle");}},{isActive:X==="picking"}),useInput(h=>{X==="confirming"&&he&&(h==="y"||h==="Y"?(d(he),re("idle"),we(null)):(h==="n"||h==="N"||h==="Escape")&&(re("idle"),we(null)));},{isActive:X==="confirming"});let Ze=r.length>0,Ue=r.filter(h=>W(h)!==null),et=s!==null?Ue.slice(0,-1):Ue;return ue?jsx(lo,{onPick:h=>{ce(false),h==="end-session"&&ve(true);},onClose:()=>ce(false)}):A?jsx(Rt,{roomCode:R,onPick:h=>{E(false),C(h);},onClose:()=>E(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:Ze?"Session":"Waiting for participants..."}),!Ze&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(bt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:n}),s!==null&&W(s)!==null&&jsx(ss,{projection:e,round:s,rounds:r}),et.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),et.map(h=>{let Z=r.indexOf(h)+1;return jsx(Text,{dimColor:true,children:go(h,Z,r)},h.id)})]}),X==="picking"&&de.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),de.map((h,Z)=>jsxs(Text,{children:["[",Z+1,"] ",h.displayName]},h.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),X==="picking"&&de.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"})]}),X==="confirming"&&he&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(h=>h.id===he)?.displayName,"? [y/n]"]})}),y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(q,{value:w,onChange:D,onSubmit:g,onCancel:O,placeholder:"Enter to skip",isActive:y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),b&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(q,{value:j,onChange:ae,onSubmit:ne,onCancel:oe,placeholder:"e.g. PROJ-1234",isActive:b})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),Y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(q,{value:v,onChange:T,onSubmit:P,onCancel:L,placeholder:"Enter to save",isActive:Y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),ye&&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"})]}),X==="idle"&&!y&&!b&&!Y&&!ye&&jsxs(Box,{gap:2,children:[o?jsx(Fragment,{children:s!==null&&W(s)!==null?jsxs(Fragment,{children:[W(s)!=="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"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",p==="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:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",p==="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"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",p==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function ss({projection:e,round:t,rounds:o}){let n=o.indexOf(t)+1,r=fo(t,n,o);if(W(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let s=mo(t.votes),c=new Map(e.participants.map(l=>[l.id,l.displayName])),i=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?nn(t.timerStartedAt,t.revealedAt):null,u=Object.values(t.votes)[0];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),En(t)&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",u]}),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)})]}),Object.entries(t.votes).map(([l,a])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(c.get(l)??l).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:a.padEnd(10)})]},l)),e.participants.filter(l=>!(l.id in t.votes)).map(l=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:l.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},l.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:s.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:s.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:s.agreement})]}),i!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",i]})]})]})}function wo({scale:e,selected:t,onSelect:o,onClear:n,disabled:r}){let[s,c]=useState(0);return useInput((i,u)=>{if(!r)if(u.leftArrow)c(l=>Math.max(0,l-1));else if(u.rightArrow)c(l=>Math.min(e.cards.length-1,l+1));else if(u.return){let l=e.cards[s];l===t?n():o(l);}else (u.backspace||u.delete)&&n();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((i,u)=>{let l=u===s,a=i===t;return jsx(Text,{inverse:l,bold:a,...a&&{color:"cyan"},children:a?`[${i}]`:` ${i} `},i)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function ls(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function yo({projection:e,round:t,onlineIds:o,isHost:n,myId:r,myRole:s,elapsedMs:c,roomCode:i,shareOpen:u,settingsOpen:l,onVote:a,onClearVote:d,onReveal:f,onSkip:C,onToggleRole:A,onShare:E,onSetShareOpen:R,onOpenSettings:$,confirmingQuit:p}){if(useInput(g=>{if(g==="e"||g==="E"){$();return}if(g==="c"||g==="C"){R(true);return}n&&(g==="r"||g==="R")&&f(),n&&(g==="s"||g==="S")&&C(),(g==="w"||g==="W")&&A();},{isActive:!p&&!l&&!u}),u)return jsx(Rt,{roomCode:i,onPick:g=>{R(false),E(g);},onClose:()=>R(false)});let m=t.votes[r],y=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 ",y,w,D]}),c!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",ls(c)]})]}),jsxs(Box,{gap:4,children:[jsx(bt,{participants:e.participants,onlineIds:o,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),s==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsx(wo,{scale:t.scale,selected:m,onSelect:a,onClear:d,disabled:p})]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),n&&jsx(Text,{color:"yellow",children:"[s] Skip"}),jsxs(Text,{color:"yellow",children:["[w] ",s==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var ms=3e3;function At(e=ms){let[t,o]=useState(null),n=useRef(null),r=useCallback(()=>{n.current!==null&&(clearTimeout(n.current),n.current=null);},[]),s=useCallback(i=>{r(),o(i),n.current=setTimeout(()=>{o(null),n.current=null;},e);},[r,e]),c=useCallback(()=>{r(),o(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:s,dismiss:c}}function Ss(e){let t=ee(e);return !t||W(t)!==null?"lobby":"voting"}function Pt({session:e,participantId:t,displayName:o,accessMode:n,presetOverrides:r,customScales:s}){let{exit:c}=useApp(),[i,u]=useState(e.projection()),[l,a]=useState("connecting"),[d,f]=useState(e.onlineIds()),[C,A]=useState(),[E,R]=useState(false),[$,p]=useState(n==="password"?"password":"open"),[m,y]=useState(o),[w,D]=useState(false),[g,O]=useState(false),[b,j]=useState(""),[ae,ne]=useState(false),[oe,Y]=useState(""),[v,T]=useState(),[P,L]=useState(false),[k,B]=useState(""),[z,X]=useState(null),re=At(3e3),[he,we]=useState(false),ue=At(3e3),ce=At(3e3);useEffect(()=>{let I=e.onChange(()=>{u(e.projection()),f(e.onlineIds());}),_=e.onStatusChange(a),ke=e.onHostChange(tt=>{let zo=e.projection().participants.find(Qo=>Qo.id===tt),Xo=tt===t?"You are now the host":`${zo?.displayName||"Unknown"} is now the host`;re.show(Xo);}),Go=setInterval(()=>{f(e.onlineIds());let tt=e.projection(),nt=ee(tt);nt?.timerStartedAt!==void 0&&nt.revealedAt===void 0?A(Date.now()-nt.timerStartedAt):A(void 0);},1e3);return ()=>{I(),_(),ke(),clearInterval(Go);}},[e,t,re.show]),useInput(I=>{(I==="q"||I==="Q")&&D(true);},{isActive:!E&&!w&&!g&&!ae&&!P&&!he}),useInput((I,_)=>{I==="y"||I==="Y"?(e.disconnect(),c()):(I==="n"||I==="N"||_.escape)&&D(false);},{isActive:w});let ye=Ss(i),ve=ee(i),de=i.settings.hostParticipantId===t,Ze=i.participants.find(I=>I.id===t),Ue=be(Ze??{}),et=useCallback(()=>{j(""),O(true);},[]),h=useCallback(I=>{O(false),j(""),T(Wt(I)),Y(""),ne(true);},[]),Z=useCallback(()=>{O(false),j(""),T(void 0);},[]),Eo=useCallback(I=>{ne(false),Y("");let[_,ke]=Xn(v,I);e.newRound(_,ke),T(void 0);},[e,v]),Ao=useCallback(()=>{ne(false),Y(""),T(void 0);},[]),No=useCallback(()=>{let I=e.current();!I||I.revealedAt===void 0||(X(I.id),B(I.title??""),L(true));},[e]),Po=useCallback(I=>{let _=z;if(L(false),X(null),!_)return;let ke=I.trim();ke!==""&&e.updateRoundDescriptor(_,{title:ke});},[e,z]),Do=useCallback(()=>{L(false),X(null);},[]),ko=useCallback(I=>{e.vote(I);},[e]),Oo=useCallback(()=>{e.unvote();},[e]),Mo=useCallback(()=>{e.reveal();},[e]),$o=useCallback(()=>{e.skip();},[e]),Bo=useCallback(()=>{j(""),O(true);},[]),Ho=useCallback(()=>{e.revote();},[e]),cn=useCallback(()=>{e.toggleRole();},[e]),Uo=useCallback(I=>{e.updateName(I);},[e]),jo=useCallback(I=>{e.updateScale(I);},[e]),Lo=useCallback(I=>{e.updateDisplayName(I),y(I);},[e]),_o=useCallback(async(I,_)=>{await e.updateAccess(I,_),p(I);},[e]),Fo=useCallback(I=>{try{e.handoffHost(I);}catch(_){console.error(`Handoff failed: ${_ instanceof Error?_.message:String(_)}`);}},[e]),dn=useCallback(()=>{R(true);},[]),Vo=useCallback(()=>{R(false);},[]),Yo=useCallback(()=>{e.endSessionForEveryone();},[e]),ln=useCallback(async I=>{let _=I==="code"?gt(e.roomCode):I==="url"?ht(e.roomCode):St(e.roomCode);try{await Co.write(_),ue.show("Copied!");}catch{ue.show(`Copy failed \u2014 ${_}`);}},[e.roomCode,ue]),Ot=i.rounds.filter(I=>W(I)!==null),Jo=Ot.length>0?Ot.at(-1):null,Wo=Ot.length>0,qo=useCallback(()=>uo(i,I=>Co.write(I),ce.show),[i,ce.show]);return jsxs(Box,{flexDirection:"column",children:[jsx(Zn,{roomCode:e.roomCode,sessionName:i.settings.name,status:l,isHost:de}),re.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:re.notice})}),ue.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ue.notice.startsWith("Copy failed")?"red":"green",children:ue.notice})}),ce.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ce.notice.startsWith("Clipboard write failed")?"red":"green",children:ce.notice})}),E?jsx(ao,{sessionName:i.settings.name,displayName:m,currentScale:i.settings.defaultScale,accessMode:$,presetOverrides:r,customScales:s,isHost:de,onChangeName:Uo,onChangeScale:jo,onChangeDisplayName:Lo,onChangeAccess:_o,onClose:Vo}):ye==="lobby"?jsx(ho,{projection:i,onlineIds:d,isHost:de,participantId:t,rounds:i.rounds,currentRound:Jo,settingsOpen:E,onStartRound:et,onNewRound:Bo,roundTitlePromptActive:g,roundTitleInput:b,onRoundTitleChange:j,onRoundTitleSubmit:h,onRoundTitleCancel:Z,roundTicketIdPromptActive:ae,roundTicketIdInput:oe,onRoundTicketIdChange:Y,onRoundTicketIdSubmit:Eo,onRoundTicketIdCancel:Ao,onRevote:Ho,onOpenSettings:dn,onHandoffHost:Fo,onEndSession:Yo,onShare:ln,shareOpen:he,onSetShareOpen:we,roomCode:e.roomCode,confirmingQuit:w,myRole:Ue,onToggleRole:cn,descriptorPromptActive:P,descriptorInput:k,onDescriptorChange:B,onDescriptorSubmit:Po,onDescriptorCancel:Do,onEditDescriptor:No,canExport:Wo,onExportResults:qo}):ye==="voting"&&ve?jsx(yo,{projection:i,round:ve,onlineIds:d,isHost:de,myId:t,myRole:Ue,elapsedMs:C,onVote:ko,onClearVote:Oo,onReveal:Mo,onSkip:$o,onToggleRole:cn,onShare:ln,onSetShareOpen:we,shareOpen:he,settingsOpen:E,onOpenSettings:dn,roomCode:e.roomCode,confirmingQuit:w}):null,w&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function bo({presetOverrides:e,customScales:t}){let{exit:o}=useApp(),[n,r]=useState("main-menu"),[s,c]=useState(Ce()),[i,u]=useState(s.displayName??""),[l,a]=useState(s.relayUrl??""),[d,f]=useState(s.defaultSessionName??""),[C,A]=useState(t??[]),[E,R]=useState(e??{});useInput(v=>{(v==="q"||v==="Q")&&o();},{isActive:n==="main-menu"});let $=useMemo(()=>lt(E,C),[E,C]),p=s.defaultScale,m=p?$.find(v=>v.id===p):void 0,y=[{label:"Display name",value:"display-name",detail:`[${s.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${s.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${m?Ie(m.id,C):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${s.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${s.defaultPassword?"on":"off"}]`}];function w(v){v==="display-name"?(u(s.displayName??""),r("editing-display-name")):v==="relay-url"?(a(s.relayUrl??""),r("editing-relay-url")):v==="default-scale"?r("picking-scale"):v==="default-session-name"?(f(s.defaultSessionName??""),r("editing-session-name")):v==="default-password"&&r("picking-default-password");}function D(v){let T=v.trim();if(T.length>0){let P={...s,displayName:T};c(P),J({displayName:T});}r("main-menu");}function g(v){let T=v.trim();if(T.length>0){let P={...s,relayUrl:T};c(P),J({relayUrl:T});}r("main-menu");}function O(v){let T=v.trim(),P=T.length>0?{...s,defaultSessionName:T}:{...s};T.length===0?(delete P.defaultSessionName,c(P),_e({defaultSessionName:""})):(c(P),J({defaultSessionName:T})),r("main-menu");}function b(v){let T=v.length>0?{...s,defaultScale:v}:{...s};v.length===0?(delete T.defaultScale,c(T),_e({defaultScale:""})):(c(T),J({defaultScale:v})),r("main-menu");}function j(v,T){let P={...E};T.length===0?delete P[v]:P[v]=T,R(P),J({presetOverrides:Object.keys(P).length>0?P:void 0});}function ae(v){let T=v==="on",P={...s,defaultPassword:T};c(P),J({defaultPassword:T}),r("main-menu");}function ne(v,T){let P=`custom-${randomUUID()}`,L=[...C,{id:P,label:v,cards:T}];A(L),c({...s,customScales:L}),J({customScales:L});}function oe(v,T,P){let L=C.map(k=>k.id===v?{id:v,label:T,cards:P}:k);A(L),c({...s,customScales:L}),J({customScales:L});}function Y(v){let T=C.filter(L=>L.id!==v);A(T);let P={...s,customScales:T};s.defaultScale===v?(P.defaultScale="fibonacci",J({customScales:T,defaultScale:"fibonacci"})):J({customScales:T}),c(P);}if(n==="main-menu")return jsx(pe,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:y,onSelect:w,onClose:()=>o()});if(n==="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(q,{value:i,onChange:u,onSubmit:D,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="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(q,{value:l,onChange:a,onSubmit:g,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="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(q,{value:d,onChange:f,onSubmit:O,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="picking-scale"){let v=[{id:"",cards:[]},...$];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(yt,{scales:v,selectedScaleId:p??"",presetOverrides:E,customScales:C,onSelect:b,onOverrideChange:j,onCustomScaleCreate:ne,onCustomScaleEdit:oe,onCustomScaleDelete:Y,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(n==="picking-default-password"){let v=[{label:"On",value:"on",detail:s.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:s.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(pe,{title:"Default password:",items:v,onSelect:ae,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function an(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",o=>{t.close(),e(o);});})}async function Ts(e){let t=await Le(),o=e.scale??t.defaultScale??"fibonacci",n=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,s;r&&(s=await an());let c=dt(o,t.presetOverrides,t.customScales);if(!c){let d=Object.keys(se).join(", ");console.error(`Unknown or fully-disabled scale: "${o}". Builtin IDs: ${d}`),process.exit(1);}let i=await Jn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:n,password:s,defaultScale:c}),u;s&&(u=await Re(s,i.roomUuid)),pt({roomCode:i.roomCode,roomUuid:i.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Room created: ${i.roomCode}`),console.error(`Share: hnch join ${i.roomCode}`),console.error("");let{waitUntilExit:l,unmount:a}=render(It.createElement(Pt,{session:i,participantId:t.participantId,displayName:t.displayName,accessMode:s?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));mt({doc:i.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),a();try{await F();}catch(f){console.error(`Failed to clear cached session: ${f instanceof Error?f.message:String(f)}`);}i.disconnect(),process.exit(0);}}),await l(),i.disconnect(),F(),process.exit(0);}async function Es(e){let t=await Le(),o=qn(e.code);o===null&&(console.error("invalid room code"),process.exit(1));let n;e.password&&(n=await an());let r=await Ye(t.relayUrl,o),s;r.accessMode==="password"&&!e.password?s=await an():e.password&&(s=n);let c,i=false,u=await Wn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:o,password:s,onRejection(d){if(d==="unknown-room"){ft({clearLastSession:F,logger:console,exit:process.exit});return}d==="room-full"&&(i=true,c?.());}}),l;s&&(l=await Re(s,u.roomUuid)),pt({roomCode:u.roomCode,roomUuid:u.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Joined room: ${u.roomCode}`),console.error("");let a=render(It.createElement(Pt,{session:u,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));c=a.unmount,mt({doc:u.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),c?.();try{await F();}catch(f){console.error(`Failed to clear cached session: ${f instanceof Error?f.message:String(f)}`);}u.disconnect(),process.exit(0);}}),await a.waitUntilExit(),i&&(console.error("This room is full (max 20 participants)."),u.disconnect(),F(),process.exit(1)),u.disconnect(),F(),process.exit(0);}async function As(){let e=await Le(),t=zn();t||(console.error("No recent session to resume."),process.exit(0));let o;try{o=await Ye(e.relayUrl,t.roomCode);}catch(a){if((a instanceof Error?a.message:String(a)).includes("Room not found"))return await ft({clearLastSession:F,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}o.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 n=new Oe.Doc,r=new Awareness(n);ct(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let s=false,c=false,i,u=ut({doc:n,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(a){if(a==="unknown-room"){ft({clearLastSession:F,logger:console,exit:process.exit});return}a==="wrong-password"&&(s=true,i?.()),a==="room-full"&&(c=true,i?.());}});pt({roomCode:u.roomCode,roomUuid:u.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let l=render(It.createElement(Pt,{session:u,participantId:e.participantId,displayName:e.displayName,accessMode:o.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));i=l.unmount,mt({doc:u.doc,localParticipantId:e.participantId,onEnded:async a=>{console.error(a.isLocal?"Session ended.":`Session ended by ${a.hostName}.`),i?.();try{await F();}catch(d){console.error(`Failed to clear cached session: ${d instanceof Error?d.message:String(d)}`);}u.disconnect(),process.exit(0);}}),await l.waitUntilExit(),c&&(console.error("This room is full (max 20 participants)."),F(),process.exit(1)),s&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),F(),process.exit(0)),u.disconnect(),F(),process.exit(0);}async function Ns(e){if(!(e.name!==void 0||e.relayUrl!==void 0||e.scale!==void 0||e.sessionName!==void 0||e.password!==void 0)){let n=await Le(),{waitUntilExit:r}=render(It.createElement(bo,{presetOverrides:n.presetOverrides,customScales:n.customScales}));await r(),process.exit(0);}let o={};if(e.name!==void 0&&(o.displayName=e.name),e.relayUrl!==void 0&&(o.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let n=Ce();if(!dt(e.scale,n.presetOverrides,n.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(se).join(", ")}`);return}}o.defaultScale=e.scale;}e.sessionName!==void 0&&(o.defaultSessionName=e.sessionName),e.password!==void 0&&(o.defaultPassword=e.password),_e(o),console.log("Config updated.");}var To=bs(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=>{Ts(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=>{Es(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{As().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=>{Ns(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).demandCommand(1,"Specify a command: create, join, resume, or config").strict().help(),sn=hideBin(process.argv);(sn.length===0||sn.length===1&&sn[0]==="--")&&(To.showHelp(),process.exit(0));To.parse();
|
|
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();
|