@xauyxau/hnch 1.5.0 → 1.6.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 +5 -2
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 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();
|
|
2
|
+
import Yr from'yargs';import {hideBin}from'yargs/helpers';import St,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as Ie 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 zo from'ws';import Hr from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var No="https://hnch.dev";function Oe(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function It(){return join(Oe(),"config.json")}function nn(){let e=Oe();existsSync(e)||mkdirSync(e,{recursive:true});}function ge(){let e=It();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function Y(e){nn();let n={...ge(),...e};writeFileSync(It(),JSON.stringify(n,null,2)+`
|
|
3
|
+
`,"utf-8");}async function Po(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,o=>{t.close(),n(o.trim());});})}function Oo(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function De(){let e=ge(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let o=await Po("Enter your display name: ");e.displayName=o||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=No,t=true),t&&Y(e);let n=process.env.HNCH_RELAY_URL||e.relayUrl;return n=Oo(n),{participantId:e.participantId,displayName:e.displayName,relayUrl:n,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales}}function Me(e){nn();let n={...ge()};for(let[o,r]of Object.entries(e))r===""?delete n[o]:r!==void 0&&(n[o]=r);writeFileSync(It(),JSON.stringify(n,null,2)+`
|
|
4
|
+
`,"utf-8");}var Do={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},on=new Map(Object.entries(Do).map(([e,t])=>[t,e]));function he(e){return e.role??"voter"}function G(e){let{revealedAt:t,skippedAt:n}=e;return t===void 0&&n===void 0?null:t===void 0?"skipped":n===void 0||t<=n?"revealed":"skipped"}var ze={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},rn={id:"t-shirt",cards:["XS","S","M","L","XL"]},sn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},an={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},cn={id:"risk",cards:["Low","Medium","High","Critical"]},te={[ze.id]:ze,[rn.id]:rn,[sn.id]:sn,[an.id]:an,[cn.id]:cn},dn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function Se(e){return e in dn?dn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(n=>n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var Mo="meta",ke="settings",ko="participants",$o="rounds",Bo=["roomUuid","createdAt","createdBy","sessionEndedAt"],Ho=["name","defaultScale","hostParticipantId"],Uo=["displayName","joinedAt","role","leftAt","removedBy"],jo=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt"];function Qe(e){return e.getMap(Mo)}function Ke(e){return e.getMap(ke)}function Xe(e){return e.getMap(ko)}function Tt(e){return e.getArray($o)}function Ze(e,t){let n={};for(let o of t){let r=e.get(o);r!==void 0&&(n[o]=r);}return n}function Lo(e){return Ze(Qe(e),Bo)}function _o(e){return Ze(Ke(e),Ho)}function Fo(e){let t=Xe(e),n=[];return t.forEach((o,r)=>{let s=Ze(o,Uo);n.push({id:r,...s});}),n.sort((o,r)=>o.joinedAt-r.joinedAt||o.id.localeCompare(r.id)),n}function Vo(e){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}function Yo(e){let t=Ze(e,jo),n=e.get("votes"),o=n?Vo(n):{};return {...t,votes:o}}function Jo(e){let t=Tt(e),n=[];return t.forEach(o=>{n.push(Yo(o));}),n}function z(e){return {meta:Lo(e),settings:_o(e),participants:Fo(e),rounds:Jo(e)}}function ln(e,t){if(Qe(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let n=Qe(e);n.set("roomUuid",t.roomUuid),n.set("createdAt",t.createdAt),n.set("createdBy",t.participantId);let o=Ke(e);t.sessionName!==void 0&&o.set("name",t.sessionName),o.set("defaultScale",t.defaultScale),o.set("hostParticipantId",t.participantId);let r=new Ie.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),Xe(e).set(t.participantId,r);});}function et(e,t){e.transact(()=>{let n=Xe(e),o=n.get(t.participantId),r=o??new Ie.Map;r.set("displayName",t.displayName),o===void 0&&r.set("joinedAt",Date.now()),r.delete("leftAt"),r.delete("removedBy"),o===void 0&&n.set(t.participantId,r);});}function Te(e,t){e.transact(()=>{let n=Ke(e);for(let[o,r]of Object.entries(t))r===void 0?n.delete(o):n.set(o,r);});}function Et(e,t,n){e.transact(()=>{let o=Xe(e),r=o.get(t),s=r??new Ie.Map;s.set("displayName",n.displayName),s.set("joinedAt",n.joinedAt),n.role!==void 0&&s.set("role",n.role),r===void 0&&o.set(t,s);});}function At(e,t){let n=t.scale??Ke(e).get("defaultScale");if(!n)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let o=new Ie.Map;o.set("id",t.id),o.set("createdAt",t.createdAt),o.set("createdBy",t.createdBy),o.set("scale",n),t.title!==void 0&&o.set("title",t.title),t.description!==void 0&&o.set("description",t.description),t.ticketId!==void 0&&o.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&o.set("parentRoundId",t.parentRoundId),o.set("timerStartedAt",t.createdAt),o.set("votes",new Ie.Map),Tt(e).push([o]);}),t.id}function un(e,t,n){let o=$e(e,t);if(!o)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{n.title!==void 0&&o.set("title",n.title),n.description!==void 0&&o.set("description",n.description);});}function $e(e,t){let n=Tt(e);for(let o=0;o<n.length;o+=1){let r=n.get(o);if(r.get("id")===t)return r}}function pn(e,t,n,o){let r=$e(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(n,o);});}function fn(e,t,n){let o=$e(e,t);if(!o)throw new Error(`clearVote: round ${t} not found`);o.get("revealedAt")===void 0&&e.transact(()=>{o.get("votes").delete(n);});}function Nt(e,t,n){let o=$e(e,t);if(!o)throw new Error(`revealRound: round ${t} not found`);if(o.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{o.set("revealedAt",n);});}function mn(e,t,n){let o=$e(e,t);if(!o)throw new Error(`skipRound: round ${t} not found`);if(o.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(o.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{o.set("skippedAt",n);});}function gn(e){e.transact(()=>{Qe(e).set("sessionEndedAt",Date.now());});}function X(e){let{rounds:t}=e;if(t.length===0)return null;for(let n=t.length-1;n>=0;n-=1){let o=t[n];if(o.revealedAt===void 0)return o}return t.at(-1)}function hn(e){let t=Object.values(e.votes);return t.length<2?false:t.every(n=>n===t[0])}var Sn="PBKDF2",Wo="SHA-256",xn=new TextEncoder;function qo(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function xe(e,t){let n=await crypto.subtle.importKey("raw",xn.encode(e),Sn,false,["deriveBits"]),o=await crypto.subtle.deriveBits({name:Sn,salt:xn.encode(t),iterations:1e5,hash:Wo},n,256);return qo(o)}var wn="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(wn.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${wn.length}`);function Pt(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function yn(e,t=true){let n=Pt(e);return !t||n.length!==6?n:`${n.slice(0,3)}-${n.slice(3)}`}function tt(e,t,n){if(e.startsWith("custom-")){let r=(n??[]).find(s=>s.id===e);return r?{id:r.id,cards:r.cards}:void 0}let o=te[e];if(o){let r=(t??{})[e]??[];if(r.length===0)return o;let s=o.cards.filter((p,a)=>!r.includes(a));return s.length===0?void 0:{id:e,cards:s}}}function nt(e,t){let n=Object.keys(te).map(r=>tt(r,e,t)).filter(r=>r!==void 0),o=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...n,...o]}async function vn(e,t){let n=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!n.ok)throw new Error(`POST /rooms failed: ${n.status}`);return await n.json()}async function Be(e,t){let n=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(n.status===404){let o=await n.json().catch(()=>null);throw new Error(`Room not found: ${o?.reason??"unknown-room"}`)}if(!n.ok)throw new Error(`GET /rooms/:code failed: ${n.status}`);return await n.json()}async function Ot(e,t,n){let o=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:n})});if(!o.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${o.status}`)}function Cn(e){let n=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,o={did:e.deviceId};e.passwordHash!==void 0&&(o.pw=e.passwordHash);let r=new WebsocketProvider(n,e.roomUuid,e.doc,{params:o,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:zo}),s=u=>{e.onStatusChange?.(u.status);},p=u=>{if(u===null)return;let i=on.get(u.code);i!==void 0&&(e.onRejection?.(i),r.shouldConnect=false,r.disconnect());};r.on("status",s),r.on("connection-close",p);let a=false,l=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(u){if(u.passwordHash===l)return;l=u.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let c={did:r.params.did??""};l!==void 0&&(c.pw=l),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 Qo=5e3;function bn(e,t,n){let o=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(ke).get("hostParticipantId")}function a(){r!==null&&(clearTimeout(r),r=null),o=null;}function l(){let i=p(),c=o;if(o=null,!c||i!==c)return;let h=s();if(h.has(i))return;let E=[...h].toSorted();if(E.length===0)return;let P=E[0];P===n&&Te(e,{hostParticipantId:P});}function u(){let i=p();if(!i)return;if(s().has(i)){a();return}o!==i&&(a(),o=i,r=setTimeout(()=>{r=null,l();},Qo));}return t.on("change",u),e.getMap(ke).observe(u),u(),{stop(){a(),t.off("change",u),e.getMap(ke).unobserve(u);}}}async function Tn(e){let t,n=await vn(e.relayUrl);e.password&&(t=await xe(e.password,n.uuid),await Ot(e.relayUrl,n.uuid,t));let o=new Ie.Doc,r=new Awareness(o),s=Date.now();return ln(o,{roomUuid:n.uuid,createdAt:s,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??ze,...e.sessionName!==void 0&&{sessionName:e.sessionName}}),r.setLocalStateField("participantId",e.participantId),ot({doc:o,awareness:r,roomCode:n.code,roomUuid:n.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function En(e){let t=await Be(e.relayUrl,e.roomCode),n;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");n=await xe(e.password,t.uuid);}let o=new Ie.Doc,r=new Awareness(o);return et(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),ot({doc:o,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:n,onRejection:e.onRejection})}function ot(e){let{doc:t,awareness:n,participantId:o,relayUrl:r,roomUuid:s}=e,p=new Set,a=new Set,l=new Set,u=Cn({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:o,passwordHash:e.passwordHash,awareness:n,onStatusChange(d){p.forEach(m=>m(d));},onRejection(d){console.error(`Connection rejected: ${d}`),e.onRejection?.(d);}}),i=bn(t,n,o),c=()=>{a.forEach(d=>d());};t.getMap("meta").observeDeep(c),t.getMap("settings").observeDeep(c),t.getMap("participants").observeDeep(c),t.getArray("rounds").observeDeep(c);function h(){let d=new Set;return n.getStates().forEach(m=>{let v=m.participantId;typeof v=="string"&&d.add(v);}),d}let E=new Set,P=setInterval(()=>{let d=z(t),m=X(d);if(!m||m.revealedAt!==void 0||E.has(m.id))return;let v=h();if(v.size===0)return;let w=d.participants.filter(f=>v.has(f.id)&&he(f)==="voter");if(w.length===0)return;w.filter(f=>f.id in m.votes).length>=w.length&&(E.add(m.id),Nt(t,m.id,Date.now()));},250),T=t.getMap("settings").get("hostParticipantId"),I=()=>{let d=t.getMap("settings").get("hostParticipantId");d!==T&&d!==void 0&&l.forEach(m=>m(d)),T=d;};t.getMap("settings").observe(I);let H=false;return {doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return z(t)},current(){return X(z(t))},isHost(){return z(t).settings.hostParticipantId===o},onlineIds:h,vote(d){let m=X(z(t));m&&pn(t,m.id,o,d);},unvote(){let d=X(z(t));d&&fn(t,d.id,o);},reveal(){let d=X(z(t));d&&Nt(t,d.id,Date.now());},skip(){let d=X(z(t));d&&mn(t,d.id,Date.now());},newRound(d){let m=randomUUID();return At(t,{id:m,createdAt:Date.now(),createdBy:o,...d!==void 0&&{title:d}}),m},revote(){let d=X(z(t)),m=randomUUID();return At(t,{id:m,createdAt:Date.now(),createdBy:o,...d?.id!==void 0&&{parentRoundId:d.id},...d?.title!==void 0&&{title:d.title},...d?.description!==void 0&&{description:d.description},...d?.ticketId!==void 0&&{ticketId:d.ticketId}}),m},updateRoundDescriptor(d,m){un(t,d,m);},updateName(d){Te(t,{name:d});},updateScale(d){Te(t,{defaultScale:d});},updateDisplayName(d){let w=z(t).participants.find(M=>M.id===o)?.joinedAt??Date.now();Et(t,o,{displayName:d,joinedAt:w});},async updateAccess(d,m){let v=null;if(d==="password"){if(!m)throw new Error("Password required for password mode");v=await xe(m,s);}await Ot(r,s,v),u.updateCredentials({passwordHash:v});},handoffHost(d){if(!this.isHost())throw new Error("Only the current host can hand off");if(!h().has(d))throw new Error("Target participant is not online");if(!z(t).participants.some(M=>M.id===d))throw new Error("Target participant does not exist");Te(t,{hostParticipantId:d});},toggleRole(){let m=z(t).participants.find(f=>f.id===o),w=he(m??{})==="viewer"?"voter":"viewer",M=m?.joinedAt??Date.now();Et(t,o,{displayName:m?.displayName??"",joinedAt:M,role:w});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");gn(t);},onChange(d){return a.add(d),()=>a.delete(d)},onStatusChange(d){return p.add(d),()=>p.delete(d)},onHostChange(d){return l.add(d),()=>l.delete(d)},disconnect(){H||(H=true,clearInterval(P),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),u.disconnect());}}}function An(e){let t=Pt(e);return t===""?null:t}var or=1440*60*1e3;function Mt(){return join(Oe(),"last-session.json")}function rr(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 Pn(){let e=Mt();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !rr(t)||Date.now()-t.lastSeenAt>or?(F(),null):t}catch{return F(),null}}function rt(e){let t=Oe();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let n=Mt();writeFileSync(n,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{encoding:"utf-8",mode:384}),chmodSync(n,384);}function F(){let e=Mt();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function st(e){let t=true;try{await e.clearLastSession();}catch(n){t=false,e.logger.error(`Failed to clear cached session: ${n instanceof Error?n.message:String(n)}`);}return t?e.logger.error("Session expired (room no longer exists). Cached session cleared."):e.logger.error("Session expired. Could not delete ~/.config/hnch/last-session.json \u2014 please remove it manually."),e.exit(1)}function it(e){let t=e.doc.getMap("meta"),n=null,o=false;function r(){if(o)return;let s=t.get("sessionEndedAt");if(s==null||s===n)return;n=s;let p=t.get("createdBy"),a=p===e.localParticipantId,l=e.doc.getMap("participants"),u=e.doc.getMap("settings").get("hostParticipantId")??p,i="host";if(u){let h=l.get(u)?.get("displayName");typeof h=="string"&&h.length>0&&(i=h);}setImmediate(()=>{o||e.onEnded({isLocal:a,hostName:i,timestamp:s});});}return t.observe(r),r(),()=>{o=true,t.unobserve(r);}}var sr="@xauyxau/hnch";function at(e){return yn(e)}function ct(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function dt(e){return `npx ${sr} join ${e}`}var ir={connecting:"yellow",connected:"green",disconnected:"red"};function Mn({roomCode:e,sessionName:t,status:n,isHost:o}){let r=t?`${e} \xB7 ${t}`:e;return jsxs(Box,{borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[jsxs(Text,{bold:true,children:["hnch \xB7 ",r]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:ir[n],children:n})]})]})}function ce({items:e,onSelect:t,onClose:n,title:o}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(a=>!a.disabled),[s,p]=useState(Math.max(r,0));return useInput((a,l)=>{if(l.upArrow)p(u=>{let i=(u-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(l.downArrow)p(u=>{let i=(u+1)%e.length,c=0;for(;e[i]?.disabled&&c<e.length;)i=(i+1)%e.length,c++;return i});else if(l.return){let u=e[s];u&&!u.disabled&&t(u.value);}else l.escape&&n?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Box,{flexDirection:"column",children:e.map((a,l)=>{let u=l===s,i=a.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...u&&{color:"cyan"},dimColor:i,children:u?">":" "}),jsx(Text,{bold:u,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:n,onCancel:o,placeholder:r,isActive:s=true,mask:p=false}){useInput((i,c)=>{c.escape?o?.():c.return?n(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,l=a.length>0?a:r??"",u=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:u,children:l}),jsx(Text,{inverse:true,children:" "})]})}function Hn({mode:e,password:t,onModeChange:n,onPasswordChange:o,onClose:r}){let[s,p]=useState(e==="open"?0:1),[a,l]=useState(false);return useEffect(()=>{p(e==="open"?0:1);},[e]),useInput((u,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&&n(c),c==="password"&&l(true);}else i.escape&&r?.();},{isActive:!a}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((u,i)=>{let c=i===s,h=u===e,E=u==="open"?"Open":"Password";return jsx(Text,{inverse:c,bold:h,...h&&{color:"cyan"},children:h?`[${E}]`:` ${E} `},u)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(W,{value:t,onChange:o,onSubmit:()=>l(false),onCancel:()=>l(false),placeholder:"(required to join)",isActive:a,mask:true}),!a&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),a&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function Ln({scaleId:e,cards:t,disabledIndices:n,onOverrideChange:o,onClose:r}){let s=useMemo(()=>new Set(n),[n]),[p,a]=useState(0),l=u=>{let i=new Set(s);if(i.has(u))i.delete(u);else {if(i.size>=t.length-1)return;i.add(u);}let c=Array.from(i).toSorted((h,E)=>h-E);o(e,c);};return useInput((u,i)=>{i.leftArrow?a(c=>Math.max(0,c-1)):i.rightArrow?a(c=>Math.min(t.length-1,c+1)):u===" "?l(p):(i.return||i.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((u,i)=>{let c=i===p,h=s.has(i);return jsx(Text,{inverse:c,bold:!h,...!h&&{color:"cyan"},strikethrough:h,dimColor:h,children:u},u)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function _t({initialName:e="",initialCards:t=[],onSave:n,onCancel:o}){let r=e.length>0,[s,p]=useState(e),[a,l]=useState(t.length>0?t:[""]),[u,i]=useState(0),[c,h]=useState("editing-name"),[E,P]=useState(""),T=()=>{let d=s.trim();if(d.length===0||d.length>40){P("Name must be 1-40 characters");return}p(d),P(""),h("editing-cards");},I=()=>{let d=s.trim();if(d.length===0||d.length>40){P("Name must be 1-40 characters");return}let m=a.map(w=>w.trim()).filter(w=>w.length>0),v=Array.from(new Set(m));if(v.length<2){P("Need at least 2 unique non-empty cards");return}P(""),n(d,v);};return useInput((d,m)=>{if(c==="editing-cards"){if(m.leftArrow)i(v=>Math.max(0,v-1));else if(m.rightArrow)i(v=>{let w=v+1;return w>=a.length&&a.length<25?(l(M=>[...M,""]),w):Math.min(w,a.length-1)});else if(m.return)I();else if(m.escape)o();else if(m.tab)h("editing-name");else if(m.backspace){let v=a[u]||"";if(v.length===0){if(a.length>2){let w=a.filter((M,f)=>f!==u);l(w),i(Math.max(0,u-1));}}else {let w=[...a];w[u]=v.slice(0,-1),l(w);}}else if(d&&!m.ctrl&&!m.meta){let v=a[u]||"";if(v.length<10){let w=[...a];w[u]=v+d,l(w);}}}},{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:T,onCancel:o,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((d,m)=>{let v=m===u;return jsx(Text,{inverse:v,...!v&&{color:"cyan"},children:d.length>0?d:"\xB7"},m)})})]}),E&&jsx(Text,{color:"red",children:E}),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 pt({scales:e,selectedScaleId:t,presetOverrides:n,customScales:o=[],onSelect:r,onOverrideChange:s,onCustomScaleCreate:p,onCustomScaleEdit:a,onCustomScaleDelete:l,onClose:u,showNoneOption:i=false}){let[c,h]=useState(0),[E,P]=useState(null),[T,I]=useState("browsing"),[H,d]=useState(null),[m,v]=useState(null),w=p?[...e,{id:"__create-custom__",cards:[]}]:e,M=w.length;if(useInput((f,k)=>{if(T==="browsing"){if(k.escape){u();return}if(M===0)return;if(k.upArrow)h(b=>(b-1+M)%M);else if(k.downArrow)h(b=>(b+1)%M);else if(k.return){let b=w[c];if(!b)return;if(b.id==="__create-custom__"){I("creating");return}b.id in te?P(E===b.id?null:b.id):r(b.id);}else if(f===" "){let b=w[c];b&&b.id!=="__create-custom__"&&r(b.id);}else if(f==="e"||f==="E"){let b=w[c];a&&b?.id.startsWith("custom-")&&(d(b.id),I("editing"));}else if(f==="d"||f==="D"){let b=w[c];l&&b?.id.startsWith("custom-")&&(v(b.id),I("confirming-delete"));}}else T==="confirming-delete"&&(f==="y"||f==="Y"?(m&&l&&l(m),v(null),I("browsing")):(f==="n"||f==="N"||k.escape)&&(v(null),I("browsing")));},{isActive:T==="browsing"&&E===null||T==="confirming-delete"}),T==="creating")return jsx(_t,{onSave:(f,k)=>{p&&p(f,k),I("browsing");},onCancel:()=>I("browsing")});if(T==="editing"&&H){let f=o?.find(b=>b.id===H);if(e.find(b=>b.id===H)&&f)return jsx(_t,{initialName:f.label,initialCards:f.cards,onSave:(b,L)=>{a&&a(H,b,L),d(null),I("browsing");},onCancel:()=>{d(null),I("browsing");}})}if(T==="confirming-delete"&&m){let f=w.find(b=>b.id===m),k=f?Se(f.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 w.length===0?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"(no scales available)"}),jsx(Text,{dimColor:true,children:"esc back"})]}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{flexDirection:"column",children:w.map((f,k)=>{let b=k===c,L=f.id===t,oe=E===f.id,Z=f.id in te,ee=f.id==="__create-custom__",re=f.cards.join(", "),g=i&&f.id==="",C=g?"(none)":ee?"[+ Create custom scale]":Se(f.id);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...b&&{color:"cyan"},children:b?">":" "}),jsx(Text,{bold:b,children:C}),!g&&!ee&&jsx(Text,{dimColor:true,children:re}),L&&jsx(Text,{color:"cyan",children:"[current]"})]}),oe&&!g&&!ee&&jsx(Box,{paddingLeft:2,children:Z?jsx(Ln,{scaleId:f.id,cards:te[f.id]?.cards??[],disabledIndices:n?.[f.id]??[],onOverrideChange:s,onClose:()=>P(null)}):null})]},f.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let f=c<w.length?w[c]:null;return f?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${a?" [e] edit":""}${l?" [d] delete":""} esc back`:f&&f.id in te?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function yr(e,t){return t?[...e]:e.filter(n=>n.value==="display-name")}function _n({sessionName:e,displayName:t,currentScale:n,accessMode:o,presetOverrides:r,customScales:s,isHost:p=true,onChangeName:a,onChangeScale:l,onChangeDisplayName:u,onChangeAccess:i,onClose:c}){let[h,E]=useState(r??{}),P=useMemo(()=>nt(h,s),[h,s]),[T,I]=useState("main-menu"),[H,d]=useState(e??""),[m,v]=useState(t),[w,M]=useState(o==="password"?"password":"open"),[f,k]=useState(""),[b,L]=useState(false),oe=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Se(n.id)}]`},{label:"Access",value:"access",detail:`[${o==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],Z=yr(oe,p);function ee(O){!p&&O!=="display-name"||(O==="room-name"?(d(e??""),I("editing-room-name")):O==="scale"?I("picking-scale"):O==="access"?I("picking-access"):O==="display-name"&&(v(t),I("editing-display-name")));}function re(O){let D=O.trim()===""?void 0:O.trim();a(D),I("main-menu");}function g(O){let D=O.trim();D.length>0&&(u(D),process.nextTick(()=>Y({displayName:D}))),I("main-menu");}function C(O){let D=P.find(_=>_.id===O);D&&l(D),I("main-menu");}function A(O,D){let _={...h};D.length===0?delete _[O]:_[O]=D,E(_),Y({presetOverrides:Object.keys(_).length>0?_:void 0});}async function B(O,D){L(true);try{await i(O,D),M(O),k(O==="password"?D??"":"");}catch(_){console.error(`Failed to update access: ${_}`);}finally{L(false),I("main-menu");}}return T==="main-menu"?jsx(ce,{title:"\u2500\u2500 Settings \u2500\u2500",items:Z,onSelect:ee,onClose:c}):T==="editing-room-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Room name: "}),jsx(W,{value:H,onChange:d,onSubmit:re,onCancel:()=>I("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):T==="editing-display-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(W,{value:m,onChange:v,onSubmit:g,onCancel:()=>I("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):T==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(pt,{scales:P,selectedScaleId:n.id,presetOverrides:h,onSelect:C,onOverrideChange:A,onClose:()=>I("main-menu")})]}):T==="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(Hn,{mode:w,password:f,onModeChange:O=>{O==="open"&&B("open");},onPasswordChange:k,onClose:()=>I("main-menu")})]}):jsx(Box,{})}function gt({participants:e,onlineIds:t,hostId:n,votes:o,revealed:r,participantId:s}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(p=>{let a=t.has(p.id),l=a?"\u25CF":"\u25CB",u=a?"green":"gray",i=p.id===n,c=he(p)==="viewer",h=p.id===s,E=p.id in o,P=c?" (viewer)":r?o[p.id]?` \u2192 ${o[p.id]}`:"":E?" \u2713":" \xB7",T=h&&!c&&!(r&&o[p.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:u,children:l}),jsxs(Text,{children:[p.displayName,i?" (host)":""]}),T?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:c?"gray":E?"green":"gray",children:P})]},p.id)})]})}var vr=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function Vn({onPick:e,onClose:t}){return jsx(ce,{title:"Host Actions",items:vr,onSelect:e,onClose:t})}function ht({roomCode:e,onPick:t,onClose:n}){let o=[{label:"Copy code",value:"code",detail:at(e)},{label:"Copy share link",value:"url",detail:ct(e)},{label:"Copy npx command",value:"npx",detail:dt(e)}];return jsx(ce,{title:"Share",items:o,onSelect:r=>t(r),onClose:n})}function Yn(e){let t=Object.values(e).map(i=>parseFloat(i)).filter(i=>!isNaN(i)).toSorted((i,c)=>i-c);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let o=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 l=Math.max(...a.values()),u=p.length>0?Math.round(l/p.length*100):0;return {average:o.toFixed(1),median:s.toFixed(1),agreement:`${u}%`}}function Vt(e,t){let n=Math.floor((t-e)/1e3),o=Math.floor(n/60),r=n%60;return `${o}:${r.toString().padStart(2,"0")}`}function Jn(e,t){if(G(e)==="skipped"){let a=e.title?` ${e.title}`:"",l=e.ticketId?` [${e.ticketId}]`:"";return `Round ${t}:${a}${l} \u2014 Skipped`}let n=new Map;for(let a of Object.values(e.votes))n.set(a,(n.get(a)??0)+1);let o=[...n.entries()].toSorted((a,l)=>l[1]-a[1]||a[0].localeCompare(l[0])).map(([a,l])=>`${a}\xD7${l}`).join(", "),r=e.title?` ${e.title}`:"",s=e.ticketId?` [${e.ticketId}]`:"",p=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${Vt(e.timerStartedAt,e.revealedAt)}`:"";return `Round ${t}:${r}${s} \u2014 ${o||"(no votes)"}${p}`}function Wn({projection:e,onlineIds:t,isHost:n,participantId:o,rounds:r,currentRound:s,settingsOpen:p,onStartRound:a,onNewRound:l,onRevote:u,onOpenSettings:i,onHandoffHost:c,onEndSession:h,onShare:E,shareOpen:P,onSetShareOpen:T,roomCode:I,confirmingQuit:H,myRole:d,onToggleRole:m,roundTitlePromptActive:v,roundTitleInput:w,onRoundTitleChange:M,onRoundTitleSubmit:f,onRoundTitleCancel:k,descriptorPromptActive:b,descriptorInput:L,onDescriptorChange:oe,onDescriptorSubmit:Z,onDescriptorCancel:ee,onEditDescriptor:re}){let[g,C]=St.useState("idle"),[A,B]=St.useState(null),[O,D]=St.useState(false),[_,me]=St.useState(false);useEffect(()=>{n||(C("idle"),B(null),D(false),me(false));},[n]),useInput(S=>{if(S==="c"||S==="C"){T(true);return}if(S==="w"||S==="W"){m();return}n&&((S==="e"||S==="E")&&i(),(S==="s"||S==="S")&&a(),(S==="h"||S==="H")&&C("picking"),(S==="m"||S==="M")&&D(true),s!==null&&G(s)!==null&&((S==="n"||S==="N")&&l(),(S==="v"||S==="V")&&G(s)!=="skipped"&&u(),(S==="t"||S==="T")&&re()));},{isActive:!p&&!H&&g==="idle"&&!v&&!O&&!_&&!P&&!b}),useInput((S,K)=>{S==="y"||S==="Y"?(h(),me(false)):(S==="n"||S==="N"||K.escape)&&me(false);},{isActive:_});let se=e.participants.filter(S=>S.id!==o&&t.has(S.id));useInput(S=>{if(g==="picking"){let K=parseInt(S,10);!isNaN(K)&&K>=1&&K<=se.length?(B(se[K-1].id),C("confirming")):(S==="Escape"||S==="q"||S==="Q")&&C("idle");}},{isActive:g==="picking"}),useInput(S=>{g==="confirming"&&A&&(S==="y"||S==="Y"?(c(A),C("idle"),B(null)):(S==="n"||S==="N"||S==="Escape")&&(C("idle"),B(null)));},{isActive:g==="confirming"});let Ye=r.length>0,Pe=r.filter(S=>G(S)!==null),Je=s!==null?Pe.slice(0,-1):Pe;return O?jsx(Vn,{onPick:S=>{D(false),S==="end-session"&&me(true);},onClose:()=>D(false)}):P?jsx(ht,{roomCode:I,onPick:S=>{T(false),E(S);},onClose:()=>T(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:Ye?"Session":"Waiting for participants..."}),!Ye&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(gt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:o}),s!==null&&G(s)!==null&&jsx(Ir,{projection:e,round:s,rounds:r}),Je.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),Je.map(S=>{let K=r.indexOf(S)+1;return jsx(Text,{dimColor:true,children:Jn(S,K)},S.id)})]}),g==="picking"&&se.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),se.map((S,K)=>jsxs(Text,{children:["[",K+1,"] ",S.displayName]},S.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),g==="picking"&&se.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"&&A&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(S=>S.id===A)?.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:w,onChange:M,onSubmit:f,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:L,onChange:oe,onSubmit:Z,onCancel:ee,placeholder:"Enter to save",isActive:b})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),_&&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&&!_&&jsxs(Box,{gap:2,children:[n?jsx(Fragment,{children:s!==null&&G(s)!==null?jsxs(Fragment,{children:[G(s)!=="skipped"&&jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[t] Edit title"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),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 Ir({projection:e,round:t,rounds:n}){let o=n.indexOf(t)+1,r=t.title?` \u2014 ${t.title}`:"",s=t.ticketId?` [${t.ticketId}]`:"";if(G(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsxs(Text,{bold:true,children:["Round ",o,r,s," \u2014 Skipped"]})});let p=Yn(t.votes),a=new Map(e.participants.map(i=>[i.id,i.displayName])),l=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?Vt(t.timerStartedAt,t.revealedAt):null,u=Object.values(t.votes)[0];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{bold:true,children:["Round ",o,r,s," \u2014 Results"]}),hn(t)&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",u]}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:2,children:[jsx(Text,{bold:true,underline:true,children:"Name".padEnd(20)}),jsx(Text,{bold:true,underline:true,children:"Estimate".padEnd(10)})]}),Object.entries(t.votes).map(([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})]}),l!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",l]})]})]})}function zn({scale:e,selected:t,onSelect:n,onClear:o,disabled:r}){let[s,p]=useState(0);return useInput((a,l)=>{if(!r)if(l.leftArrow)p(u=>Math.max(0,u-1));else if(l.rightArrow)p(u=>Math.min(e.cards.length-1,u+1));else if(l.return){let u=e.cards[s];u===t?o():n(u);}else (l.backspace||l.delete)&&o();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((a,l)=>{let u=l===s,i=a===t;return jsx(Text,{inverse:u,bold:i,...i&&{color:"cyan"},children:i?`[${a}]`:` ${a} `},a)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function Pr(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function Qn({projection:e,round:t,onlineIds:n,isHost:o,myId:r,myRole:s,elapsedMs:p,roomCode:a,shareOpen:l,settingsOpen:u,onVote:i,onClearVote:c,onReveal:h,onSkip:E,onToggleRole:P,onShare:T,onSetShareOpen:I,onOpenSettings:H,confirmingQuit:d}){if(useInput(f=>{if(f==="e"||f==="E"){H();return}if(f==="c"||f==="C"){I(true);return}o&&(f==="r"||f==="R")&&h(),o&&(f==="s"||f==="S")&&E(),(f==="w"||f==="W")&&P();},{isActive:!d&&!u&&!l}),l)return jsx(ht,{roomCode:a,onPick:f=>{I(false),T(f);},onClose:()=>I(false)});let m=t.votes[r],v=e.rounds.indexOf(t)+1,w=t.title?` \u2014 ${t.title}`:"",M=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",v,w,M]}),p!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",Pr(p)]})]}),jsxs(Box,{gap:4,children:[jsx(gt,{participants:e.participants,onlineIds:n,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(zn,{scale:t.scale,selected:m,onSelect:i,onClear:c,disabled:d})]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),o&&jsx(Text,{color:"yellow",children:"[s] Skip"}),jsxs(Text,{color:"yellow",children:["[w] ",s==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var kr=3e3;function Wt(e=kr){let[t,n]=useState(null),o=useRef(null),r=useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null);},[]),s=useCallback(a=>{r(),n(a),o.current=setTimeout(()=>{n(null),o.current=null;},e);},[r,e]),p=useCallback(()=>{r(),n(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:s,dismiss:p}}function Ur(e){let t=X(e);return !t||G(t)!==null?"lobby":"voting"}function vt({session:e,participantId:t,displayName:n,accessMode:o,presetOverrides:r,customScales:s}){let{exit:p}=useApp(),[a,l]=useState(e.projection()),[u,i]=useState("connecting"),[c,h]=useState(e.onlineIds()),[E,P]=useState(),[T,I]=useState(false),[H,d]=useState(o==="password"?"password":"open"),[m,v]=useState(n),[w,M]=useState(false),[f,k]=useState(false),[b,L]=useState(""),[oe,Z]=useState(false),[ee,re]=useState(""),[g,C]=useState(null),A=Wt(3e3),[B,O]=useState(false),D=Wt(3e3);useEffect(()=>{let R=e.onChange(()=>{l(e.projection()),h(e.onlineIds());}),V=e.onStatusChange(i),We=e.onHostChange(qe=>{let vo=e.projection().participants.find(bo=>bo.id===qe),Co=qe===t?"You are now the host":`${vo?.displayName||"Unknown"} is now the host`;A.show(Co);}),yo=setInterval(()=>{h(e.onlineIds());let qe=e.projection(),Ge=X(qe);Ge?.timerStartedAt!==void 0&&Ge.revealedAt===void 0?P(Date.now()-Ge.timerStartedAt):P(void 0);},1e3);return ()=>{R(),V(),We(),clearInterval(yo);}},[e,t,A.show]),useInput(R=>{(R==="q"||R==="Q")&&M(true);},{isActive:!T&&!w&&!f&&!oe&&!B}),useInput((R,V)=>{R==="y"||R==="Y"?(e.disconnect(),p()):(R==="n"||R==="N"||V.escape)&&M(false);},{isActive:w});let _=Ur(a),me=X(a),se=a.settings.hostParticipantId===t,Ye=a.participants.find(R=>R.id===t),Pe=he(Ye??{}),Je=useCallback(()=>{L(""),k(true);},[]),S=useCallback(R=>{k(false),L(""),e.newRound(R.trim()||void 0);},[e]),K=useCallback(()=>{k(false),L("");},[]),no=useCallback(()=>{let R=e.current();!R||R.revealedAt===void 0||(C(R.id),re(R.title??""),Z(true));},[e]),oo=useCallback(R=>{let V=g;if(Z(false),C(null),!V)return;let We=R.trim();We!==""&&e.updateRoundDescriptor(V,{title:We});},[e,g]),ro=useCallback(()=>{Z(false),C(null);},[]),so=useCallback(R=>{e.vote(R);},[e]),io=useCallback(()=>{e.unvote();},[e]),ao=useCallback(()=>{e.reveal();},[e]),co=useCallback(()=>{e.skip();},[e]),lo=useCallback(()=>{L(""),k(true);},[]),uo=useCallback(()=>{e.revote();},[e]),Qt=useCallback(()=>{e.toggleRole();},[e]),po=useCallback(R=>{e.updateName(R);},[e]),fo=useCallback(R=>{e.updateScale(R);},[e]),mo=useCallback(R=>{e.updateDisplayName(R),v(R);},[e]),go=useCallback(async(R,V)=>{await e.updateAccess(R,V),d(R);},[e]),ho=useCallback(R=>{try{e.handoffHost(R);}catch(V){console.error(`Handoff failed: ${V instanceof Error?V.message:String(V)}`);}},[e]),Kt=useCallback(()=>{I(true);},[]),So=useCallback(()=>{I(false);},[]),xo=useCallback(()=>{e.endSessionForEveryone();},[e]),Xt=useCallback(async R=>{let V=R==="code"?at(e.roomCode):R==="url"?ct(e.roomCode):dt(e.roomCode);try{await Hr.write(V),D.show("Copied!");}catch{D.show(`Copy failed \u2014 ${V}`);}},[e.roomCode,D]),Zt=a.rounds.filter(R=>G(R)!==null),wo=Zt.length>0?Zt.at(-1):null;return jsxs(Box,{flexDirection:"column",children:[jsx(Mn,{roomCode:e.roomCode,sessionName:a.settings.name,status:u,isHost:se}),A.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:A.notice})}),D.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:D.notice.startsWith("Copy failed")?"red":"green",children:D.notice})}),T?jsx(_n,{sessionName:a.settings.name,displayName:m,currentScale:a.settings.defaultScale,accessMode:H,presetOverrides:r,customScales:s,isHost:se,onChangeName:po,onChangeScale:fo,onChangeDisplayName:mo,onChangeAccess:go,onClose:So}):_==="lobby"?jsx(Wn,{projection:a,onlineIds:c,isHost:se,participantId:t,rounds:a.rounds,currentRound:wo,settingsOpen:T,onStartRound:Je,onNewRound:lo,roundTitlePromptActive:f,roundTitleInput:b,onRoundTitleChange:L,onRoundTitleSubmit:S,onRoundTitleCancel:K,onRevote:uo,onOpenSettings:Kt,onHandoffHost:ho,onEndSession:xo,onShare:Xt,shareOpen:B,onSetShareOpen:O,roomCode:e.roomCode,confirmingQuit:w,myRole:Pe,onToggleRole:Qt,descriptorPromptActive:oe,descriptorInput:ee,onDescriptorChange:re,onDescriptorSubmit:oo,onDescriptorCancel:ro,onEditDescriptor:no}):_==="voting"&&me?jsx(Qn,{projection:a,round:me,onlineIds:c,isHost:se,myId:t,myRole:Pe,elapsedMs:E,onVote:so,onClearVote:io,onReveal:ao,onSkip:co,onToggleRole:Qt,onShare:Xt,onSetShareOpen:O,shareOpen:B,settingsOpen:T,onOpenSettings:Kt,roomCode:e.roomCode,confirmingQuit:w}):null,w&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function Xn({presetOverrides:e,customScales:t}){let{exit:n}=useApp(),[o,r]=useState("main-menu"),[s,p]=useState(ge()),[a,l]=useState(s.displayName??""),[u,i]=useState(s.relayUrl??""),[c,h]=useState(s.defaultSessionName??""),[E,P]=useState(t??[]),[T,I]=useState(e??{});useInput(g=>{(g==="q"||g==="Q")&&n();},{isActive:o==="main-menu"});let H=useMemo(()=>nt(T,E),[T,E]),d=s.defaultScale,m=d?H.find(g=>g.id===d):void 0,v=[{label:"Display name",value:"display-name",detail:`[${s.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${s.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${m?Se(m.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 w(g){g==="display-name"?(l(s.displayName??""),r("editing-display-name")):g==="relay-url"?(i(s.relayUrl??""),r("editing-relay-url")):g==="default-scale"?r("picking-scale"):g==="default-session-name"?(h(s.defaultSessionName??""),r("editing-session-name")):g==="default-password"&&r("picking-default-password");}function M(g){let C=g.trim();if(C.length>0){let A={...s,displayName:C};p(A),Y({displayName:C});}r("main-menu");}function f(g){let C=g.trim();if(C.length>0){let A={...s,relayUrl:C};p(A),Y({relayUrl:C});}r("main-menu");}function k(g){let C=g.trim(),A=C.length>0?{...s,defaultSessionName:C}:{...s};C.length===0?(delete A.defaultSessionName,p(A),Me({defaultSessionName:""})):(p(A),Y({defaultSessionName:C})),r("main-menu");}function b(g){let C=g.length>0?{...s,defaultScale:g}:{...s};g.length===0?(delete C.defaultScale,p(C),Me({defaultScale:""})):(p(C),Y({defaultScale:g})),r("main-menu");}function L(g,C){let A={...T};C.length===0?delete A[g]:A[g]=C,I(A),Y({presetOverrides:Object.keys(A).length>0?A:void 0});}function oe(g){let C=g==="on",A={...s,defaultPassword:C};p(A),Y({defaultPassword:C}),r("main-menu");}function Z(g,C){let A=`custom-${randomUUID()}`,B=[...E,{id:A,label:g,cards:C}];P(B),p({...s,customScales:B}),Y({customScales:B});}function ee(g,C,A){let B=E.map(O=>O.id===g?{id:g,label:C,cards:A}:O);P(B),p({...s,customScales:B}),Y({customScales:B});}function re(g){let C=E.filter(B=>B.id!==g);P(C);let A={...s,customScales:C};s.defaultScale===g?(A.defaultScale="fibonacci",Y({customScales:C,defaultScale:"fibonacci"})):Y({customScales:C}),p(A);}if(o==="main-menu")return jsx(ce,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:v,onSelect:w,onClose:()=>n()});if(o==="editing-display-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(W,{value:a,onChange:l,onSubmit:M,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-relay-url")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Relay URL: "}),jsx(W,{value:u,onChange:i,onSubmit:f,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-session-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Default session name: "}),jsx(W,{value:c,onChange:h,onSubmit:k,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="picking-scale"){let g=[{id:"",cards:[]},...H];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(pt,{scales:g,selectedScaleId:d??"",presetOverrides:T,customScales:E,onSelect:b,onOverrideChange:L,onCustomScaleCreate:Z,onCustomScaleEdit:ee,onCustomScaleDelete:re,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(o==="picking-default-password"){let g=[{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(ce,{title:"Default password:",items:g,onSelect:oe,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function zt(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",n=>{t.close(),e(n);});})}async function qr(e){let t=await De(),n=e.scale??t.defaultScale??"fibonacci",o=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,s;r&&(s=await zt());let p=tt(n,t.presetOverrides,t.customScales);if(!p){let c=Object.keys(te).join(", ");console.error(`Unknown or fully-disabled scale: "${n}". Builtin IDs: ${c}`),process.exit(1);}let a=await Tn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:o,password:s,defaultScale:p}),l;s&&(l=await xe(s,a.roomUuid)),rt({roomCode:a.roomCode,roomUuid:a.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Room created: ${a.roomCode}`),console.error(`Share: hnch join ${a.roomCode}`),console.error("");let{waitUntilExit:u,unmount:i}=render(St.createElement(vt,{session:a,participantId:t.participantId,displayName:t.displayName,accessMode:s?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));it({doc:a.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),i();try{await F();}catch(h){console.error(`Failed to clear cached session: ${h instanceof Error?h.message:String(h)}`);}a.disconnect(),process.exit(0);}}),await u(),a.disconnect(),F(),process.exit(0);}async function Gr(e){let t=await De(),n=An(e.code);n===null&&(console.error("invalid room code"),process.exit(1));let o;e.password&&(o=await zt());let r=await Be(t.relayUrl,n),s;r.accessMode==="password"&&!e.password?s=await zt():e.password&&(s=o);let p,a=false,l=await En({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:n,password:s,onRejection(c){if(c==="unknown-room"){st({clearLastSession:F,logger:console,exit:process.exit});return}c==="room-full"&&(a=true,p?.());}}),u;s&&(u=await xe(s,l.roomUuid)),rt({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Joined room: ${l.roomCode}`),console.error("");let i=render(St.createElement(vt,{session:l,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));p=i.unmount,it({doc:l.doc,localParticipantId:t.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),p?.();try{await F();}catch(h){console.error(`Failed to clear cached session: ${h instanceof Error?h.message:String(h)}`);}l.disconnect(),process.exit(0);}}),await i.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),l.disconnect(),F(),process.exit(1)),l.disconnect(),F(),process.exit(0);}async function zr(){let e=await De(),t=Pn();t||(console.error("No recent session to resume."),process.exit(0));let n;try{n=await Be(e.relayUrl,t.roomCode);}catch(i){if((i instanceof Error?i.message:String(i)).includes("Room not found"))return await st({clearLastSession:F,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}n.accessMode==="password"&&!t.passwordHash&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),F(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let o=new Ie.Doc,r=new Awareness(o);et(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let s=false,p=false,a,l=ot({doc:o,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(i){if(i==="unknown-room"){st({clearLastSession:F,logger:console,exit:process.exit});return}i==="wrong-password"&&(s=true,a?.()),i==="room-full"&&(p=true,a?.());}});rt({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let u=render(St.createElement(vt,{session:l,participantId:e.participantId,displayName:e.displayName,accessMode:n.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));a=u.unmount,it({doc:l.doc,localParticipantId:e.participantId,onEnded:async i=>{console.error(i.isLocal?"Session ended.":`Session ended by ${i.hostName}.`),a?.();try{await F();}catch(c){console.error(`Failed to clear cached session: ${c instanceof Error?c.message:String(c)}`);}l.disconnect(),process.exit(0);}}),await u.waitUntilExit(),p&&(console.error("This room is full (max 20 participants)."),F(),process.exit(1)),s&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),F(),process.exit(0)),l.disconnect(),F(),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 o=await De(),{waitUntilExit:r}=render(St.createElement(Xn,{presetOverrides:o.presetOverrides,customScales:o.customScales}));await r(),process.exit(0);}let n={};if(e.name!==void 0&&(n.displayName=e.name),e.relayUrl!==void 0&&(n.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let o=ge();if(!tt(e.scale,o.presetOverrides,o.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(te).join(", ")}`);return}}n.defaultScale=e.scale;}e.sessionName!==void 0&&(n.defaultSessionName=e.sessionName),e.password!==void 0&&(n.defaultPassword=e.password),Me(n),console.log("Config updated.");}var to=Yr(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=>{qr(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=>{Gr(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{zr().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(),Gt=hideBin(process.argv);(Gt.length===0||Gt.length===1&&Gt[0]==="--")&&(to.showHelp(),process.exit(0));to.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xauyxau/hnch",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Pointing poker CLI for agile teams",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pointing-poker",
|
|
@@ -42,7 +42,9 @@
|
|
|
42
42
|
"prepublishOnly": "pnpm run build",
|
|
43
43
|
"typecheck": "tsc --noEmit",
|
|
44
44
|
"dev": "tsx src/index.ts",
|
|
45
|
-
"test": "vitest run"
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"format:check": "biome format .",
|
|
47
|
+
"lint": "oxlint ."
|
|
46
48
|
},
|
|
47
49
|
"dependencies": {
|
|
48
50
|
"clipboardy": "^4.0.0",
|
|
@@ -60,6 +62,7 @@
|
|
|
60
62
|
"@types/react": "^18.3.0",
|
|
61
63
|
"@types/ws": "^8.18.1",
|
|
62
64
|
"@types/yargs": "^17.0.33",
|
|
65
|
+
"ink-testing-library": "^4.0.0",
|
|
63
66
|
"tsup": "^8.3.0",
|
|
64
67
|
"tsx": "^4.19.0",
|
|
65
68
|
"typescript": "^5.5.0",
|