@xauyxau/hnch 1.3.0 → 1.5.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 +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf-8");}async function
|
|
4
|
-
`,"utf-8");}var Sn={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},Jt=new Map(Object.entries(Sn).map(([e,t])=>[t,e]));function ue(e){return e.role??"voter"}var $e={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},Wt={id:"t-shirt",cards:["XS","S","M","L","XL"]},qt={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},Gt={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},zt={id:"risk",cards:["Low","Medium","High","Critical"]},X={[$e.id]:$e,[Wt.id]:Wt,[qt.id]:qt,[Gt.id]:Gt,[zt.id]:zt},Qt={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function pe(e){return e in Qt?Qt[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 xn="meta",Ae="settings",yn="participants",wn="rounds",vn=["roomUuid","createdAt","createdBy","sessionEndedAt"],Cn=["name","defaultScale","hostParticipantId"],bn=["displayName","joinedAt","role","leftAt","removedBy"],Rn=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","createdBy","createdAt"];function je(e){return e.getMap(xn)}function Le(e){return e.getMap(Ae)}function _e(e){return e.getMap(yn)}function St(e){return e.getArray(wn)}function Fe(e,t){let o={};for(let n of t){let r=e.get(n);r!==void 0&&(o[n]=r);}return o}function In(e){return Fe(je(e),vn)}function Tn(e){return Fe(Le(e),Cn)}function En(e){let t=_e(e),o=[];return t.forEach((n,r)=>{let s=Fe(n,bn);o.push({id:r,...s});}),o.sort((n,r)=>n.joinedAt-r.joinedAt||n.id.localeCompare(r.id)),o}function An(e){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}function Nn(e){let t=Fe(e,Rn),o=e.get("votes"),n=o?An(o):{};return {...t,votes:n}}function Pn(e){let t=St(e),o=[];return t.forEach(n=>{o.push(Nn(n));}),o}function Q(e){return {meta:In(e),settings:Tn(e),participants:En(e),rounds:Pn(e)}}function Kt(e,t){if(je(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let o=je(e);o.set("roomUuid",t.roomUuid),o.set("createdAt",t.createdAt),o.set("createdBy",t.participantId);let n=Le(e);t.sessionName!==void 0&&n.set("name",t.sessionName),n.set("defaultScale",t.defaultScale),n.set("hostParticipantId",t.participantId);let r=new we.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),_e(e).set(t.participantId,r);});}function Ve(e,t){e.transact(()=>{let o=_e(e),n=o.get(t.participantId),r=n??new we.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 ve(e,t){e.transact(()=>{let o=Le(e);for(let[n,r]of Object.entries(t))r===void 0?o.delete(n):o.set(n,r);});}function xt(e,t,o){e.transact(()=>{let n=_e(e),r=n.get(t),s=r??new we.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 yt(e,t){let o=t.scale??Le(e).get("defaultScale");if(!o)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let n=new we.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 we.Map),St(e).push([n]);}),t.id}function wt(e,t){let o=St(e);for(let n=0;n<o.length;n+=1){let r=o.get(n);if(r.get("id")===t)return r}}function Xt(e,t,o,n){let r=wt(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 Zt(e,t,o){let n=wt(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 vt(e,t,o){let n=wt(e,t);if(!n)throw new Error(`revealRound: round ${t} not found`);e.transact(()=>{n.set("revealedAt",o);});}function eo(e){e.transact(()=>{je(e).set("sessionEndedAt",Date.now());});}function Z(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[t.length-1]}function to(e){let t=Object.values(e.votes);return t.length<2?false:t.every(o=>o===t[0])}var oo="PBKDF2",On="SHA-256",no=new TextEncoder;function Mn(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function me(e,t){let o=await crypto.subtle.importKey("raw",no.encode(e),oo,false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:oo,salt:no.encode(t),iterations:1e5,hash:On},o,256);return Mn(n)}var ro="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(ro.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${ro.length}`);function Ct(e){return e.trim().replace(/-/g,"").toUpperCase()}function so(e,t=true){let o=Ct(e);return !t||o.length!==6?o:`${o.slice(0,3)}-${o.slice(3)}`}function Ye(e,t,o){if(e.startsWith("custom-")){let r=(o??[]).find(s=>s.id===e);return r?{id:r.id,cards:r.cards}:void 0}let n=X[e];if(n){let r=(t??{})[e]??[];if(r.length===0)return n;let s=n.cards.filter((p,a)=>!r.includes(a));return s.length===0?void 0:{id:e,cards:s}}}function Je(e,t){let o=Object.keys(X).map(r=>Ye(r,e,t)).filter(r=>r!==void 0),n=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...o,...n]}async function io(e,t){let o=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!o.ok)throw new Error(`POST /rooms failed: ${o.status}`);return await o.json()}async function Ne(e,t){let o=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(o.status===404){let n=await o.json().catch(()=>null);throw new Error(`Room not found: ${n?.reason??"unknown-room"}`)}if(!o.ok)throw new Error(`GET /rooms/:code failed: ${o.status}`);return await o.json()}async function bt(e,t,o){let n=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:o})});if(!n.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${n.status}`)}function ao(e){let o=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,n={did:e.deviceId};e.passwordHash!==void 0&&(n.pw=e.passwordHash);let r=new WebsocketProvider(o,e.roomUuid,e.doc,{params:n,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:kn}),s=l=>{e.onStatusChange?.(l.status);},p=l=>{if(l===null)return;let i=Jt.get(l.code);i!==void 0&&(e.onRejection?.(i),r.shouldConnect=false,r.disconnect());};r.on("status",s),r.on("connection-close",p);let a=false,d=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(l){if(l.passwordHash===d)return;d=l.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let c={did:r.params.did??""};d!==void 0&&(c.pw=d),r.params=c,r.connect();},disconnect(){a||(a=true,r.off("status",s),r.off("connection-close",p),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Hn=5e3;function co(e,t,o){let n=null,r=null;function s(){let i=new Set;return t.getStates().forEach(c=>{let h=c.participantId;typeof h=="string"&&i.add(h);}),i}function p(){return e.getMap(Ae).get("hostParticipantId")}function a(){r!==null&&(clearTimeout(r),r=null),n=null;}function d(){let i=p(),c=n;if(n=null,!c||i!==c)return;let h=s();if(h.has(i))return;let A=[...h].sort();if(A.length===0)return;let O=A[0];O===o&&ve(e,{hostParticipantId:O});}function l(){let i=p();if(!i)return;if(s().has(i)){a();return}n!==i&&(a(),n=i,r=setTimeout(()=>{r=null,d();},Hn));}return t.on("change",l),e.getMap(Ae).observe(l),l(),{stop(){a(),t.off("change",l),e.getMap(Ae).unobserve(l);}}}async function po(e){let t,o=await io(e.relayUrl);e.password&&(t=await me(e.password,o.uuid),await bt(e.relayUrl,o.uuid,t));let n=new we.Doc,r=new Awareness(n),s=Date.now();return Kt(n,{roomUuid:o.uuid,createdAt:s,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??$e,sessionName:e.sessionName}),r.setLocalStateField("participantId",e.participantId),We({doc:n,awareness:r,roomCode:o.code,roomUuid:o.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function mo(e){let t=await Ne(e.relayUrl,e.roomCode),o;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");o=await me(e.password,t.uuid);}let n=new we.Doc,r=new Awareness(n);return Ve(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),We({doc:n,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:o,onRejection:e.onRejection})}function We(e){let{doc:t,awareness:o,participantId:n,relayUrl:r,roomUuid:s}=e,p=new Set,a=new Set,d=new Set,l=ao({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:n,passwordHash:e.passwordHash,awareness:o,onStatusChange(u){p.forEach(g=>g(u));},onRejection(u){console.error(`Connection rejected: ${u}`),e.onRejection?.(u);}}),i=co(t,o,n),c=()=>{a.forEach(u=>u());};t.getMap("meta").observeDeep(c),t.getMap("settings").observeDeep(c),t.getMap("participants").observeDeep(c),t.getArray("rounds").observeDeep(c);function h(){let u=new Set;return o.getStates().forEach(g=>{let w=g.participantId;typeof w=="string"&&u.add(w);}),u}let A=new Set,O=setInterval(()=>{let u=Q(t),g=Z(u);if(!g||g.revealedAt!==void 0||A.has(g.id))return;let w=h();if(w.size===0)return;let x=u.participants.filter(f=>w.has(f.id)&&ue(f)==="voter");if(x.length===0)return;x.filter(f=>f.id in g.votes).length>=x.length&&(A.add(g.id),vt(t,g.id,Date.now()));},250),R=t.getMap("settings").get("hostParticipantId"),I=()=>{let u=t.getMap("settings").get("hostParticipantId");u!==R&&u!==void 0&&d.forEach(g=>g(u)),R=u;};t.getMap("settings").observe(I);let k=false;return {doc:t,awareness:o,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return Q(t)},current(){return Z(Q(t))},isHost(){return Q(t).settings.hostParticipantId===n},onlineIds:h,vote(u){let g=Z(Q(t));g&&Xt(t,g.id,n,u);},unvote(){let u=Z(Q(t));u&&Zt(t,u.id,n);},reveal(){let u=Z(Q(t));u&&vt(t,u.id,Date.now());},newRound(u){let g=randomUUID();return yt(t,{id:g,createdAt:Date.now(),createdBy:n,title:u}),g},revote(){let u=Z(Q(t)),g=randomUUID();return yt(t,{id:g,createdAt:Date.now(),createdBy:n,parentRoundId:u?.id,title:u?.title,description:u?.description,ticketId:u?.ticketId}),g},updateName(u){ve(t,{name:u});},updateScale(u){ve(t,{defaultScale:u});},updateDisplayName(u){let x=Q(t).participants.find(T=>T.id===n)?.joinedAt??Date.now();xt(t,n,{displayName:u,joinedAt:x});},async updateAccess(u,g){let w=null;if(u==="password"){if(!g)throw new Error("Password required for password mode");w=await me(g,s);}await bt(r,s,w),l.updateCredentials({passwordHash:w});},handoffHost(u){if(!this.isHost())throw new Error("Only the current host can hand off");if(!h().has(u))throw new Error("Target participant is not online");if(!Q(t).participants.some(T=>T.id===u))throw new Error("Target participant does not exist");ve(t,{hostParticipantId:u});},toggleRole(){let g=Q(t).participants.find(f=>f.id===n),x=ue(g??{})==="viewer"?"voter":"viewer",T=g?.joinedAt??Date.now();xt(t,n,{displayName:g?.displayName??"",joinedAt:T,role:x});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");eo(t);},onChange(u){return a.add(u),()=>a.delete(u)},onStatusChange(u){return p.add(u),()=>p.delete(u)},onHostChange(u){return d.add(u),()=>d.delete(u)},disconnect(){k||(k=true,clearInterval(O),i.stop(),t.getMap("meta").unobserveDeep(c),t.getMap("settings").unobserveDeep(c),t.getMap("settings").unobserve(I),t.getMap("participants").unobserveDeep(c),t.getArray("rounds").unobserveDeep(c),l.disconnect());}}}function fo(e){let t=Ct(e);return t===""?null:t}var Fn=1440*60*1e3;function It(){return join(Ie(),"last-session.json")}function Vn(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 ho(){let e=It();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !Vn(t)||Date.now()-t.lastSeenAt>Fn?(j(),null):t}catch{return j(),null}}function qe(e){let t=Ie();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let o=It();writeFileSync(o,JSON.stringify(e,null,2)+`
|
|
5
|
-
`,{encoding:"utf-8",mode:384}),chmodSync(o,384);}function j(){let e=It();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function Ge(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 ze(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 p=t.get("createdBy"),a=p===e.localParticipantId,d=e.doc.getMap("participants"),l=e.doc.getMap("settings").get("hostParticipantId")??p,i="host";if(l){let h=d.get(l)?.get("displayName");typeof h=="string"&&h.length>0&&(i=h);}setImmediate(()=>{n||e.onEnded({isLocal:a,hostName:i,timestamp:s});});}return t.observe(r),r(),()=>{n=true,t.unobserve(r);}}var Yn="@xauyxau/hnch";function Qe(e){return so(e)}function Ke(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function Xe(e){return `npx ${Yn} join ${e}`}var Jn={connecting:"yellow",connected:"green",disconnected:"red"};function yo({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:Jn[o],children:o})]})]})}function ne({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(a=>!a.disabled),[s,p]=useState(r>=0?r:0);return useInput((a,d)=>{if(d.upArrow)p(l=>{let i=(l-1+e.length)%e.length,c=0;for(;e[i]?.disabled&&c<e.length;)i=(i-1+e.length)%e.length,c++;return i});else if(d.downArrow)p(l=>{let i=(l+1)%e.length,c=0;for(;e[i]?.disabled&&c<e.length;)i=(i+1)%e.length,c++;return i});else if(d.return){let l=e[s];l&&!l.disabled&&t(l.value);}else d.escape&&o?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Box,{flexDirection:"column",children:e.map((a,d)=>{let l=d===s,i=a.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{color:l?"cyan":void 0,dimColor:i,children:l?">":" "}),jsx(Text,{bold:l,dimColor:i,children:a.label}),a.detail&&jsx(Text,{dimColor:true,children:a.detail})]},a.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function W({value:e,onChange:t,onSubmit:o,onCancel:n,placeholder:r,isActive:s=true,mask:p=false}){useInput((i,c)=>{c.escape?n?.():c.return?o(e):c.backspace||c.delete?t(e.slice(0,-1)):i&&!c.ctrl&&!c.meta&&t(e+i);},{isActive:s});let a=p&&e.length>0?"*".repeat(e.length):e,d=a.length>0?a:r??"",l=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:l,children:d}),jsx(Text,{inverse:true,children:" "})]})}function bo({mode:e,password:t,onModeChange:o,onPasswordChange:n,onClose:r}){let[s,p]=useState(e==="open"?0:1),[a,d]=useState(false);return useEffect(()=>{p(e==="open"?0:1);},[e]),useInput((l,i)=>{if(i.leftArrow)p(c=>Math.max(0,c-1));else if(i.rightArrow)p(c=>Math.min(1,c+1));else if(i.return){let c=s===0?"open":"password";c!==e&&o(c),c==="password"&&d(true);}else i.escape&&r?.();},{isActive:!a}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((l,i)=>{let c=i===s,h=l===e,A=l==="open"?"Open":"Password";return jsx(Text,{inverse:c,bold:h,color:h?"cyan":void 0,children:h?`[${A}]`:` ${A} `},l)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(W,{value:t,onChange:n,onSubmit:()=>d(false),onCancel:()=>d(false),placeholder:"(required to join)",isActive:a,mask:true}),!a&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),a&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function To({scaleId:e,cards:t,disabledIndices:o,onOverrideChange:n,onClose:r}){let s=useMemo(()=>new Set(o),[o]),[p,a]=useState(0),d=l=>{let i=new Set(s);if(i.has(l))i.delete(l);else {if(i.size>=t.length-1)return;i.add(l);}let c=Array.from(i).sort((h,A)=>h-A);n(e,c);};return useInput((l,i)=>{i.leftArrow?a(c=>Math.max(0,c-1)):i.rightArrow?a(c=>Math.min(t.length-1,c+1)):l===" "?d(p):(i.return||i.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((l,i)=>{let c=i===p,h=s.has(i);return jsx(Text,{inverse:c,bold:!h,color:h?void 0:"cyan",strikethrough:h,dimColor:h,children:l},l)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function Dt({initialName:e="",initialCards:t=[],onSave:o,onCancel:n}){let r=e.length>0,[s,p]=useState(e),[a,d]=useState(t.length>0?t:[""]),[l,i]=useState(0),[c,h]=useState("editing-name"),[A,O]=useState(""),R=()=>{let u=s.trim();if(u.length<1||u.length>40){O("Name must be 1-40 characters");return}p(u),O(""),h("editing-cards");},I=()=>{let u=s.trim();if(u.length<1||u.length>40){O("Name must be 1-40 characters");return}let g=a.map(x=>x.trim()).filter(x=>x.length>0),w=Array.from(new Set(g));if(w.length<2){O("Need at least 2 unique non-empty cards");return}O(""),o(u,w);};return useInput((u,g)=>{if(c==="editing-cards"){if(g.leftArrow)i(w=>Math.max(0,w-1));else if(g.rightArrow)i(w=>{let x=w+1;return x>=a.length&&a.length<25?(d(T=>[...T,""]),x):Math.min(x,a.length-1)});else if(g.return)I();else if(g.escape)n();else if(g.tab)h("editing-name");else if(g.backspace){let w=a[l]||"";if(w.length===0){if(a.length>2){let x=a.filter((T,f)=>f!==l);d(x),i(Math.max(0,l-1));}}else {let x=[...a];x[l]=w.slice(0,-1),d(x);}}else if(u&&!g.ctrl&&!g.meta){let w=a[l]||"";if(w.length<10){let x=[...a];x[l]=w+u,d(x);}}}},{isActive:c==="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(W,{value:s,onChange:p,onSubmit:R,onCancel:n,placeholder:"Scale name",isActive:c==="editing-name"})]}),c==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:a.map((u,g)=>{let w=g===l;return jsx(Text,{inverse:w,color:w?void 0:"cyan",children:u.length>0?u:"\xB7"},g)})})]}),A&&jsx(Text,{color:"red",children:A}),jsx(Text,{dimColor:true,children:c==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function tt({scales:e,selectedScaleId:t,presetOverrides:o,customScales:n=[],onSelect:r,onOverrideChange:s,onCustomScaleCreate:p,onCustomScaleEdit:a,onCustomScaleDelete:d,onClose:l,showNoneOption:i=false}){let[c,h]=useState(0),[A,O]=useState(null),[R,I]=useState("browsing"),[k,u]=useState(null),[g,w]=useState(null),x=p?[...e,{id:"__create-custom__",cards:[]}]:e,T=x.length;if(useInput((f,P)=>{if(R==="browsing"){if(P.escape){l();return}if(T===0)return;if(P.upArrow)h(y=>(y-1+T)%T);else if(P.downArrow)h(y=>(y+1)%T);else if(P.return){let y=x[c];if(!y)return;if(y.id==="__create-custom__"){I("creating");return}y.id in X?O(A===y.id?null:y.id):r(y.id);}else if(f===" "){let y=x[c];y&&y.id!=="__create-custom__"&&r(y.id);}else if(f==="e"||f==="E"){let y=x[c];a&&y?.id.startsWith("custom-")&&(u(y.id),I("editing"));}else if(f==="d"||f==="D"){let y=x[c];d&&y?.id.startsWith("custom-")&&(w(y.id),I("confirming-delete"));}}else R==="confirming-delete"&&(f==="y"||f==="Y"?(g&&d&&d(g),w(null),I("browsing")):(f==="n"||f==="N"||P.escape)&&(w(null),I("browsing")));},{isActive:R==="browsing"&&A===null||R==="confirming-delete"}),R==="creating")return jsx(Dt,{onSave:(f,P)=>{p&&p(f,P),I("browsing");},onCancel:()=>I("browsing")});if(R==="editing"&&k){let f=n?.find(y=>y.id===k);if(e.find(y=>y.id===k)&&f)return jsx(Dt,{initialName:f.label,initialCards:f.cards,onSave:(y,H)=>{a&&a(k,y,H),u(null),I("browsing");},onCancel:()=>{u(null),I("browsing");}})}if(R==="confirming-delete"&&g){let f=x.find(y=>y.id===g),P=f?pe(f.id):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",P,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return x.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:x.map((f,P)=>{let y=P===c,H=f.id===t,J=A===f.id,Y=f.id in X;f.id.startsWith("custom-");let B=f.id==="__create-custom__",S=f.cards.join(", "),v=i&&f.id==="",E=v?"(none)":B?"[+ Create custom scale]":pe(f.id);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{color:y?"cyan":void 0,children:y?">":" "}),jsx(Text,{bold:y,children:E}),!v&&!B&&jsx(Text,{dimColor:true,children:S}),H&&jsx(Text,{color:"cyan",children:"[current]"})]}),J&&!v&&!B&&jsx(Box,{paddingLeft:2,children:Y?jsx(To,{scaleId:f.id,cards:X[f.id]?.cards??[],disabledIndices:o?.[f.id]??[],onOverrideChange:s,onClose:()=>O(null)}):null})]},f.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let f=c<x.length?x[c]:null;return f?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${a?" [e] edit":""}${d?" [d] delete":""} esc back`:f&&f.id in X?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function sr(e,t){return t?[...e]:e.filter(o=>o.value==="display-name")}function Eo({sessionName:e,displayName:t,currentScale:o,accessMode:n,presetOverrides:r,customScales:s,isHost:p=true,onChangeName:a,onChangeScale:d,onChangeDisplayName:l,onChangeAccess:i,onClose:c}){let[h,A]=useState(r??{}),O=useMemo(()=>Je(h,s),[h,s]),[R,I]=useState("main-menu"),[k,u]=useState(e??""),[g,w]=useState(t),[x,T]=useState(n==="password"?"password":"open"),[f,P]=useState(""),[y,H]=useState(false),J=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${pe(o.id)}]`},{label:"Access",value:"access",detail:`[${n==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],Y=sr(J,p);function G(m){!p&&m!=="display-name"||(m==="room-name"?(u(e??""),I("editing-room-name")):m==="scale"?I("picking-scale"):m==="access"?I("picking-access"):m==="display-name"&&(w(t),I("editing-display-name")));}function B(m){let M=m.trim()===""?void 0:m.trim();a(M),I("main-menu");}function S(m){let M=m.trim();M.length>0&&(l(M),process.nextTick(()=>_({displayName:M}))),I("main-menu");}function v(m){let M=O.find(K=>K.id===m);M&&d(M),I("main-menu");}function E(m,M){let K={...h};M.length===0?delete K[m]:K[m]=M,A(K),_({presetOverrides:Object.keys(K).length>0?K:void 0});}async function L(m,M){H(true);try{await i(m,M),T(m),P(m==="password"?M??"":"");}catch(K){console.error(`Failed to update access: ${K}`);}finally{H(false),I("main-menu");}}return R==="main-menu"?jsx(ne,{title:"\u2500\u2500 Settings \u2500\u2500",items:Y,onSelect:G,onClose:c}):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(W,{value:k,onChange:u,onSubmit:B,onCancel:()=>I("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(W,{value:g,onChange:w,onSubmit:S,onCancel:()=>I("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(tt,{scales:O,selectedScaleId:o.id,presetOverrides:h,onSelect:v,onOverrideChange:E,onClose:()=>I("main-menu")})]}):R==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),y&&jsx(Text,{dimColor:true,children:"Updating access..."}),!y&&jsx(bo,{mode:x,password:f,onModeChange:m=>{m==="open"&&L("open");},onPasswordChange:P,onClose:()=>I("main-menu")})]}):jsx(Box,{})}function st({participants:e,onlineIds:t,hostId:o,votes:n,revealed:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(s=>{let p=t.has(s.id),a=p?"\u25CF":"\u25CB",d=p?"green":"gray",l=s.id===o,i=ue(s)==="viewer",c=s.id in n,h=i?" (viewer)":r?n[s.id]?` \u2192 ${n[s.id]}`:"":c?" \u2713":" \xB7";return jsxs(Box,{gap:1,children:[jsx(Text,{color:d,children:a}),jsxs(Text,{children:[s.displayName,l?" (host)":""]}),jsx(Text,{color:i?"gray":c?"green":"gray",children:h})]},s.id)})]})}var ir=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function Po({onPick:e,onClose:t}){return jsx(ne,{title:"Host Actions",items:ir,onSelect:e,onClose:t})}function it({roomCode:e,onPick:t,onClose:o}){let n=[{label:"Copy code",value:"code",detail:Qe(e)},{label:"Copy share link",value:"url",detail:Ke(e)},{label:"Copy npx command",value:"npx",detail:Xe(e)}];return jsx(ne,{title:"Share",items:n,onSelect:r=>t(r),onClose:o})}function dr(e){let t=Object.values(e).map(i=>parseFloat(i)).filter(i=>!isNaN(i)).sort((i,c)=>i-c);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let n=t.reduce((i,c)=>i+c,0)/t.length,r=Math.floor(t.length/2),s=t.length%2===0?(t[r-1]+t[r])/2:t[r],p=Object.values(e),a=new Map;for(let i of p)a.set(i,(a.get(i)??0)+1);let d=Math.max(...a.values()),l=p.length>0?Math.round(d/p.length*100):0;return {average:n.toFixed(1),median:s.toFixed(1),agreement:`${l}%`}}function Oo(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 ur(e,t){let o=new Map;for(let a of Object.values(e.votes))o.set(a,(o.get(a)??0)+1);let n=[...o.entries()].sort((a,d)=>d[1]-a[1]||a[0].localeCompare(d[0])).map(([a,d])=>`${a}\xD7${d}`).join(", "),r=e.title?` ${e.title}`:"",s=e.ticketId?` [${e.ticketId}]`:"",p=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${Oo(e.timerStartedAt,e.revealedAt)}`:"";return `Round ${t}:${r}${s} \u2014 ${n||"(no votes)"}${p}`}function Mo({projection:e,onlineIds:t,isHost:o,participantId:n,rounds:r,currentRound:s,settingsOpen:p,onStartRound:a,onNewRound:d,onRevote:l,onOpenSettings:i,onHandoffHost:c,onEndSession:h,onShare:A,shareOpen:O,onSetShareOpen:R,roomCode:I,confirmingQuit:k,roundTitlePromptActive:u,roundTitleInput:g,onRoundTitleChange:w,onRoundTitleSubmit:x,onRoundTitleCancel:T}){let[f,P]=at.useState("idle"),[y,H]=at.useState(null),[J,Y]=at.useState(false),[G,B]=at.useState(false);useEffect(()=>{o||(P("idle"),H(null),Y(false),B(false));},[o]),useInput(m=>{if(m==="c"||m==="C"){R(true);return}o&&((m==="e"||m==="E")&&i(),(m==="s"||m==="S")&&a(),(m==="h"||m==="H")&&P("picking"),(m==="m"||m==="M")&&Y(true),s?.revealedAt!==void 0&&((m==="n"||m==="N")&&d(),(m==="v"||m==="V")&&l()));},{isActive:!p&&!k&&f==="idle"&&!u&&!J&&!G&&!O}),useInput((m,M)=>{m==="y"||m==="Y"?(h(),B(false)):(m==="n"||m==="N"||M.escape)&&B(false);},{isActive:G});let S=e.participants.filter(m=>m.id!==n&&t.has(m.id));useInput(m=>{if(f==="picking"){let M=parseInt(m,10);!isNaN(M)&&M>=1&&M<=S.length?(H(S[M-1].id),P("confirming")):(m==="Escape"||m==="q"||m==="Q")&&P("idle");}},{isActive:f==="picking"}),useInput(m=>{f==="confirming"&&y&&(m==="y"||m==="Y"?(c(y),P("idle"),H(null)):(m==="n"||m==="N"||m==="Escape")&&(P("idle"),H(null)));},{isActive:f==="confirming"});let v=r.length>0,E=r.filter(m=>m.revealedAt!==void 0),L=s!==null?E.slice(0,-1):E;return J?jsx(Po,{onPick:m=>{Y(false),m==="end-session"&&B(true);},onClose:()=>Y(false)}):O?jsx(it,{roomCode:I,onPick:m=>{R(false),A(m);},onClose:()=>R(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:v?"Session":"Waiting for participants..."}),!v&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(st,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false}),s?.revealedAt!==void 0&&jsx(pr,{projection:e,round:s,rounds:r}),L.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),L.map(m=>{let M=r.indexOf(m)+1;return jsx(Text,{dimColor:true,children:ur(m,M)},m.id)})]}),f==="picking"&&S.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),S.map((m,M)=>jsxs(Text,{children:["[",M+1,"] ",m.displayName]},m.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),f==="picking"&&S.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"})]}),f==="confirming"&&y&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(m=>m.id===y)?.displayName,"? [y/n]"]})}),u&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(W,{value:g,onChange:w,onSubmit:x,onCancel:T,placeholder:"Enter to skip",isActive:u})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),G&&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"})]}),f==="idle"&&!u&&!G&&jsxs(Box,{gap:2,children:[o?jsx(Fragment,{children:s?.revealedAt!==void 0?jsxs(Fragment,{children:[jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),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"}),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"})]}),jsx(Text,{children:"[q] Quit"})]})]})}function pr({projection:e,round:t,rounds:o}){let n=o.indexOf(t)+1,r=t.title?` \u2014 ${t.title}`:"",s=t.ticketId?` [${t.ticketId}]`:"",p=dr(t.votes),a=new Map(e.participants.map(i=>[i.id,i.displayName])),d=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?Oo(t.timerStartedAt,t.revealedAt):null,l=Object.values(t.votes)[0];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{bold:true,children:["Round ",n,r,s," \u2014 Results"]}),to(t)&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",l]}),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(([i,c])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(a.get(i)??i).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:c.padEnd(10)})]},i)),e.participants.filter(i=>!(i.id in t.votes)).map(i=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:i.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},i.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:p.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:p.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:p.agreement})]}),d!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",d]})]})]})}function Ho({scale:e,selected:t,onSelect:o,onClear:n,disabled:r}){let[s,p]=useState(0);return useInput((a,d)=>{if(!r)if(d.leftArrow)p(l=>Math.max(0,l-1));else if(d.rightArrow)p(l=>Math.min(e.cards.length-1,l+1));else if(d.return){let l=e.cards[s];l===t?n():o(l);}else (d.backspace||d.delete)&&n();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((a,d)=>{let l=d===s,i=a===t;return jsx(Text,{inverse:l,bold:i,color:i?"cyan":void 0,children:i?`[${a}]`:` ${a} `},a)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function Sr(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function Bo({projection:e,round:t,onlineIds:o,isHost:n,myId:r,myRole:s,elapsedMs:p,roomCode:a,shareOpen:d,settingsOpen:l,onVote:i,onClearVote:c,onReveal:h,onToggleRole:A,onShare:O,onSetShareOpen:R,onOpenSettings:I,confirmingQuit:k}){if(useInput(T=>{if(T==="e"||T==="E"){I();return}if(T==="c"||T==="C"){R(true);return}n&&(T==="r"||T==="R")&&h(),(T==="w"||T==="W")&&A();},{isActive:!k&&!l&&!d}),d)return jsx(it,{roomCode:a,onPick:T=>{R(false),O(T);},onClose:()=>R(false)});let u=t.votes[r],g=e.rounds.indexOf(t)+1,w=t.title?` \u2014 ${t.title}`:"",x=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",g,w,x]}),p!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",Sr(p)]})]}),jsxs(Box,{gap:4,children:[jsx(st,{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(Ho,{scale:t.scale,selected:u,onSelect:i,onClear:c,disabled:k})]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),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 vr=3e3;function Bt(e=vr){let[t,o]=useState(null),n=useRef(null),r=useCallback(()=>{n.current!==null&&(clearTimeout(n.current),n.current=null);},[]),s=useCallback(a=>{r(),o(a),n.current=setTimeout(()=>{o(null),n.current=null;},e);},[r,e]),p=useCallback(()=>{r(),o(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:s,dismiss:p}}function Ir(e){let t=Z(e);return !t||t.revealedAt!==void 0?"lobby":"voting"}function ut({session:e,participantId:t,displayName:o,accessMode:n,presetOverrides:r,customScales:s}){let{exit:p}=useApp(),[a,d]=useState(e.projection()),[l,i]=useState("connecting"),[c,h]=useState(e.onlineIds()),[A,O]=useState(void 0),[R,I]=useState(false),[k,u]=useState(n==="password"?"password":"open"),[g,w]=useState(o),[x,T]=useState(false),[f,P]=useState(false),[y,H]=useState(""),J=Bt(3e3),[Y,G]=useState(false),B=Bt(3e3);useEffect(()=>{let N=e.onChange(()=>{d(e.projection()),h(e.onlineIds());}),z=e.onStatusChange(i),nn=e.onHostChange(Be=>{let sn=e.projection().participants.find(cn=>cn.id===Be),an=Be===t?"You are now the host":`${sn?.displayName||"Unknown"} is now the host`;J.show(an);}),rn=setInterval(()=>{h(e.onlineIds());let Be=e.projection(),Ue=Z(Be);Ue?.timerStartedAt!==void 0&&Ue.revealedAt===void 0?O(Date.now()-Ue.timerStartedAt):O(void 0);},1e3);return ()=>{N(),z(),nn(),clearInterval(rn);}},[e,t,J.show]),useInput(N=>{(N==="q"||N==="Q")&&T(true);},{isActive:!R&&!x&&!f&&!Y}),useInput((N,z)=>{N==="y"||N==="Y"?(e.disconnect(),p()):(N==="n"||N==="N"||z.escape)&&T(false);},{isActive:x});let S=Ir(a),v=Z(a),E=a.settings.hostParticipantId===t,L=a.participants.find(N=>N.id===t),m=ue(L??{}),M=useCallback(()=>{H(""),P(true);},[]),K=useCallback(N=>{P(false),H(""),e.newRound(N.trim()||void 0);},[e]),Fo=useCallback(()=>{P(false),H("");},[]),Vo=useCallback(N=>{e.vote(N);},[e]),Yo=useCallback(()=>{e.unvote();},[e]),Jo=useCallback(()=>{e.reveal();},[e]),Wo=useCallback(()=>{H(""),P(true);},[]),qo=useCallback(()=>{e.revote();},[e]),Go=useCallback(()=>{e.toggleRole();},[e]),zo=useCallback(N=>{e.updateName(N);},[e]),Qo=useCallback(N=>{e.updateScale(N);},[e]),Ko=useCallback(N=>{e.updateDisplayName(N),w(N);},[e]),Xo=useCallback(async(N,z)=>{await e.updateAccess(N,z),u(N);},[e]),Zo=useCallback(N=>{try{e.handoffHost(N);}catch(z){console.error(`Handoff failed: ${z instanceof Error?z.message:String(z)}`);}},[e]),Lt=useCallback(()=>{I(true);},[]),en=useCallback(()=>{I(false);},[]),tn=useCallback(()=>{e.endSessionForEveryone();},[e]),_t=useCallback(async N=>{let z=N==="code"?Qe(e.roomCode):N==="url"?Ke(e.roomCode):Xe(e.roomCode);try{await Rr.write(z),B.show("Copied!");}catch{B.show(`Copy failed \u2014 ${z}`);}},[e.roomCode,B]),ft=a.rounds.filter(N=>N.revealedAt!==void 0),on=ft.length>0?ft[ft.length-1]:null;return jsxs(Box,{flexDirection:"column",children:[jsx(yo,{roomCode:e.roomCode,sessionName:a.settings.name,status:l,isHost:E}),J.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:J.notice})}),B.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:B.notice.startsWith("Copy failed")?"red":"green",children:B.notice})}),R?jsx(Eo,{sessionName:a.settings.name,displayName:g,currentScale:a.settings.defaultScale,accessMode:k,presetOverrides:r,customScales:s,isHost:E,onChangeName:zo,onChangeScale:Qo,onChangeDisplayName:Ko,onChangeAccess:Xo,onClose:en}):S==="lobby"?jsx(Mo,{projection:a,onlineIds:c,isHost:E,participantId:t,rounds:a.rounds,currentRound:on,settingsOpen:R,onStartRound:M,onNewRound:Wo,roundTitlePromptActive:f,roundTitleInput:y,onRoundTitleChange:H,onRoundTitleSubmit:K,onRoundTitleCancel:Fo,onRevote:qo,onOpenSettings:Lt,onHandoffHost:Zo,onEndSession:tn,onShare:_t,shareOpen:Y,onSetShareOpen:G,roomCode:e.roomCode,confirmingQuit:x}):S==="voting"&&v?jsx(Bo,{projection:a,round:v,onlineIds:c,isHost:E,myId:t,myRole:m,elapsedMs:A,onVote:Vo,onClearVote:Yo,onReveal:Jo,onToggleRole:Go,onShare:_t,onSetShareOpen:G,shareOpen:Y,settingsOpen:R,onOpenSettings:Lt,roomCode:e.roomCode,confirmingQuit:x}):null,x&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function $o({presetOverrides:e,customScales:t}){let{exit:o}=useApp(),[n,r]=useState("main-menu"),[s,p]=useState(de()),[a,d]=useState(s.displayName??""),[l,i]=useState(s.relayUrl??""),[c,h]=useState(s.defaultSessionName??""),[A,O]=useState(t??[]),[R,I]=useState(e??{});useInput(S=>{(S==="q"||S==="Q")&&o();},{isActive:n==="main-menu"});let k=useMemo(()=>Je(R,A),[R,A]),u=s.defaultScale,g=u?k.find(S=>S.id===u):void 0,w=[{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:`[${g?pe(g.id):"(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 x(S){S==="display-name"?(d(s.displayName??""),r("editing-display-name")):S==="relay-url"?(i(s.relayUrl??""),r("editing-relay-url")):S==="default-scale"?r("picking-scale"):S==="default-session-name"?(h(s.defaultSessionName??""),r("editing-session-name")):S==="default-password"&&r("picking-default-password");}function T(S){let v=S.trim();if(v.length>0){let E={...s,displayName:v};p(E),_({displayName:v});}r("main-menu");}function f(S){let v=S.trim();if(v.length>0){let E={...s,relayUrl:v};p(E),_({relayUrl:v});}r("main-menu");}function P(S){let v=S.trim(),E=v.length>0?{...s,defaultSessionName:v}:{...s};v.length===0?(delete E.defaultSessionName,p(E),Ee({defaultSessionName:""})):(p(E),_({defaultSessionName:v})),r("main-menu");}function y(S){let v=S.length>0?{...s,defaultScale:S}:{...s};S.length===0?(delete v.defaultScale,p(v),Ee({defaultScale:""})):(p(v),_({defaultScale:S})),r("main-menu");}function H(S,v){let E={...R};v.length===0?delete E[S]:E[S]=v,I(E),_({presetOverrides:Object.keys(E).length>0?E:void 0});}function J(S){let v=S==="on",E={...s,defaultPassword:v};p(E),_({defaultPassword:v}),r("main-menu");}function Y(S,v){let E=`custom-${randomUUID()}`,L=[...A,{id:E,label:S,cards:v}];O(L),p({...s,customScales:L}),_({customScales:L});}function G(S,v,E){let L=A.map(m=>m.id===S?{id:S,label:v,cards:E}:m);O(L),p({...s,customScales:L}),_({customScales:L});}function B(S){let v=A.filter(L=>L.id!==S);O(v);let E={...s,customScales:v};s.defaultScale===S?(E.defaultScale="fibonacci",_({customScales:v,defaultScale:"fibonacci"})):_({customScales:v}),p(E);}if(n==="main-menu")return jsx(ne,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:w,onSelect:x,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(W,{value:a,onChange:d,onSubmit:T,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(W,{value:l,onChange:i,onSubmit:f,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(W,{value:c,onChange:h,onSubmit:P,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 S=[{id:"",cards:[]},...k];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(tt,{scales:S,selectedScaleId:u??"",presetOverrides:R,customScales:A,onSelect:y,onOverrideChange:H,onCustomScaleCreate:Y,onCustomScaleEdit:G,onCustomScaleDelete:B,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(n==="picking-default-password"){let S=[{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(ne,{title:"Default password:",items:S,onSelect:J,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function jt(){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 kr(e){let t=await Te(),o=e.scale??t.defaultScale??"fibonacci",n=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,s;r&&(s=await jt());let p=Ye(o,t.presetOverrides,t.customScales);if(!p){let c=Object.keys(X).join(", ");console.error(`Unknown or fully-disabled scale: "${o}". Builtin IDs: ${c}`),process.exit(1);}let a=await po({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:n,password:s,defaultScale:p}),d;s&&(d=await me(s,a.roomUuid)),qe({roomCode:a.roomCode,roomUuid:a.roomUuid,passwordHash:d,lastSeenAt:Date.now()}),console.error(`Room created: ${a.roomCode}`),console.error(`Share: hnch join ${a.roomCode}`),console.error("");let{waitUntilExit:l,unmount:i}=render(at.createElement(ut,{session:a,participantId:t.participantId,displayName:t.displayName,accessMode:s?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));ze({doc:a.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),i();try{await j();}catch(h){console.error(`Failed to clear cached session: ${h instanceof Error?h.message:String(h)}`);}a.disconnect(),process.exit(0);}}),await l(),a.disconnect(),j(),process.exit(0);}async function Hr(e){let t=await Te(),o=fo(e.code);o===null&&(console.error("invalid room code"),process.exit(1));let n;e.password&&(n=await jt());let r=await Ne(t.relayUrl,o),s;r.accessMode==="password"&&!e.password?s=await jt():e.password&&(s=n);let p,a=false,d=await mo({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:o,password:s,onRejection(c){if(c==="unknown-room"){Ge({clearLastSession:j,logger:console,exit:process.exit});return}c==="room-full"&&(a=true,p?.());}}),l;s&&(l=await me(s,d.roomUuid)),qe({roomCode:d.roomCode,roomUuid:d.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Joined room: ${d.roomCode}`),console.error("");let i=render(at.createElement(ut,{session:d,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));p=i.unmount,ze({doc:d.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),p?.();try{await j();}catch(h){console.error(`Failed to clear cached session: ${h instanceof Error?h.message:String(h)}`);}d.disconnect(),process.exit(0);}}),await i.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),d.disconnect(),j(),process.exit(1)),d.disconnect(),j(),process.exit(0);}async function Br(){let e=await Te(),t=ho();t||(console.error("No recent session to resume."),process.exit(0));let o;try{o=await Ne(e.relayUrl,t.roomCode);}catch(i){if((i instanceof Error?i.message:String(i)).includes("Room not found"))return await Ge({clearLastSession:j,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`),j(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let n=new we.Doc,r=new Awareness(n);Ve(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let s=false,p=false,a,d=We({doc:n,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(i){if(i==="unknown-room"){Ge({clearLastSession:j,logger:console,exit:process.exit});return}i==="wrong-password"&&(s=true,a?.()),i==="room-full"&&(p=true,a?.());}});qe({roomCode:d.roomCode,roomUuid:d.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let l=render(at.createElement(ut,{session:d,participantId:e.participantId,displayName:e.displayName,accessMode:o.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));a=l.unmount,ze({doc:d.doc,localParticipantId:e.participantId,onEnded:async i=>{console.error(i.isLocal?"Session ended.":`Session ended by ${i.hostName}.`),a?.();try{await j();}catch(c){console.error(`Failed to clear cached session: ${c instanceof Error?c.message:String(c)}`);}d.disconnect(),process.exit(0);}}),await l.waitUntilExit(),p&&(console.error("This room is full (max 20 participants)."),j(),process.exit(1)),s&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),j(),process.exit(0)),d.disconnect(),j(),process.exit(0);}async function Ur(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 Te(),{waitUntilExit:r}=render(at.createElement($o,{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=de();if(!Ye(e.scale,n.presetOverrides,n.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(X).join(", ")}`);return}}o.defaultScale=e.scale;}e.sessionName!==void 0&&(o.defaultSessionName=e.sessionName),e.password!==void 0&&(o.defaultPassword=e.password),Ee(o),console.log("Config updated.");}var _o=Or(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=>{kr(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=>{Hr(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Br().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=>{Ur(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(),$t=hideBin(process.argv);($t.length===0||$t.length===1&&$t[0]==="--")&&(_o.showHelp(),process.exit(0));_o.parse();
|
|
2
|
+
import _r from'yargs';import {hideBin}from'yargs/helpers';import ht,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as Re 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 Yn from'ws';import kr from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var Rn="https://hnch.dev";function Pe(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function It(){return join(Pe(),"config.json")}function eo(){let e=Pe();existsSync(e)||mkdirSync(e,{recursive:true});}function fe(){let e=It();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function Y(e){eo();let o={...fe(),...e};writeFileSync(It(),JSON.stringify(o,null,2)+`
|
|
3
|
+
`,"utf-8");}async function In(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(o=>{t.question(e,n=>{t.close(),o(n.trim());});})}function Tn(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function Oe(){let e=fe(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let n=await In("Enter your display name: ");e.displayName=n||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=Rn,t=true),t&&Y(e);let o=process.env.HNCH_RELAY_URL||e.relayUrl;return o=Tn(o),{participantId:e.participantId,displayName:e.displayName,relayUrl:o,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales}}function De(e){eo();let o={...fe()};for(let[n,r]of Object.entries(e))r===""?delete o[n]:r!==void 0&&(o[n]=r);writeFileSync(It(),JSON.stringify(o,null,2)+`
|
|
4
|
+
`,"utf-8");}var En={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},to=new Map(Object.entries(En).map(([e,t])=>[t,e]));function ge(e){return e.role??"voter"}var qe={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},oo={id:"t-shirt",cards:["XS","S","M","L","XL"]},no={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},ro={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},so={id:"risk",cards:["Low","Medium","High","Critical"]},Z={[qe.id]:qe,[oo.id]:oo,[no.id]:no,[ro.id]:ro,[so.id]:so},io={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function he(e){return e in io?io[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 An="meta",Me="settings",Nn="participants",Pn="rounds",On=["roomUuid","createdAt","createdBy","sessionEndedAt"],Dn=["name","defaultScale","hostParticipantId"],Mn=["displayName","joinedAt","role","leftAt","removedBy"],kn=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","createdBy","createdAt"];function Ge(e){return e.getMap(An)}function ze(e){return e.getMap(Me)}function Qe(e){return e.getMap(Nn)}function Tt(e){return e.getArray(Pn)}function Ke(e,t){let o={};for(let n of t){let r=e.get(n);r!==void 0&&(o[n]=r);}return o}function Bn(e){return Ke(Ge(e),On)}function Hn(e){return Ke(ze(e),Dn)}function Un(e){let t=Qe(e),o=[];return t.forEach((n,r)=>{let a=Ke(n,Mn);o.push({id:r,...a});}),o.sort((n,r)=>n.joinedAt-r.joinedAt||n.id.localeCompare(r.id)),o}function $n(e){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}function jn(e){let t=Ke(e,kn),o=e.get("votes"),n=o?$n(o):{};return {...t,votes:n}}function Ln(e){let t=Tt(e),o=[];return t.forEach(n=>{o.push(jn(n));}),o}function K(e){return {meta:Bn(e),settings:Hn(e),participants:Un(e),rounds:Ln(e)}}function ao(e,t){if(Ge(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let o=Ge(e);o.set("roomUuid",t.roomUuid),o.set("createdAt",t.createdAt),o.set("createdBy",t.participantId);let n=ze(e);t.sessionName!==void 0&&n.set("name",t.sessionName),n.set("defaultScale",t.defaultScale),n.set("hostParticipantId",t.participantId);let r=new Re.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),Qe(e).set(t.participantId,r);});}function Xe(e,t){e.transact(()=>{let o=Qe(e),n=o.get(t.participantId),r=n??new Re.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 Ie(e,t){e.transact(()=>{let o=ze(e);for(let[n,r]of Object.entries(t))r===void 0?o.delete(n):o.set(n,r);});}function Et(e,t,o){e.transact(()=>{let n=Qe(e),r=n.get(t),a=r??new Re.Map;a.set("displayName",o.displayName),a.set("joinedAt",o.joinedAt),o.role!==void 0&&a.set("role",o.role),r===void 0&&n.set(t,a);});}function At(e,t){let o=t.scale??ze(e).get("defaultScale");if(!o)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let n=new Re.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 Re.Map),Tt(e).push([n]);}),t.id}function co(e,t,o){let n=Ze(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 Ze(e,t){let o=Tt(e);for(let n=0;n<o.length;n+=1){let r=o.get(n);if(r.get("id")===t)return r}}function lo(e,t,o,n){let r=Ze(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 uo(e,t,o){let n=Ze(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 Nt(e,t,o){let n=Ze(e,t);if(!n)throw new Error(`revealRound: round ${t} not found`);e.transact(()=>{n.set("revealedAt",o);});}function po(e){e.transact(()=>{Ge(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[t.length-1]}function mo(e){let t=Object.values(e.votes);return t.length<2?false:t.every(o=>o===t[0])}var fo="PBKDF2",_n="SHA-256",go=new TextEncoder;function Fn(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Se(e,t){let o=await crypto.subtle.importKey("raw",go.encode(e),fo,false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:fo,salt:go.encode(t),iterations:1e5,hash:_n},o,256);return Fn(n)}var ho="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(ho.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${ho.length}`);function Pt(e){return e.trim().replace(/-/g,"").toUpperCase()}function So(e,t=true){let o=Pt(e);return !t||o.length!==6?o:`${o.slice(0,3)}-${o.slice(3)}`}function et(e,t,o){if(e.startsWith("custom-")){let r=(o??[]).find(a=>a.id===e);return r?{id:r.id,cards:r.cards}:void 0}let n=Z[e];if(n){let r=(t??{})[e]??[];if(r.length===0)return n;let a=n.cards.filter((u,i)=>!r.includes(i));return a.length===0?void 0:{id:e,cards:a}}}function tt(e,t){let o=Object.keys(Z).map(r=>et(r,e,t)).filter(r=>r!==void 0),n=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...o,...n]}async function xo(e,t){let o=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!o.ok)throw new Error(`POST /rooms failed: ${o.status}`);return await o.json()}async function ke(e,t){let o=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(o.status===404){let n=await o.json().catch(()=>null);throw new Error(`Room not found: ${n?.reason??"unknown-room"}`)}if(!o.ok)throw new Error(`GET /rooms/:code failed: ${o.status}`);return await o.json()}async function Ot(e,t,o){let n=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:o})});if(!n.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${n.status}`)}function wo(e){let o=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,n={did:e.deviceId};e.passwordHash!==void 0&&(n.pw=e.passwordHash);let r=new WebsocketProvider(o,e.roomUuid,e.doc,{params:n,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:Yn}),a=l=>{e.onStatusChange?.(l.status);},u=l=>{if(l===null)return;let s=to.get(l.code);s!==void 0&&(e.onRejection?.(s),r.shouldConnect=false,r.disconnect());};r.on("status",a),r.on("connection-close",u);let i=false,p=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(l){if(l.passwordHash===p)return;p=l.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let c={did:r.params.did??""};p!==void 0&&(c.pw=p),r.params=c,r.connect();},disconnect(){i||(i=true,r.off("status",a),r.off("connection-close",u),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Jn=5e3;function yo(e,t,o){let n=null,r=null;function a(){let s=new Set;return t.getStates().forEach(c=>{let f=c.participantId;typeof f=="string"&&s.add(f);}),s}function u(){return e.getMap(Me).get("hostParticipantId")}function i(){r!==null&&(clearTimeout(r),r=null),n=null;}function p(){let s=u(),c=n;if(n=null,!c||s!==c)return;let f=a();if(f.has(s))return;let A=[...f].sort();if(A.length===0)return;let P=A[0];P===o&&Ie(e,{hostParticipantId:P});}function l(){let s=u();if(!s)return;if(a().has(s)){i();return}n!==s&&(i(),n=s,r=setTimeout(()=>{r=null,p();},Jn));}return t.on("change",l),e.getMap(Me).observe(l),l(),{stop(){i(),t.off("change",l),e.getMap(Me).unobserve(l);}}}async function bo(e){let t,o=await xo(e.relayUrl);e.password&&(t=await Se(e.password,o.uuid),await Ot(e.relayUrl,o.uuid,t));let n=new Re.Doc,r=new Awareness(n),a=Date.now();return ao(n,{roomUuid:o.uuid,createdAt:a,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??qe,sessionName:e.sessionName}),r.setLocalStateField("participantId",e.participantId),ot({doc:n,awareness:r,roomCode:o.code,roomUuid:o.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function Ro(e){let t=await ke(e.relayUrl,e.roomCode),o;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");o=await Se(e.password,t.uuid);}let n=new Re.Doc,r=new Awareness(n);return Xe(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),ot({doc:n,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:o,onRejection:e.onRejection})}function ot(e){let{doc:t,awareness:o,participantId:n,relayUrl:r,roomUuid:a}=e,u=new Set,i=new Set,p=new Set,l=wo({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:n,passwordHash:e.passwordHash,awareness:o,onStatusChange(d){u.forEach(m=>m(d));},onRejection(d){console.error(`Connection rejected: ${d}`),e.onRejection?.(d);}}),s=yo(t,o,n),c=()=>{i.forEach(d=>d());};t.getMap("meta").observeDeep(c),t.getMap("settings").observeDeep(c),t.getMap("participants").observeDeep(c),t.getArray("rounds").observeDeep(c);function f(){let d=new Set;return o.getStates().forEach(m=>{let v=m.participantId;typeof v=="string"&&d.add(v);}),d}let A=new Set,P=setInterval(()=>{let d=K(t),m=ee(d);if(!m||m.revealedAt!==void 0||A.has(m.id))return;let v=f();if(v.size===0)return;let x=d.participants.filter(S=>v.has(S.id)&&ge(S)==="voter");if(x.length===0)return;x.filter(S=>S.id in m.votes).length>=x.length&&(A.add(m.id),Nt(t,m.id,Date.now()));},250),I=t.getMap("settings").get("hostParticipantId"),T=()=>{let d=t.getMap("settings").get("hostParticipantId");d!==I&&d!==void 0&&p.forEach(m=>m(d)),I=d;};t.getMap("settings").observe(T);let H=false;return {doc:t,awareness:o,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return K(t)},current(){return ee(K(t))},isHost(){return K(t).settings.hostParticipantId===n},onlineIds:f,vote(d){let m=ee(K(t));m&&lo(t,m.id,n,d);},unvote(){let d=ee(K(t));d&&uo(t,d.id,n);},reveal(){let d=ee(K(t));d&&Nt(t,d.id,Date.now());},newRound(d){let m=randomUUID();return At(t,{id:m,createdAt:Date.now(),createdBy:n,title:d}),m},revote(){let d=ee(K(t)),m=randomUUID();return At(t,{id:m,createdAt:Date.now(),createdBy:n,parentRoundId:d?.id,title:d?.title,description:d?.description,ticketId:d?.ticketId}),m},updateRoundDescriptor(d,m){co(t,d,m);},updateName(d){Ie(t,{name:d});},updateScale(d){Ie(t,{defaultScale:d});},updateDisplayName(d){let x=K(t).participants.find(N=>N.id===n)?.joinedAt??Date.now();Et(t,n,{displayName:d,joinedAt:x});},async updateAccess(d,m){let v=null;if(d==="password"){if(!m)throw new Error("Password required for password mode");v=await Se(m,a);}await Ot(r,a,v),l.updateCredentials({passwordHash:v});},handoffHost(d){if(!this.isHost())throw new Error("Only the current host can hand off");if(!f().has(d))throw new Error("Target participant is not online");if(!K(t).participants.some(N=>N.id===d))throw new Error("Target participant does not exist");Ie(t,{hostParticipantId:d});},toggleRole(){let m=K(t).participants.find(S=>S.id===n),x=ge(m??{})==="viewer"?"voter":"viewer",N=m?.joinedAt??Date.now();Et(t,n,{displayName:m?.displayName??"",joinedAt:N,role:x});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");po(t);},onChange(d){return i.add(d),()=>i.delete(d)},onStatusChange(d){return u.add(d),()=>u.delete(d)},onHostChange(d){return p.add(d),()=>p.delete(d)},disconnect(){H||(H=true,clearInterval(P),s.stop(),t.getMap("meta").unobserveDeep(c),t.getMap("settings").unobserveDeep(c),t.getMap("settings").unobserve(T),t.getMap("participants").unobserveDeep(c),t.getArray("rounds").unobserveDeep(c),l.disconnect());}}}function Io(e){let t=Pt(e);return t===""?null:t}var Xn=1440*60*1e3;function Mt(){return join(Pe(),"last-session.json")}function Zn(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 Eo(){let e=Mt();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !Zn(t)||Date.now()-t.lastSeenAt>Xn?(_(),null):t}catch{return _(),null}}function nt(e){let t=Pe();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let o=Mt();writeFileSync(o,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{encoding:"utf-8",mode:384}),chmodSync(o,384);}function _(){let e=Mt();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function rt(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 st(e){let t=e.doc.getMap("meta"),o=null,n=false;function r(){if(n)return;let a=t.get("sessionEndedAt");if(a==null||a===o)return;o=a;let u=t.get("createdBy"),i=u===e.localParticipantId,p=e.doc.getMap("participants"),l=e.doc.getMap("settings").get("hostParticipantId")??u,s="host";if(l){let f=p.get(l)?.get("displayName");typeof f=="string"&&f.length>0&&(s=f);}setImmediate(()=>{n||e.onEnded({isLocal:i,hostName:s,timestamp:a});});}return t.observe(r),r(),()=>{n=true,t.unobserve(r);}}var er="@xauyxau/hnch";function it(e){return So(e)}function at(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function ct(e){return `npx ${er} join ${e}`}var tr={connecting:"yellow",connected:"green",disconnected:"red"};function Po({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:tr[o],children:o})]})]})}function se({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),[a,u]=useState(r>=0?r:0);return useInput((i,p)=>{if(p.upArrow)u(l=>{let s=(l-1+e.length)%e.length,c=0;for(;e[s]?.disabled&&c<e.length;)s=(s-1+e.length)%e.length,c++;return s});else if(p.downArrow)u(l=>{let s=(l+1)%e.length,c=0;for(;e[s]?.disabled&&c<e.length;)s=(s+1)%e.length,c++;return s});else if(p.return){let l=e[a];l&&!l.disabled&&t(l.value);}else p.escape&&o?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Box,{flexDirection:"column",children:e.map((i,p)=>{let l=p===a,s=i.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{color:l?"cyan":void 0,dimColor:s,children:l?">":" "}),jsx(Text,{bold:l,dimColor:s,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 W({value:e,onChange:t,onSubmit:o,onCancel:n,placeholder:r,isActive:a=true,mask:u=false}){useInput((s,c)=>{c.escape?n?.():c.return?o(e):c.backspace||c.delete?t(e.slice(0,-1)):s&&!c.ctrl&&!c.meta&&t(e+s);},{isActive:a});let i=u&&e.length>0?"*".repeat(e.length):e,p=i.length>0?i:r??"",l=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:l,children:p}),jsx(Text,{inverse:true,children:" "})]})}function ko({mode:e,password:t,onModeChange:o,onPasswordChange:n,onClose:r}){let[a,u]=useState(e==="open"?0:1),[i,p]=useState(false);return useEffect(()=>{u(e==="open"?0:1);},[e]),useInput((l,s)=>{if(s.leftArrow)u(c=>Math.max(0,c-1));else if(s.rightArrow)u(c=>Math.min(1,c+1));else if(s.return){let c=a===0?"open":"password";c!==e&&o(c),c==="password"&&p(true);}else s.escape&&r?.();},{isActive:!i}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((l,s)=>{let c=s===a,f=l===e,A=l==="open"?"Open":"Password";return jsx(Text,{inverse:c,bold:f,color:f?"cyan":void 0,children:f?`[${A}]`:` ${A} `},l)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(W,{value:t,onChange:n,onSubmit:()=>p(false),onCancel:()=>p(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 Uo({scaleId:e,cards:t,disabledIndices:o,onOverrideChange:n,onClose:r}){let a=useMemo(()=>new Set(o),[o]),[u,i]=useState(0),p=l=>{let s=new Set(a);if(s.has(l))s.delete(l);else {if(s.size>=t.length-1)return;s.add(l);}let c=Array.from(s).sort((f,A)=>f-A);n(e,c);};return useInput((l,s)=>{s.leftArrow?i(c=>Math.max(0,c-1)):s.rightArrow?i(c=>Math.min(t.length-1,c+1)):l===" "?p(u):(s.return||s.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((l,s)=>{let c=s===u,f=a.has(s);return jsx(Text,{inverse:c,bold:!f,color:f?void 0:"cyan",strikethrough:f,dimColor:f,children:l},l)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function _t({initialName:e="",initialCards:t=[],onSave:o,onCancel:n}){let r=e.length>0,[a,u]=useState(e),[i,p]=useState(t.length>0?t:[""]),[l,s]=useState(0),[c,f]=useState("editing-name"),[A,P]=useState(""),I=()=>{let d=a.trim();if(d.length<1||d.length>40){P("Name must be 1-40 characters");return}u(d),P(""),f("editing-cards");},T=()=>{let d=a.trim();if(d.length<1||d.length>40){P("Name must be 1-40 characters");return}let m=i.map(x=>x.trim()).filter(x=>x.length>0),v=Array.from(new Set(m));if(v.length<2){P("Need at least 2 unique non-empty cards");return}P(""),o(d,v);};return useInput((d,m)=>{if(c==="editing-cards"){if(m.leftArrow)s(v=>Math.max(0,v-1));else if(m.rightArrow)s(v=>{let x=v+1;return x>=i.length&&i.length<25?(p(N=>[...N,""]),x):Math.min(x,i.length-1)});else if(m.return)T();else if(m.escape)n();else if(m.tab)f("editing-name");else if(m.backspace){let v=i[l]||"";if(v.length===0){if(i.length>2){let x=i.filter((N,S)=>S!==l);p(x),s(Math.max(0,l-1));}}else {let x=[...i];x[l]=v.slice(0,-1),p(x);}}else if(d&&!m.ctrl&&!m.meta){let v=i[l]||"";if(v.length<10){let x=[...i];x[l]=v+d,p(x);}}}},{isActive:c==="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(W,{value:a,onChange:u,onSubmit:I,onCancel:n,placeholder:"Scale name",isActive:c==="editing-name"})]}),c==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:i.map((d,m)=>{let v=m===l;return jsx(Text,{inverse:v,color:v?void 0:"cyan",children:d.length>0?d:"\xB7"},m)})})]}),A&&jsx(Text,{color:"red",children:A}),jsx(Text,{dimColor:true,children:c==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function ut({scales:e,selectedScaleId:t,presetOverrides:o,customScales:n=[],onSelect:r,onOverrideChange:a,onCustomScaleCreate:u,onCustomScaleEdit:i,onCustomScaleDelete:p,onClose:l,showNoneOption:s=false}){let[c,f]=useState(0),[A,P]=useState(null),[I,T]=useState("browsing"),[H,d]=useState(null),[m,v]=useState(null),x=u?[...e,{id:"__create-custom__",cards:[]}]:e,N=x.length;if(useInput((S,k)=>{if(I==="browsing"){if(k.escape){l();return}if(N===0)return;if(k.upArrow)f(b=>(b-1+N)%N);else if(k.downArrow)f(b=>(b+1)%N);else if(k.return){let b=x[c];if(!b)return;if(b.id==="__create-custom__"){T("creating");return}b.id in Z?P(A===b.id?null:b.id):r(b.id);}else if(S===" "){let b=x[c];b&&b.id!=="__create-custom__"&&r(b.id);}else if(S==="e"||S==="E"){let b=x[c];i&&b?.id.startsWith("custom-")&&(d(b.id),T("editing"));}else if(S==="d"||S==="D"){let b=x[c];p&&b?.id.startsWith("custom-")&&(v(b.id),T("confirming-delete"));}}else I==="confirming-delete"&&(S==="y"||S==="Y"?(m&&p&&p(m),v(null),T("browsing")):(S==="n"||S==="N"||k.escape)&&(v(null),T("browsing")));},{isActive:I==="browsing"&&A===null||I==="confirming-delete"}),I==="creating")return jsx(_t,{onSave:(S,k)=>{u&&u(S,k),T("browsing");},onCancel:()=>T("browsing")});if(I==="editing"&&H){let S=n?.find(b=>b.id===H);if(e.find(b=>b.id===H)&&S)return jsx(_t,{initialName:S.label,initialCards:S.cards,onSave:(b,j)=>{i&&i(H,b,j),d(null),T("browsing");},onCancel:()=>{d(null),T("browsing");}})}if(I==="confirming-delete"&&m){let S=x.find(b=>b.id===m),k=S?he(S.id):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",k,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return x.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:x.map((S,k)=>{let b=k===c,j=S.id===t,oe=A===S.id,X=S.id in Z;S.id.startsWith("custom-");let z=S.id==="__create-custom__",g=S.cards.join(", "),y=s&&S.id==="",E=y?"(none)":z?"[+ Create custom scale]":he(S.id);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{color:b?"cyan":void 0,children:b?">":" "}),jsx(Text,{bold:b,children:E}),!y&&!z&&jsx(Text,{dimColor:true,children:g}),j&&jsx(Text,{color:"cyan",children:"[current]"})]}),oe&&!y&&!z&&jsx(Box,{paddingLeft:2,children:X?jsx(Uo,{scaleId:S.id,cards:Z[S.id]?.cards??[],disabledIndices:o?.[S.id]??[],onOverrideChange:a,onClose:()=>P(null)}):null})]},S.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let S=c<x.length?x[c]:null;return S?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${i?" [e] edit":""}${p?" [d] delete":""} esc back`:S&&S.id in Z?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function gr(e,t){return t?[...e]:e.filter(o=>o.value==="display-name")}function $o({sessionName:e,displayName:t,currentScale:o,accessMode:n,presetOverrides:r,customScales:a,isHost:u=true,onChangeName:i,onChangeScale:p,onChangeDisplayName:l,onChangeAccess:s,onClose:c}){let[f,A]=useState(r??{}),P=useMemo(()=>tt(f,a),[f,a]),[I,T]=useState("main-menu"),[H,d]=useState(e??""),[m,v]=useState(t),[x,N]=useState(n==="password"?"password":"open"),[S,k]=useState(""),[b,j]=useState(false),oe=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${he(o.id)}]`},{label:"Access",value:"access",detail:`[${n==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],X=gr(oe,u);function le(O){!u&&O!=="display-name"||(O==="room-name"?(d(e??""),T("editing-room-name")):O==="scale"?T("picking-scale"):O==="access"?T("picking-access"):O==="display-name"&&(v(t),T("editing-display-name")));}function z(O){let M=O.trim()===""?void 0:O.trim();i(M),T("main-menu");}function g(O){let M=O.trim();M.length>0&&(l(M),process.nextTick(()=>Y({displayName:M}))),T("main-menu");}function y(O){let M=P.find(L=>L.id===O);M&&p(M),T("main-menu");}function E(O,M){let L={...f};M.length===0?delete L[O]:L[O]=M,A(L),Y({presetOverrides:Object.keys(L).length>0?L:void 0});}async function U(O,M){j(true);try{await s(O,M),N(O),k(O==="password"?M??"":"");}catch(L){console.error(`Failed to update access: ${L}`);}finally{j(false),T("main-menu");}}return I==="main-menu"?jsx(se,{title:"\u2500\u2500 Settings \u2500\u2500",items:X,onSelect:le,onClose:c}):I==="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(W,{value:H,onChange:d,onSubmit:z,onCancel:()=>T("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):I==="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(W,{value:m,onChange:v,onSubmit:g,onCancel:()=>T("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):I==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(ut,{scales:P,selectedScaleId:o.id,presetOverrides:f,onSelect:y,onOverrideChange:E,onClose:()=>T("main-menu")})]}):I==="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(ko,{mode:x,password:S,onModeChange:O=>{O==="open"&&U("open");},onPasswordChange:k,onClose:()=>T("main-menu")})]}):jsx(Box,{})}function ft({participants:e,onlineIds:t,hostId:o,votes:n,revealed:r,participantId:a}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(u=>{let i=t.has(u.id),p=i?"\u25CF":"\u25CB",l=i?"green":"gray",s=u.id===o,c=ge(u)==="viewer",f=u.id===a,A=u.id in n,P=c?" (viewer)":r?n[u.id]?` \u2192 ${n[u.id]}`:"":A?" \u2713":" \xB7",I=f&&!c&&!(r&&n[u.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:l,children:p}),jsxs(Text,{children:[u.displayName,s?" (host)":""]}),I?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:c?"gray":A?"green":"gray",children:P})]},u.id)})]})}var hr=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function Lo({onPick:e,onClose:t}){return jsx(se,{title:"Host Actions",items:hr,onSelect:e,onClose:t})}function gt({roomCode:e,onPick:t,onClose:o}){let n=[{label:"Copy code",value:"code",detail:it(e)},{label:"Copy share link",value:"url",detail:at(e)},{label:"Copy npx command",value:"npx",detail:ct(e)}];return jsx(se,{title:"Share",items:n,onSelect:r=>t(r),onClose:o})}function yr(e){let t=Object.values(e).map(s=>parseFloat(s)).filter(s=>!isNaN(s)).sort((s,c)=>s-c);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let n=t.reduce((s,c)=>s+c,0)/t.length,r=Math.floor(t.length/2),a=t.length%2===0?(t[r-1]+t[r])/2:t[r],u=Object.values(e),i=new Map;for(let s of u)i.set(s,(i.get(s)??0)+1);let p=Math.max(...i.values()),l=u.length>0?Math.round(p/u.length*100):0;return {average:n.toFixed(1),median:a.toFixed(1),agreement:`${l}%`}}function _o(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 vr(e,t){let o=new Map;for(let i of Object.values(e.votes))o.set(i,(o.get(i)??0)+1);let n=[...o.entries()].sort((i,p)=>p[1]-i[1]||i[0].localeCompare(p[0])).map(([i,p])=>`${i}\xD7${p}`).join(", "),r=e.title?` ${e.title}`:"",a=e.ticketId?` [${e.ticketId}]`:"",u=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${_o(e.timerStartedAt,e.revealedAt)}`:"";return `Round ${t}:${r}${a} \u2014 ${n||"(no votes)"}${u}`}function Fo({projection:e,onlineIds:t,isHost:o,participantId:n,rounds:r,currentRound:a,settingsOpen:u,onStartRound:i,onNewRound:p,onRevote:l,onOpenSettings:s,onHandoffHost:c,onEndSession:f,onShare:A,shareOpen:P,onSetShareOpen:I,roomCode:T,confirmingQuit:H,myRole:d,onToggleRole:m,roundTitlePromptActive:v,roundTitleInput:x,onRoundTitleChange:N,onRoundTitleSubmit:S,onRoundTitleCancel:k,descriptorPromptActive:b,descriptorInput:j,onDescriptorChange:oe,onDescriptorSubmit:X,onDescriptorCancel:le,onEditDescriptor:z}){let[g,y]=ht.useState("idle"),[E,U]=ht.useState(null),[O,M]=ht.useState(false),[L,me]=ht.useState(false);useEffect(()=>{o||(y("idle"),U(null),M(false),me(false));},[o]),useInput(h=>{if(h==="c"||h==="C"){I(true);return}if(h==="w"||h==="W"){m();return}o&&((h==="e"||h==="E")&&s(),(h==="s"||h==="S")&&i(),(h==="h"||h==="H")&&y("picking"),(h==="m"||h==="M")&&M(true),a?.revealedAt!==void 0&&((h==="n"||h==="N")&&p(),(h==="v"||h==="V")&&l(),(h==="t"||h==="T")&&z()));},{isActive:!u&&!H&&g==="idle"&&!v&&!O&&!L&&!P&&!b}),useInput((h,Q)=>{h==="y"||h==="Y"?(f(),me(false)):(h==="n"||h==="N"||Q.escape)&&me(false);},{isActive:L});let ne=e.participants.filter(h=>h.id!==n&&t.has(h.id));useInput(h=>{if(g==="picking"){let Q=parseInt(h,10);!isNaN(Q)&&Q>=1&&Q<=ne.length?(U(ne[Q-1].id),y("confirming")):(h==="Escape"||h==="q"||h==="Q")&&y("idle");}},{isActive:g==="picking"}),useInput(h=>{g==="confirming"&&E&&(h==="y"||h==="Y"?(c(E),y("idle"),U(null)):(h==="n"||h==="N"||h==="Escape")&&(y("idle"),U(null)));},{isActive:g==="confirming"});let Fe=r.length>0,Ne=r.filter(h=>h.revealedAt!==void 0),Ve=a!==null?Ne.slice(0,-1):Ne;return O?jsx(Lo,{onPick:h=>{M(false),h==="end-session"&&me(true);},onClose:()=>M(false)}):P?jsx(gt,{roomCode:T,onPick:h=>{I(false),A(h);},onClose:()=>I(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:Fe?"Session":"Waiting for participants..."}),!Fe&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(ft,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:n}),a?.revealedAt!==void 0&&jsx(Cr,{projection:e,round:a,rounds:r}),Ve.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),Ve.map(h=>{let Q=r.indexOf(h)+1;return jsx(Text,{dimColor:true,children:vr(h,Q)},h.id)})]}),g==="picking"&&ne.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),ne.map((h,Q)=>jsxs(Text,{children:["[",Q+1,"] ",h.displayName]},h.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),g==="picking"&&ne.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"})]}),g==="confirming"&&E&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(h=>h.id===E)?.displayName,"? [y/n]"]})}),v&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(W,{value:x,onChange:N,onSubmit:S,onCancel:k,placeholder:"Enter to skip",isActive:v})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),b&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(W,{value:j,onChange:oe,onSubmit:X,onCancel:le,placeholder:"Enter to save",isActive:b})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),L&&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"})]}),g==="idle"&&!v&&!b&&!L&&jsxs(Box,{gap:2,children:[o?jsx(Fragment,{children:a?.revealedAt!==void 0?jsxs(Fragment,{children:[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"}),jsxs(Text,{color:"yellow",children:["[w] ",d==="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"}),jsxs(Text,{color:"yellow",children:["[w] ",d==="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"}),jsxs(Text,{color:"yellow",children:["[w] ",d==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function Cr({projection:e,round:t,rounds:o}){let n=o.indexOf(t)+1,r=t.title?` \u2014 ${t.title}`:"",a=t.ticketId?` [${t.ticketId}]`:"",u=yr(t.votes),i=new Map(e.participants.map(s=>[s.id,s.displayName])),p=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?_o(t.timerStartedAt,t.revealedAt):null,l=Object.values(t.votes)[0];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{bold:true,children:["Round ",n,r,a," \u2014 Results"]}),mo(t)&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",l]}),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(([s,c])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(i.get(s)??s).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:c.padEnd(10)})]},s)),e.participants.filter(s=>!(s.id in t.votes)).map(s=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:s.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},s.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:u.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:u.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:u.agreement})]}),p!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",p]})]})]})}function Jo({scale:e,selected:t,onSelect:o,onClear:n,disabled:r}){let[a,u]=useState(0);return useInput((i,p)=>{if(!r)if(p.leftArrow)u(l=>Math.max(0,l-1));else if(p.rightArrow)u(l=>Math.min(e.cards.length-1,l+1));else if(p.return){let l=e.cards[a];l===t?n():o(l);}else (p.backspace||p.delete)&&n();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((i,p)=>{let l=p===a,s=i===t;return jsx(Text,{inverse:l,bold:s,color:s?"cyan":void 0,children:s?`[${i}]`:` ${i} `},i)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function Er(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function Wo({projection:e,round:t,onlineIds:o,isHost:n,myId:r,myRole:a,elapsedMs:u,roomCode:i,shareOpen:p,settingsOpen:l,onVote:s,onClearVote:c,onReveal:f,onToggleRole:A,onShare:P,onSetShareOpen:I,onOpenSettings:T,confirmingQuit:H}){if(useInput(N=>{if(N==="e"||N==="E"){T();return}if(N==="c"||N==="C"){I(true);return}n&&(N==="r"||N==="R")&&f(),(N==="w"||N==="W")&&A();},{isActive:!H&&!l&&!p}),p)return jsx(gt,{roomCode:i,onPick:N=>{I(false),P(N);},onClose:()=>I(false)});let d=t.votes[r],m=e.rounds.indexOf(t)+1,v=t.title?` \u2014 ${t.title}`:"",x=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",m,v,x]}),u!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",Er(u)]})]}),jsxs(Box,{gap:4,children:[jsx(ft,{participants:e.participants,onlineIds:o,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),a==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsx(Jo,{scale:t.scale,selected:d,onSelect:s,onClear:c,disabled:H})]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),jsxs(Text,{color:"yellow",children:["[w] ",a==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var Or=3e3;function Jt(e=Or){let[t,o]=useState(null),n=useRef(null),r=useCallback(()=>{n.current!==null&&(clearTimeout(n.current),n.current=null);},[]),a=useCallback(i=>{r(),o(i),n.current=setTimeout(()=>{o(null),n.current=null;},e);},[r,e]),u=useCallback(()=>{r(),o(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:a,dismiss:u}}function Br(e){let t=ee(e);return !t||t.revealedAt!==void 0?"lobby":"voting"}function yt({session:e,participantId:t,displayName:o,accessMode:n,presetOverrides:r,customScales:a}){let{exit:u}=useApp(),[i,p]=useState(e.projection()),[l,s]=useState("connecting"),[c,f]=useState(e.onlineIds()),[A,P]=useState(void 0),[I,T]=useState(false),[H,d]=useState(n==="password"?"password":"open"),[m,v]=useState(o),[x,N]=useState(false),[S,k]=useState(false),[b,j]=useState(""),[oe,X]=useState(false),[le,z]=useState(""),[g,y]=useState(null),E=Jt(3e3),[U,O]=useState(false),M=Jt(3e3);useEffect(()=>{let R=e.onChange(()=>{p(e.projection()),f(e.onlineIds());}),V=e.onStatusChange(s),Ye=e.onHostChange(Je=>{let hn=e.projection().participants.find(xn=>xn.id===Je),Sn=Je===t?"You are now the host":`${hn?.displayName||"Unknown"} is now the host`;E.show(Sn);}),gn=setInterval(()=>{f(e.onlineIds());let Je=e.projection(),We=ee(Je);We?.timerStartedAt!==void 0&&We.revealedAt===void 0?P(Date.now()-We.timerStartedAt):P(void 0);},1e3);return ()=>{R(),V(),Ye(),clearInterval(gn);}},[e,t,E.show]),useInput(R=>{(R==="q"||R==="Q")&&N(true);},{isActive:!I&&!x&&!S&&!oe&&!U}),useInput((R,V)=>{R==="y"||R==="Y"?(e.disconnect(),u()):(R==="n"||R==="N"||V.escape)&&N(false);},{isActive:x});let L=Br(i),me=ee(i),ne=i.settings.hostParticipantId===t,Fe=i.participants.find(R=>R.id===t),Ne=ge(Fe??{}),Ve=useCallback(()=>{j(""),k(true);},[]),h=useCallback(R=>{k(false),j(""),e.newRound(R.trim()||void 0);},[e]),Q=useCallback(()=>{k(false),j("");},[]),Xo=useCallback(()=>{let R=e.current();!R||R.revealedAt===void 0||(y(R.id),z(R.title??""),X(true));},[e]),Zo=useCallback(R=>{let V=g;if(X(false),y(null),!V)return;let Ye=R.trim();Ye!==""&&e.updateRoundDescriptor(V,{title:Ye});},[e,g]),en=useCallback(()=>{X(false),y(null);},[]),tn=useCallback(R=>{e.vote(R);},[e]),on=useCallback(()=>{e.unvote();},[e]),nn=useCallback(()=>{e.reveal();},[e]),rn=useCallback(()=>{j(""),k(true);},[]),sn=useCallback(()=>{e.revote();},[e]),zt=useCallback(()=>{e.toggleRole();},[e]),an=useCallback(R=>{e.updateName(R);},[e]),cn=useCallback(R=>{e.updateScale(R);},[e]),ln=useCallback(R=>{e.updateDisplayName(R),v(R);},[e]),dn=useCallback(async(R,V)=>{await e.updateAccess(R,V),d(R);},[e]),un=useCallback(R=>{try{e.handoffHost(R);}catch(V){console.error(`Handoff failed: ${V instanceof Error?V.message:String(V)}`);}},[e]),Qt=useCallback(()=>{T(true);},[]),pn=useCallback(()=>{T(false);},[]),mn=useCallback(()=>{e.endSessionForEveryone();},[e]),Kt=useCallback(async R=>{let V=R==="code"?it(e.roomCode):R==="url"?at(e.roomCode):ct(e.roomCode);try{await kr.write(V),M.show("Copied!");}catch{M.show(`Copy failed \u2014 ${V}`);}},[e.roomCode,M]),bt=i.rounds.filter(R=>R.revealedAt!==void 0),fn=bt.length>0?bt[bt.length-1]:null;return jsxs(Box,{flexDirection:"column",children:[jsx(Po,{roomCode:e.roomCode,sessionName:i.settings.name,status:l,isHost:ne}),E.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:E.notice})}),M.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:M.notice.startsWith("Copy failed")?"red":"green",children:M.notice})}),I?jsx($o,{sessionName:i.settings.name,displayName:m,currentScale:i.settings.defaultScale,accessMode:H,presetOverrides:r,customScales:a,isHost:ne,onChangeName:an,onChangeScale:cn,onChangeDisplayName:ln,onChangeAccess:dn,onClose:pn}):L==="lobby"?jsx(Fo,{projection:i,onlineIds:c,isHost:ne,participantId:t,rounds:i.rounds,currentRound:fn,settingsOpen:I,onStartRound:Ve,onNewRound:rn,roundTitlePromptActive:S,roundTitleInput:b,onRoundTitleChange:j,onRoundTitleSubmit:h,onRoundTitleCancel:Q,onRevote:sn,onOpenSettings:Qt,onHandoffHost:un,onEndSession:mn,onShare:Kt,shareOpen:U,onSetShareOpen:O,roomCode:e.roomCode,confirmingQuit:x,myRole:Ne,onToggleRole:zt,descriptorPromptActive:oe,descriptorInput:le,onDescriptorChange:z,onDescriptorSubmit:Zo,onDescriptorCancel:en,onEditDescriptor:Xo}):L==="voting"&&me?jsx(Wo,{projection:i,round:me,onlineIds:c,isHost:ne,myId:t,myRole:Ne,elapsedMs:A,onVote:tn,onClearVote:on,onReveal:nn,onToggleRole:zt,onShare:Kt,onSetShareOpen:O,shareOpen:U,settingsOpen:I,onOpenSettings:Qt,roomCode:e.roomCode,confirmingQuit:x}):null,x&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function Go({presetOverrides:e,customScales:t}){let{exit:o}=useApp(),[n,r]=useState("main-menu"),[a,u]=useState(fe()),[i,p]=useState(a.displayName??""),[l,s]=useState(a.relayUrl??""),[c,f]=useState(a.defaultSessionName??""),[A,P]=useState(t??[]),[I,T]=useState(e??{});useInput(g=>{(g==="q"||g==="Q")&&o();},{isActive:n==="main-menu"});let H=useMemo(()=>tt(I,A),[I,A]),d=a.defaultScale,m=d?H.find(g=>g.id===d):void 0,v=[{label:"Display name",value:"display-name",detail:`[${a.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${a.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${m?he(m.id):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${a.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${a.defaultPassword?"on":"off"}]`}];function x(g){g==="display-name"?(p(a.displayName??""),r("editing-display-name")):g==="relay-url"?(s(a.relayUrl??""),r("editing-relay-url")):g==="default-scale"?r("picking-scale"):g==="default-session-name"?(f(a.defaultSessionName??""),r("editing-session-name")):g==="default-password"&&r("picking-default-password");}function N(g){let y=g.trim();if(y.length>0){let E={...a,displayName:y};u(E),Y({displayName:y});}r("main-menu");}function S(g){let y=g.trim();if(y.length>0){let E={...a,relayUrl:y};u(E),Y({relayUrl:y});}r("main-menu");}function k(g){let y=g.trim(),E=y.length>0?{...a,defaultSessionName:y}:{...a};y.length===0?(delete E.defaultSessionName,u(E),De({defaultSessionName:""})):(u(E),Y({defaultSessionName:y})),r("main-menu");}function b(g){let y=g.length>0?{...a,defaultScale:g}:{...a};g.length===0?(delete y.defaultScale,u(y),De({defaultScale:""})):(u(y),Y({defaultScale:g})),r("main-menu");}function j(g,y){let E={...I};y.length===0?delete E[g]:E[g]=y,T(E),Y({presetOverrides:Object.keys(E).length>0?E:void 0});}function oe(g){let y=g==="on",E={...a,defaultPassword:y};u(E),Y({defaultPassword:y}),r("main-menu");}function X(g,y){let E=`custom-${randomUUID()}`,U=[...A,{id:E,label:g,cards:y}];P(U),u({...a,customScales:U}),Y({customScales:U});}function le(g,y,E){let U=A.map(O=>O.id===g?{id:g,label:y,cards:E}:O);P(U),u({...a,customScales:U}),Y({customScales:U});}function z(g){let y=A.filter(U=>U.id!==g);P(y);let E={...a,customScales:y};a.defaultScale===g?(E.defaultScale="fibonacci",Y({customScales:y,defaultScale:"fibonacci"})):Y({customScales:y}),u(E);}if(n==="main-menu")return jsx(se,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:v,onSelect:x,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(W,{value:i,onChange:p,onSubmit:N,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(W,{value:l,onChange:s,onSubmit:S,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(W,{value:c,onChange:f,onSubmit:k,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 g=[{id:"",cards:[]},...H];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(ut,{scales:g,selectedScaleId:d??"",presetOverrides:I,customScales:A,onSelect:b,onOverrideChange:j,onCustomScaleCreate:X,onCustomScaleEdit:le,onCustomScaleDelete:z,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(n==="picking-default-password"){let g=[{label:"On",value:"on",detail:a.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:a.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(se,{title:"Default password:",items:g,onSelect:oe,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function Gt(){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 Yr(e){let t=await Oe(),o=e.scale??t.defaultScale??"fibonacci",n=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,a;r&&(a=await Gt());let u=et(o,t.presetOverrides,t.customScales);if(!u){let c=Object.keys(Z).join(", ");console.error(`Unknown or fully-disabled scale: "${o}". Builtin IDs: ${c}`),process.exit(1);}let i=await bo({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:n,password:a,defaultScale:u}),p;a&&(p=await Se(a,i.roomUuid)),nt({roomCode:i.roomCode,roomUuid:i.roomUuid,passwordHash:p,lastSeenAt:Date.now()}),console.error(`Room created: ${i.roomCode}`),console.error(`Share: hnch join ${i.roomCode}`),console.error("");let{waitUntilExit:l,unmount:s}=render(ht.createElement(yt,{session:i,participantId:t.participantId,displayName:t.displayName,accessMode:a?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));st({doc:i.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),s();try{await _();}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(),_(),process.exit(0);}async function Jr(e){let t=await Oe(),o=Io(e.code);o===null&&(console.error("invalid room code"),process.exit(1));let n;e.password&&(n=await Gt());let r=await ke(t.relayUrl,o),a;r.accessMode==="password"&&!e.password?a=await Gt():e.password&&(a=n);let u,i=false,p=await Ro({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:o,password:a,onRejection(c){if(c==="unknown-room"){rt({clearLastSession:_,logger:console,exit:process.exit});return}c==="room-full"&&(i=true,u?.());}}),l;a&&(l=await Se(a,p.roomUuid)),nt({roomCode:p.roomCode,roomUuid:p.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Joined room: ${p.roomCode}`),console.error("");let s=render(ht.createElement(yt,{session:p,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));u=s.unmount,st({doc:p.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),u?.();try{await _();}catch(f){console.error(`Failed to clear cached session: ${f instanceof Error?f.message:String(f)}`);}p.disconnect(),process.exit(0);}}),await s.waitUntilExit(),i&&(console.error("This room is full (max 20 participants)."),p.disconnect(),_(),process.exit(1)),p.disconnect(),_(),process.exit(0);}async function Wr(){let e=await Oe(),t=Eo();t||(console.error("No recent session to resume."),process.exit(0));let o;try{o=await ke(e.relayUrl,t.roomCode);}catch(s){if((s instanceof Error?s.message:String(s)).includes("Room not found"))return await rt({clearLastSession:_,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`),_(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let n=new Re.Doc,r=new Awareness(n);Xe(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let a=false,u=false,i,p=ot({doc:n,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(s){if(s==="unknown-room"){rt({clearLastSession:_,logger:console,exit:process.exit});return}s==="wrong-password"&&(a=true,i?.()),s==="room-full"&&(u=true,i?.());}});nt({roomCode:p.roomCode,roomUuid:p.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let l=render(ht.createElement(yt,{session:p,participantId:e.participantId,displayName:e.displayName,accessMode:o.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));i=l.unmount,st({doc:p.doc,localParticipantId:e.participantId,onEnded:async s=>{console.error(s.isLocal?"Session ended.":`Session ended by ${s.hostName}.`),i?.();try{await _();}catch(c){console.error(`Failed to clear cached session: ${c instanceof Error?c.message:String(c)}`);}p.disconnect(),process.exit(0);}}),await l.waitUntilExit(),u&&(console.error("This room is full (max 20 participants)."),_(),process.exit(1)),a&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),_(),process.exit(0)),p.disconnect(),_(),process.exit(0);}async function qr(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 Oe(),{waitUntilExit:r}=render(ht.createElement(Go,{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=fe();if(!et(e.scale,n.presetOverrides,n.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(Z).join(", ")}`);return}}o.defaultScale=e.scale;}e.sessionName!==void 0&&(o.defaultSessionName=e.sessionName),e.password!==void 0&&(o.defaultPassword=e.password),De(o),console.log("Config updated.");}var Ko=_r(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=>{Yr(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=>{Jr(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Wr().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=>{qr(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(),qt=hideBin(process.argv);(qt.length===0||qt.length===1&&qt[0]==="--")&&(Ko.showHelp(),process.exit(0));Ko.parse();
|