@banou/social 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/build/index.js +24 -24
  2. package/fkn.json +1 -1
  3. package/package.json +2 -1
package/build/index.js CHANGED
@@ -7,15 +7,15 @@ This browser reports limited detail, so the cause above is a best guess.`:``)))}
7
7
  
8
8
  `)?`image/png`:e[0]===255&&e[1]===216&&e[2]===255?`image/jpeg`:Mp(e,0,`GIF87a`)||Mp(e,0,`GIF89a`)?`image/gif`:Mp(e,0,`RIFF`)&&Mp(e,8,`WEBP`)?`image/webp`:null,Kp=e=>e?.code,qp=async(e,t)=>{for(let n of t)n!==null&&await e.delete(n.url).catch(()=>{})},Jp=async(e,t,n)=>{if(t.size>n)return{ok:!1,reason:`too-large`};if(Gp(new Uint8Array(await t.slice(0,12).arrayBuffer()))===null)return{ok:!1,reason:`kind`};try{let n=await e.put(t);return{ok:!0,picture:{url:n.url,key:n.key}}}catch(e){let t=Kp(e);return{ok:!1,reason:t===`quota`||t===`too-many`?t:`storage-unavailable`}}},Yp=async(e,t,n)=>{let r=await Jp(e.storage,n,wp[t]);if(!r.ok)return r;let i=r.picture,{outcome:a,replaced:o,applied:s}=await pp(e,t,i);return await qp(e.storage,[a.ok&&s?o:i]),a.ok&&!s?{ok:!1,reason:`not-public`}:a},Xp=async(e,t)=>{let{outcome:n,replaced:r}=await pp(e,t,null);return n.ok&&await qp(e.storage,[r]),n},Zp=async(e,t,n)=>{if(t===null)return null;try{let r=await e.get(t.url,t.key);if(r.size>n)return null;let i=new Uint8Array(await r.arrayBuffer()),a=Gp(i);return i.length>n||a===null?null:{bytes:i,kind:a}}catch{return null}},Qp=async(e,t,n)=>{let r=await Zp(e,t,n);return r===null?null:new Blob([r.bytes.slice()],{type:r.kind})},$p=e=>`${e.url}#${e.key}`,em=e=>{if(typeof e!=`string`)return null;let t=e.indexOf(`#`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return gf(n,200)===n?yf({url:n,key:r})??null:null},tm=e=>{let t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode(...e.subarray(n,n+32768)));return btoa(t.join(``))},nm=async(e,t,n)=>{let r=await Zp(e,t,n);return r===null?null:`data:${r.kind};base64,${tm(r.bytes)}`},rm=[.86,.72,.58,.44],im=6,am=33554432,om=4194304,sm=async(e,t,n,r)=>{let i=jp(n),a=e===`image/gif`?zp(t):Up(t);if(a===null)return{ok:!1,reason:`kind`};if(a.length>i.maxBytes)return{ok:!1,reason:`too-large`};let o=new Blob([a.slice()],{type:e}),s;try{s=await r.decode(o)}catch{return{ok:!1,reason:`kind`}}try{let{width:e,height:t}=s;return e>0&&t>0?Math.max(e,t)>i.animatedSide?{ok:!1,reason:`too-large`}:{ok:!0,picture:{blob:o,width:e,height:t,animated:!0}}:{ok:!1,reason:`kind`}}finally{r.release?.(s.source)}},cm=async(e,t,n)=>{let r=jp(t),i=Gp(new Uint8Array(await e.slice(0,12).arrayBuffer()));if(i===`image/gif`||i===`image/webp`){if(e.size>r.maxBytes){let t=new Uint8Array(await(e.size<=am?e:e.slice(0,om)).arrayBuffer());if(Wp(t)||i===`image/webp`&&e.size>am&&t.length>=21&&Mp(t,12,`VP8X`)&&t[20]&2)return{ok:!1,reason:`too-large`}}else{let r=new Uint8Array(await e.arrayBuffer());if(Wp(r))return sm(i,r,t,n)}}let a;try{a=await n.decode(e)}catch{return{ok:!1,reason:`kind`}}let{source:o,width:s,height:c}=a;try{if(!(s>0&&c>0))return{ok:!1,reason:`kind`};let e=Math.min(1,r.side/Math.max(s,c)),t={width:Math.max(1,Math.round(s*e)),height:Math.max(1,Math.round(c*e))},i=`image/webp`;for(let e=0;e<im;e++){for(let e of rm){let a=await n.encode(o,t.width,t.height,i,e);if(a.type!==i&&i===`image/webp`&&(i=`image/jpeg`,a=await n.encode(o,t.width,t.height,i,e)),a.type!==i)return{ok:!1,reason:`kind`};if(a.size<=r.staticBytes)return{ok:!0,picture:{blob:a,...t}}}t={width:Math.max(1,Math.round(t.width*.75)),height:Math.max(1,Math.round(t.height*.75))}}return{ok:!1,reason:`too-large`}}catch{return{ok:!1,reason:`kind`}}finally{n.release?.(o)}},lm={decode:async e=>{let t=await createImageBitmap(e,{imageOrientation:`from-image`});return{source:t,width:t.width,height:t.height}},encode:(e,t,n,r,i)=>new Promise((a,o)=>{let s=document.createElement(`canvas`);s.width=t,s.height=n;let c=s.getContext(`2d`);if(c===null)return o(Error(`social: no 2d canvas`));r===`image/jpeg`&&(c.fillStyle=`#fff`,c.fillRect(0,0,t,n)),c.imageSmoothingQuality=`high`,c.drawImage(e,0,0,t,n),s.toBlob(e=>e===null?o(Error(`social: the picture did not encode`)):a(e),r,i)}),release:e=>e.close()},um=2e3,dm=/^[A-Za-z0-9_-]{8,32}$/,fm=()=>Y(crypto.getRandomValues(new Uint8Array(12))),pm=e=>{let t=e.normalize(`NFC`).trim();return t!==``&&hf(t,{max:80,multiline:!1})===null?t:null},mm=e=>{let t=e.normalize(`NFC`).replaceAll(`\r
9
9
  `,`
10
- `).trim();return t!==``&&hf(t,{max:2e3,multiline:!0})===null?t:null},hm=e=>{if(e===void 0)return;let t=e.normalize(`NFC`).trim();if(t!==``)return hf(t,{max:120,multiline:!1})===null?t:null},gm=e=>typeof e==`string`&&dm.test(e),_m=e=>typeof e==`string`&&e.trim()===e&&e!==``&&hf(e,{max:80,multiline:!1})===null,vm=e=>typeof e==`string`&&e.trim()===e&&e!==``&&hf(e,{max:2e3,multiline:!0})===null,ym=e=>{if(e!==void 0)return typeof e!=`string`||e.trim()!==e||e===``||hf(e,{max:120,multiline:!1})!==null?null:e},bm=e=>{if(typeof e!=`object`||!e)return null;let{url:t,key:n,caption:r}=e,i=yf({url:t,key:n}),a=ym(r);return i==null||a===null?null:a===void 0?{url:i.url,key:i.key}:{url:i.url,key:i.key,caption:a}},xm=e=>e.kind===`text`?{id:e.id,kind:`text`,title:e.title,body:e.body}:{id:e.id,kind:`artwork`,title:e.title,items:e.items.map(({url:e,key:t,caption:n})=>n===void 0||n===``?{url:e,key:t}:{url:e,key:t,caption:n})},Sm=e=>{if(typeof e!=`object`||!e)return null;let{id:t,kind:n,title:r}=e;if(!gm(t)||!_m(r))return null;if(n===`text`){let{body:n}=e;return vm(n)?{id:t,kind:`text`,title:r,body:n}:null}if(n===`artwork`){let{items:n}=e;if(!Array.isArray(n)||n.length===0||n.length>4)return null;let i=[];for(let e of n){let t=bm(e);t!==null&&!i.some(e=>e.url===t.url)&&i.push(t)}return i.length>0?{id:t,kind:`artwork`,title:r,items:i}:null}return null},Cm=e=>{let t=[];for(let n of Array.isArray(e)?e:[]){let e=Sm(n);e!==null&&!t.some(t=>t.id===e.id)&&t.length<6&&t.push(e)}return t},wm=e=>{let t=new Set;for(let n of Array.isArray(e)?e:[])if(gm(n)&&t.add(n),t.size>=12)break;return[...t]},Tm=new Set([`public`,`friends`,`off`]),Em=e=>{if(typeof e!=`object`||!e)return null;let{id:t,kind:n,title:r,level:i}=e;if(!gm(t)||!_m(r)||typeof i!=`string`||!Tm.has(i))return null;if(n===`text`){let{body:n}=e;return vm(n)?{id:t,kind:`text`,title:r,body:n,level:i}:null}if(n===`artwork`){let{items:n}=e;if(!Array.isArray(n)||n.length>4)return null;let a=[];for(let e of n){if(typeof e!=`object`||!e)continue;let{picture:t,caption:n}=e,r=yf(t),i=ym(n);r!=null&&i!==null&&!a.some(e=>e.picture.url===r.url)&&a.push(i===void 0?{picture:r}:{picture:r,caption:i})}return{id:t,kind:`artwork`,title:r,items:a,level:i}}return null},Dm=e=>{let t=[];for(let n of Array.isArray(e.profile.panels?.value)?e.profile.panels.value:[]){let e=Em(n);e!==null&&!t.some(t=>t.id===e.id)&&t.length<6&&t.push(e)}return t},Om=e=>e.level===`off`?null:e.kind===`text`?{id:e.id,kind:`text`,title:e.title,body:e.body}:e.items.length===0?null:{id:e.id,kind:`artwork`,title:e.title,items:e.items.map(({picture:e,caption:t})=>t===void 0?{url:e.url,key:e.key}:{url:e.url,key:e.key,caption:t})},km=e=>Dm(e).filter(e=>e.level===`public`).map(Om).filter(e=>e!==null),Am=e=>Dm(e).filter(e=>e.level===`friends`).map(Om).filter(e=>e!==null),jm=e=>Dm(e).filter(e=>Om(e)!==null).map(e=>e.id),Mm=e=>e.kind===`artwork`?e.items.map(e=>e.picture):[],Nm=async(e,t)=>{let n=pm(t.title);if(n===null)return{ok:!1,reason:`title`};let r=mm(t.body);if(r===null)return{ok:!1,reason:`body`};let i=!1,a=await Z(e,e=>{let a=Dm(e);return a.length>=6?(i=!0,{}):{panels:[...a,{id:fm(),kind:`text`,title:n,body:r,level:t.level}]}});return i?{ok:!1,reason:`full`}:a},Pm=async(e,t)=>{let n=pm(t.title);if(n===null)return{ok:!1,reason:`title`};let r=!1,i=await Z(e,e=>{let i=Dm(e);return i.length>=6?(r=!0,{}):{panels:[...i,{id:fm(),kind:`artwork`,title:n,items:[],level:t.level}]}});return r?{ok:!1,reason:`full`}:i},Fm=async(e,t,n)=>{let r=pm(n.title);if(r===null)return{ok:!1,reason:`title`};let i=mm(n.body);if(i===null)return{ok:!1,reason:`body`};let a=!1,o=await Z(e,e=>{let n=Dm(e),o=n.findIndex(e=>e.id===t&&e.kind===`text`);if(o<0)return a=!0,{};let s=[...n];return s[o]={...n[o],title:r,body:i},{panels:s}});return a?{ok:!1,reason:`not-found`}:o},Im=async(e,t,n)=>{let r=pm(n.title);if(r===null)return{ok:!1,reason:`title`};let i={};for(let[e,t]of Object.entries(n.captions)){let n=hm(t);if(n===null)return{ok:!1,reason:`caption`};i[e]=n}let a=!1,o=await Z(e,e=>{let n=Dm(e),o=n.findIndex(e=>e.id===t&&e.kind===`artwork`);if(o<0)return a=!0,{};let s=n[o],c=s.items.map(e=>{if(!Object.hasOwn(i,e.picture.url))return e;let t=i[e.picture.url];return t===void 0?{picture:e.picture}:{picture:e.picture,caption:t}}),l=[...n];return l[o]={...s,title:r,items:c},{panels:l}});return a?{ok:!1,reason:`not-found`}:o},Lm=async(e,t,n)=>Z(e,e=>{let r=Dm(e),i=r.findIndex(e=>e.id===t),a=i+n;if(i<0||a<0||a>=r.length)return{};let o=[...r];return[o[i],o[a]]=[o[a],o[i]],{panels:o}}),Rm=async(e,t,n)=>{let r=[],i=await Z(e,e=>{let i=Dm(e),a=i.findIndex(e=>e.id===t);if(a<0)return{};let o=i[a];if(o.level===n)return{};let s=o.level===`public`&&n!==`public`||o.level===`friends`&&n===`off`,c=[...i];return o.kind===`artwork`&&s&&o.items.length>0?(r=Mm(o),c[a]={...o,items:[],level:n}):c[a]={...o,level:n},{panels:c}});return{outcome:i,dropped:i.ok?r:[]}},zm=async(e,t)=>{let n=[],r=await Z(e,e=>{let r=Dm(e),i=r.find(e=>e.id===t);return i===void 0?{}:(n=Mm(i),{panels:r.filter(e=>e.id!==t)})});return{outcome:r,dropped:r.ok?n:[]}},Bm=async(e,t,n,r)=>{let i=hm(r);if(i===null)return{ok:!1,reason:`caption`};let a=await Jp(e.storage,n,Op);if(!a.ok)return a;let o=null,s=await Z(e,e=>{let n=Dm(e),r=n.findIndex(e=>e.id===t&&e.kind===`artwork`);if(r<0)return o=`not-found`,{};let s=n[r];if(s.level===`off`)return o=`off`,{};if(s.items.length>=4)return o=`items-full`,{};let c=i===void 0?{picture:a.picture}:{picture:a.picture,caption:i},l=[...n];return l[r]={...s,items:[...s.items,c]},{panels:l}});return(!s.ok||o!==null)&&await qp(e.storage,[a.picture]),o===null?s:{ok:!1,reason:o}},Vm=async(e,t,n)=>{let r=[],i=await Z(e,e=>{let i=Dm(e),a=i.findIndex(e=>e.id===t&&e.kind===`artwork`);if(a<0)return{};let o=i[a],s=o.items.find(e=>e.picture.url===n);if(s===void 0)return{};r=[s.picture];let c=[...i];return c[a]={...o,items:o.items.filter(e=>e.picture.url!==n)},{panels:c}});return{outcome:i,dropped:i.ok?r:[]}},Hm=Symbol.for(`pv`),Um=0;Array.isArray;function Q(e,t,n,r,i,a){t||={};var o,s,c=t;if(`ref`in c&&typeof e!=`function`)for(s in c={},t)s==`ref`?o=t[s]:c[s]=t[s];var l={type:e,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:Hm,__v:--Um,__i:-1,__u:0};return(i||a)&&(l.__source=i,l.__self=a),W.vnode&&W.vnode(l),l}var Wm=({size:e=18})=>Q(`svg`,{width:e,height:e,viewBox:`0 0 20 20`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2.25`,y:`2.25`,width:`15.5`,height:`15.5`}),Q(`path`,{d:`M2.25 10h8.5V2.25`}),Q(`rect`,{x:`11.5`,y:`11.5`,width:`3.75`,height:`3.75`,fill:`currentColor`,stroke:`none`})]}),Gm=({id:e})=>{switch(e){case`overview`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`2`,width:`5`,height:`5`}),Q(`rect`,{x:`9`,y:`2`,width:`5`,height:`5`}),Q(`rect`,{x:`2`,y:`9`,width:`5`,height:`5`}),Q(`rect`,{x:`9`,y:`9`,width:`5`,height:`5`})]});case`customize`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`path`,{d:`M2 4h12M2 8h12M2 12h12`}),Q(`rect`,{x:`4`,y:`2.5`,width:`2.5`,height:`3`,fill:`currentColor`}),Q(`rect`,{x:`9.5`,y:`6.5`,width:`2.5`,height:`3`,fill:`currentColor`}),Q(`rect`,{x:`5`,y:`10.5`,width:`2.5`,height:`3`,fill:`currentColor`})]});case`friends`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2.5`,y:`3`,width:`4.5`,height:`4.5`}),Q(`path`,{d:`M1.5 13.5V10h6.5v3.5`}),Q(`rect`,{x:`9.5`,y:`4`,width:`4`,height:`4`}),Q(`path`,{d:`M9.5 10h4.5v3.5`})]});case`messages`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`path`,{d:`M2 2.5h12v9H6.5L3 14.5v-3H2z`}),Q(`path`,{d:`M5 6h6M5 8.5h4`})]});case`inbox`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`3`,width:`12`,height:`10`}),Q(`path`,{d:`M2 8.5h3.5l1.5 2h2l1.5-2H14`})]});case`apps`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`2.5`,width:`12`,height:`11`}),Q(`path`,{d:`M2 6h12M6 6v7.5`})]});case`account`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`3`,y:`2.5`,width:`5.5`,height:`5.5`}),Q(`path`,{d:`M8.5 5.25H14V8M11.75 5.25V7.5`}),Q(`path`,{d:`M2.5 13.5h11`})]})}},Km=()=>Q(`svg`,{className:`social-ico`,width:13,height:13,viewBox:`0 0 14 14`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:Q(`path`,{d:`M7 11.5V3M3.5 6.5 7 3l3.5 3.5`})}),qm=()=>Q(`svg`,{className:`social-ico`,width:13,height:13,viewBox:`0 0 14 14`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:Q(`path`,{d:`M7 2.5V11M3.5 7.5 7 11l3.5-3.5`})});new URL(Vu).host;var Jm=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Ym=({children:e})=>Q(`main`,{className:`social-shell`,children:Q(`section`,{className:`social-panel`,children:[Q(`div`,{className:`social-panel-mark`,"aria-hidden":`true`,children:Q(Wm,{size:18})}),e]})}),Xm=({label:e,state:t,error:n})=>Q(`main`,{className:`social-loader-stage`,"data-social-state":t,children:Q(`div`,{className:`social-loader-box`,children:[n,Q(`div`,{className:`social-loader-mark`,"aria-hidden":`true`,children:Q(Wm,{size:24})}),Q(`div`,{className:`social-loader-brand`,children:`FKN Social`}),Q(`div`,{className:`social-loader-track`,"aria-hidden":`true`,children:Q(`div`,{className:`social-loader-bar`})}),Q(`p`,{className:`social-loader-status`,role:`status`,children:e})]})}),Zm=`Your FKN storage is locked on this device, so nothing changed. Unlock it under Security in your FKN settings, then try again.`,Qm=`Your saved friend list will not open, so nothing changed. If you downloaded your FKN data before, bring it back under Security in your FKN settings.`,$m={empty:`Pick a name.`,"too-short":`A name has at least 3 characters.`,"too-long":`A name has at most 20 characters.`,characters:`Use lowercase letters and digits, with single underscores between them.`,reserved:`That name is reserved. Try another.`,taken:`That name is taken. Try another.`,"out-of-claims":`No claimed rooms left. Unclaim one under Rooms in your FKN settings, then try again.`,busy:`That name has too many connections right now. Close other FKN Social tabs, or try again in a moment.`,unrecorded:`The name's record could not be written. Check that Messages kept is on for it under Rooms in your FKN settings, then try again.`,unavailable:`FKN rooms did not answer. Try again in a moment.`,unreachable:`FKN could not be reached. Check your connection, then try again.`,locked:Zm,reset:`Your saved identity will not open, so nothing changed. Reload the page, then enter your recovery key.`,"list-reset":Qm,newer:`This needs a newer FKN Social. Reload the page to update.`,"no-writer":`This browser keeps no site data for FKN Social. Allow site data, then reload.`,"bad-recovery-key":`That is not a recovery key. A recovery key starts with FKNS, followed by 52 letters and digits.`},eh=({reason:e})=>e===null?null:Q(`p`,{className:`social-error`,role:`alert`,children:$m[e]}),th=e=>$m[e],nh={reset:Qm,locked:Zm,unreachable:`FKN could not be reached, so nothing changed. Check your connection, then try again.`,"no-writer":`This browser keeps no site data for FKN Social. Allow site data, then reload.`,newer:`Your friend list was saved by a newer FKN Social. Reload the page to update.`},rh={"display-name":`A display name has at most 32 characters, and no control or text direction characters.`,bio:`A bio has at most ${_f.toLocaleString(`en`)} characters, and no control or text direction characters.`,links:`You can list at most 5 links.`,link:`Each link starts with https:// and has at most 200 characters.`},ih={title:`Give the panel a title of at most 80 characters, with no control or text direction characters.`,body:`Write panel text of at most ${um.toLocaleString(`en`)} characters, with no control or text direction characters.`,caption:`A caption has at most 120 characters, with no control or text direction characters.`,full:`You can have up to 6 panels. Delete one to add another.`,"items-full":`Each artwork panel holds up to 4 pictures. Remove one to add another.`,"not-found":`That panel is no longer on your page. Reload to see the latest list.`,off:`Set this panel to Friends or Public before uploading artwork.`,"sync-failed":`Your panel changed, but FKN rooms did not update yet. Reload in a moment to sync your page.`},ah=`FKN rooms did not answer, so nothing changed. Try again in a moment.`,oh={...nh,unavailable:ah,"out-of-claims":$m[`out-of-claims`],"not-public":`Your profile is set to Only me, so the picture was not saved. Reload the page.`,"too-large":`That picture is too large or could not be made small enough. Pick another.`,kind:`Pick a PNG, JPEG, GIF or WebP picture.`,quota:`Your FKN storage is full, so the picture was not published. Free some space, then try again.`,"too-many":`FKN is not accepting new files from your account right now, so the picture was not published. Try again later.`,"storage-unavailable":`FKN storage did not answer, so the picture was not published. Try again in a moment.`},sh=e=>{let t=e.replace(/[a-ln-vx-z0-9_]/g,``).length;return t*1.05+(e.length-t)*.72},ch=e=>({fontSize:`clamp(0.875rem, ${100/Math.max(1,...e.split(/\s+/).map(sh))}cqi, 1.75rem)`}),lh=e=>{e?.focus()},uh=({children:e})=>e===null?null:Q(`p`,{className:`social-error`,role:`alert`,children:e}),dh=({signKey:e,label:t=`Your identicon`,small:n=!1})=>{let{hue:r,cells:i}=ff(e);return Q(`svg`,{className:n?`social-identicon social-identicon-small`:`social-identicon`,viewBox:`0 0 6 6`,role:`img`,"aria-label":t,children:[Q(`rect`,{width:6,height:6,fill:`hsl(${r} 45% 92%)`}),i.map((e,t)=>e&&Q(`rect`,{x:.5+t%5,y:.5+Math.floor(t/5),width:1,height:1,fill:`hsl(${r} 55% 42%)`},t))]})},fh=64,ph=33554432,mh=new WeakMap,hh=(e,t)=>{let n=0;for(let t of e.values())n+=t.bytes;for(let[r,i]of e){if(e.size<=fh&&n<=ph)break;r!==t&&(e.delete(r),n-=i.bytes)}},gh=(e,t,n)=>{let r=mh.get(e);r===void 0&&(r=new Map,mh.set(e,r));let i=`${t.url}\0${t.key}\0${n}`,a=r.get(i);if(a!==void 0)return r.delete(i),r.set(i,a),a.promise;let o={bytes:0,promise:Qp(e,t,n).then(e=>e===null?(r.get(i)===o&&r.delete(i),null):(r.get(i)===o&&(o.bytes=e.size,r.delete(i),r.set(i,o),hh(r,i)),e))};return r.set(i,o),hh(r,i),o.promise},_h=(e,t,n)=>{let r=t?.url??null,i=t?.key??null,[a,o]=K({storage:null,url:null,key:null,max:0,objectUrl:null});return q(()=>{if(r===null||i===null){o(e=>e.objectUrl===null&&e.url===null?e:{storage:null,url:null,key:null,max:0,objectUrl:null});return}let t=!0,a=null;return gh(e,{url:r,key:i},n).then(s=>{let c=s===null?null:URL.createObjectURL(s);if(!t){c!==null&&URL.revokeObjectURL(c);return}a=c,o({storage:e,url:r,key:i,max:n,objectUrl:c})}),()=>{t=!1,a!==null&&URL.revokeObjectURL(a)}},[e,r,i,n]),r===null||i===null?null:a.storage===e&&a.url===r&&a.key===i&&a.max===n?a.objectUrl:void 0},vh=({signKey:e,src:t,url:n,label:r=`Your identicon`,avatarAlt:i=`Your avatar`,small:a=!1})=>{let o=a?`social-identicon social-identicon-small`:`social-identicon`;return t===void 0?Q(`span`,{className:o,"data-social-avatar-reading":!0,"aria-hidden":`true`}):t===null?Q(dh,{signKey:e,label:r,small:a}):Q(`img`,{className:`${o} social-avatar-img`,src:t,alt:i,"data-social-avatar":n})},yh={get:()=>Promise.reject(Error(`social: no storage`))},bh=({signKey:e,name:t,storage:n,avatar:r=null,small:i=!1})=>{let a=_h(n??yh,n===void 0?null:r,wp.avatar);return r===null||n===void 0?Q(dh,{signKey:e,label:`${t}'s identicon`,small:i}):Q(vh,{signKey:e,src:a,url:r.url,label:`${t}'s identicon`,avatarAlt:`${t}'s avatar`,small:i})},xh=async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},Sh=({text:e,label:t=`Copy`})=>{let[n,r]=K(null);return Q(G,{children:[Q(`button`,{type:`button`,onClick:()=>void xh(e).then(e=>r(e?`Copied`:`Copy did not work. Select the text and copy it.`)),children:t}),n!==null&&Q(`span`,{className:`social-muted`,role:`status`,"data-social-copied":n===`Copied`,children:n})]})},Ch=({url:e,site:t})=>{let[n,r]=K(!1),i=t();return Q(`div`,{className:`social-link`,"data-social-link":e,children:[Q(`div`,{className:`social-link-bar`,children:[Q(`span`,{className:`social-link-text`,children:e}),Q(`div`,{className:`social-link-actions`,children:[i!==null&&Q(`button`,{type:`button`,"data-open-link":!0,onClick:()=>void i.open(e).catch(()=>r(!0)),children:`Open`}),Q(Sh,{text:e})]})]}),n&&Q(`p`,{className:`social-muted`,children:`It did not open. Copy it instead.`})]})},wh={started:`Started`,watched:`Watched`,completed:`Finished`,rated:`Rated`},Th=Object.keys(wh),Eh=36e5,Dh={public:[],friends:[]},Oh=/^[A-Za-z0-9_-]{22}$/,kh=RegExp(`^[\\x20-\\x7e]{1,64}$`),Ah=(e,t)=>typeof e==`string`&&e!==``&&e.isWellFormed()&&hf(e,{max:t,multiline:!1})===null,jh=e=>typeof e==`string`&&gf(e,300)===e,Mh=e=>{try{return new URL(e)}catch{return null}},Nh=e=>Ah(e,100),Ph=e=>{let t=Mh(e);return t!==null&&(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e?t.host:e},Fh=(e,t)=>{let n=Mh(t);return n?.protocol!==`https:`||n.origin!==t||Mh(e)?.origin===t},Ih=({id:e,app:t,at:n,kind:r,title:i,link:a,detail:o,image:s,subject:c})=>({id:e,app:t,at:n,kind:r,title:i,link:a,...o===void 0?{}:{detail:o},...s===void 0?{}:{image:s},...c===void 0?{}:{subject:c}}),Lh=e=>{if(typeof e!=`object`||!e)return null;let{id:t,app:n,at:r,kind:i,title:a,detail:o,link:s,image:c,subject:l}=e;return typeof t!=`string`||!Oh.test(t)||!Ah(n,100)||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||typeof i!=`string`||!Object.hasOwn(wh,i)||!Ah(a,150)||!jh(s)||!Fh(s,n)||o!==void 0&&!Ah(o,40)||c!==void 0&&!jh(c)||l!==void 0&&(typeof l!=`string`||!kh.test(l))?null:Ih({id:t,app:n,at:r,kind:i,title:a,link:s,detail:o,image:c,subject:l})},Rh=e=>typeof e==`string`?e.normalize(`NFC`).trim():e,zh=(e,t,n)=>{if(typeof e!=`object`||!e)return null;let{kind:r,title:i,detail:a,link:o,image:s,subject:c}=e,l=Rh(a),u=e=>typeof e==`string`?gf(e,300)??``:e;return Lh({id:Y(crypto.getRandomValues(new Uint8Array(16))),app:t,at:n,kind:r,title:Rh(i),link:u(o),...l===void 0||l===``?{}:{detail:l},...s===void 0?{}:{image:u(s)},...c===void 0?{}:{subject:c}})},Bh=e=>{if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let e=Lh(r);if(!(e===null||t.has(e.id))&&(t.add(e.id),n.push(e),n.length===50))break}return n},Vh=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((e,t)=>t.at-e.at||(e.id<t.id?-1:+(e.id>t.id))).slice(0,50)},Hh=(e,t,n)=>[...e.public,...e.friends].filter(e=>e.app===t&&e.at>n).length,Uh=(e,t)=>({...e,public:e.public.filter(e=>!t.includes(e.id)),friends:e.friends.filter(e=>!t.includes(e.id))}),Wh=(e,t)=>({...e,public:e.public.filter(e=>e.app!==t),friends:e.friends.filter(e=>e.app!==t)}),Gh=(e,t)=>({...e,public:e.public.filter(e=>e.app!==t),friends:Vh(e.friends,e.public.filter(e=>e.app===t))}),Kh=(e,t)=>[t,...e.filter(e=>e.id!==t.id)].slice(0,50),qh=(e,t)=>t===`off`?{...e,public:[],friends:[]}:t===`friends`?{...e,public:[],friends:Vh(e.friends,e.public)}:e,Jh=/^fkn:app:[a-z0-9]+$/,Yh=e=>Jh.test(e),Xh=async(e,t)=>{if(!Yh(e))return null;let n=t?.fetch??globalThis.fetch,r=t?.apiOrigin??Uu;try{let t=await n(`${r}/v1/apps/${encodeURIComponent(e)}/keys`);if(!t.ok)return null;let i=await t.json(),a=typeof i?.name==`string`?i.name:typeof i?.list?.name==`string`?i.list.name:null;return a!==null&&Ah(a,100)?a:null}catch{return null}},Zh=e=>{let t=new Map,n=new Map;return r=>{if(!Yh(r))return Promise.resolve(null);let i=t.get(r);if(i!==void 0)return Promise.resolve(i);let a=n.get(r);if(a!==void 0)return a;let o=Xh(r,e).then(e=>(n.delete(r),e!==null&&t.set(r,e),e),()=>(n.delete(r),null));return n.set(r,o),o}};function Qh(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var $h=e=>e?`"${e}" `:``;function eg(e,t=``){if(typeof e!=`boolean`)throw TypeError($h(t)+`expected boolean, got type=`+typeof e);return e}function tg(e,t=``){if(typeof e!=`number`)throw TypeError($h(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError($h(t)+`expected integer >= 0, got `+e);return e}function ng(e,t,n=``){if(Qh(e)&&(t===void 0||e.length===t))return e;t!==void 0&&tg(t,`length`);let r=Qh(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=$h(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var rg=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function ig(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function ag(e,t){ng(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function og(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function sg(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function cg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var lg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ug(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function dg(e){for(let t=0;t<e.length;t++)e[t]=ug(e[t]);return e}var fg=lg?e=>e:dg;function pg(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function mg(e,t){if(pg(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function hg(e,t){return rg(e,`defaults`),rg(t,`opts`),Object.assign(e,t)}function gg(e,t){if(e=ng(e),t=ng(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function _g(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var vg=(e,t)=>{function n(n,...r){if(ng(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];ng(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Qh(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&ng(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);ng(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,ng(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(ng(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function yg(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(ng(t,e,`output`),n&&!xg(t))throw Error(`invalid output, must be aligned`);return t}function bg(e,t,n){tg(e),tg(t),eg(n);let r=new Uint8Array(16),i=cg(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function xg(e){return e.byteOffset%4==0}function Sg(e){return Uint8Array.from(ng(e))}var Cg=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),wg=fg(og(Cg(`expand 16-byte k`))),Tg=fg(og(Cg(`expand 32-byte k`)));function $(e,t){return e<<t|e>>>32-t}var Eg=64,Dg=16,Og=2**32-1,kg=Uint32Array.of();function Ag(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Eg),u=og(l),d=lg&&xg(i)&&xg(a),f=d?og(i):kg,p=d?og(a):kg;if(!lg){for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),fg(u),o>=Og)throw Error(`arx: counter overflow`);let f=Math.min(Eg,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}return}for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Og)throw Error(`arx: counter overflow`);let h=Math.min(Eg,c-m);if(d&&h===Eg){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Dg;t++)n=e+t,p[n]=f[n]^u[t];m+=Eg;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function jg(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=hg({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return tg(i),tg(o),eg(a),eg(n),(t,s,c,l,u=0)=>{ng(t,void 0,`key`),ng(s,void 0,`nonce`),ng(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=yg(d,l,!1),f&&mg(c,l),tg(u),u<0||u>=Og)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=Sg(t)),g=Tg;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=wg,p.push(h);else throw ng(t,32,`arx key`),Error(`invalid key size`);(!lg||!xg(s))&&p.push(s=Sg(s));let _=og(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(lg)r(g,_,og(e),_);else{let t=fg(Uint32Array.from(g));r(t,_,og(e),_),sg(t),fg(_)}s=s.subarray(16)}else lg||fg(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=fg(og(s));try{return Ag(e,g,_,y,c,l,u,o),l}finally{sg(...p)}}}function Mg(e,t){return e[t++]&255|(e[t++]&255)<<8}var Ng=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Sg(ng(e,32,`key`));let t=Mg(e,0),n=Mg(e,2),r=Mg(e,4),i=Mg(e,6),a=Mg(e,8),o=Mg(e,10),s=Mg(e,12),c=Mg(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Mg(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=Mg(e,t+0),_=Mg(e,t+2),v=Mg(e,t+4),y=Mg(e,t+6),b=Mg(e,t+8),x=Mg(e,t+10),S=Mg(e,t+12),C=Mg(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),O=i[4]+((y>>>4|b<<12)&8191),k=i[5]+(b>>>1&8191),A=i[6]+((b>>>14|x<<2)&8191),j=i[7]+((x>>>11|S<<5)&8191),M=i[8]+((S>>>8|C<<8)&8191),N=i[9]+(C>>>5|r),P=0,F=P+w*o+5*h*T+5*m*E+5*p*D+5*f*O;P=F>>>13,F&=8191,F+=5*d*k+5*u*A+5*l*j+5*c*M+5*s*N,P+=F>>>13,F&=8191;let I=P+w*s+T*o+5*h*E+5*m*D+5*p*O;P=I>>>13,I&=8191,I+=5*f*k+5*d*A+5*u*j+5*l*M+5*c*N,P+=I>>>13,I&=8191;let L=P+w*c+T*s+E*o+5*h*D+5*m*O;P=L>>>13,L&=8191,L+=5*p*k+5*f*A+5*d*j+5*u*M+5*l*N,P+=L>>>13,L&=8191;let R=P+w*l+T*c+E*s+D*o+5*h*O;P=R>>>13,R&=8191,R+=5*m*k+5*p*A+5*f*j+5*d*M+5*u*N,P+=R>>>13,R&=8191;let ee=P+w*u+T*l+E*c+D*s+O*o;P=ee>>>13,ee&=8191,ee+=5*h*k+5*m*A+5*p*j+5*f*M+5*d*N,P+=ee>>>13,ee&=8191;let te=P+w*d+T*u+E*l+D*c+O*s;P=te>>>13,te&=8191,te+=k*o+5*h*A+5*m*j+5*p*M+5*f*N,P+=te>>>13,te&=8191;let z=P+w*f+T*d+E*u+D*l+O*c;P=z>>>13,z&=8191,z+=k*s+A*o+5*h*j+5*m*M+5*p*N,P+=z>>>13,z&=8191;let ne=P+w*p+T*f+E*d+D*u+O*l;P=ne>>>13,ne&=8191,ne+=k*c+A*s+j*o+5*h*M+5*m*N,P+=ne>>>13,ne&=8191;let re=P+w*m+T*p+E*f+D*d+O*u;P=re>>>13,re&=8191,re+=k*l+A*c+j*s+M*o+5*h*N,P+=re>>>13,re&=8191;let ie=P+w*h+T*m+E*p+D*f+O*d;P=ie>>>13,ie&=8191,ie+=k*u+A*l+j*c+M*s+N*o,P+=ie>>>13,ie&=8191,P=(P<<2)+P|0,P=P+F|0,F=P&8191,P>>>=13,I+=P,i[0]=F,i[1]=I,i[2]=L,i[3]=R,i[4]=ee,i[5]=te,i[6]=z,i[7]=ne,i[8]=re,i[9]=ie}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;sg(n)}update(e){ig(this),ng(e),e=Sg(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,sg(this.h,this.r,this.buffer,this.pad)}digestInto(e){ig(this),ag(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},Pg=_g(32,e=>new Ng(e));function Fg(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I=b,L=x;for(let e=0;e<a;e+=2)S=S+E|0,P=$(P^S,16),A=A+P|0,E=$(E^A,12),S=S+E|0,P=$(P^S,8),A=A+P|0,E=$(E^A,7),C=C+D|0,F=$(F^C,16),j=j+F|0,D=$(D^j,12),C=C+D|0,F=$(F^C,8),j=j+F|0,D=$(D^j,7),w=w+O|0,I=$(I^w,16),M=M+I|0,O=$(O^M,12),w=w+O|0,I=$(I^w,8),M=M+I|0,O=$(O^M,7),T=T+k|0,L=$(L^T,16),N=N+L|0,k=$(k^N,12),T=T+k|0,L=$(L^T,8),N=N+L|0,k=$(k^N,7),S=S+D|0,L=$(L^S,16),M=M+L|0,D=$(D^M,12),S=S+D|0,L=$(L^S,8),M=M+L|0,D=$(D^M,7),C=C+O|0,P=$(P^C,16),N=N+P|0,O=$(O^N,12),C=C+O|0,P=$(P^C,8),N=N+P|0,O=$(O^N,7),w=w+k|0,F=$(F^w,16),A=A+F|0,k=$(k^A,12),w=w+k|0,F=$(F^w,8),A=A+F|0,k=$(k^A,7),T=T+E|0,I=$(I^T,16),j=j+I|0,E=$(E^j,12),T=T+E|0,I=$(I^T,8),j=j+I|0,E=$(E^j,7);let R=0;r[R++]=o+S|0,r[R++]=s+C|0,r[R++]=c+w|0,r[R++]=l+T|0,r[R++]=u+E|0,r[R++]=d+D|0,r[R++]=f+O|0,r[R++]=p+k|0,r[R++]=m+A|0,r[R++]=h+j|0,r[R++]=g+M|0,r[R++]=_+N|0,r[R++]=v+P|0,r[R++]=y+F|0,r[R++]=b+I|0,r[R++]=x+L|0}function Ig(e,t,n,r){let i=lg?e:fg(e.slice(0,4)),a=lg?t:fg(t.slice(0,8)),o=lg?n:fg(n.slice(0,4)),s=new Uint32Array(16);Fg(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,fg(r),lg||sg(i,a,o),sg(s)}var Lg=jg(Fg,{counterRight:!1,counterLength:8,extendNonceFn:Ig,allowShortKeys:!1}),Rg=new Uint8Array(16),zg=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Rg.subarray(n))},Bg=new Uint8Array(32);function Vg(e,t,n,r,i){i!==void 0&&ng(i,void 0,`AAD`);let a=e(t,n,Bg),o=bg(r.length,i?i.length:0,!0),s=Pg.create(a);i&&zg(s,i),zg(s,r),s.update(o);let c=s.digest();return sg(a,o),c}var Hg=vg({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=yg(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Vg(e,t,n,s,r);return a.set(c,o),sg(c),a},decrypt(i,a){a=yg(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Vg(e,t,n,o,r);if(!gg(s,c))throw sg(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),sg(c),a}}))(Lg));function Ug(e,t,n=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}var Wg=(e,t,n)=>md(e,t,n),Gg=pd;function Kg(e,t=`object`){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`);return e}function qg(e,t){if(typeof e!=`function`)throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Jg=Td,Yg=(...e)=>Od(...e),Xg=e=>Dd(e),Zg=dd,Qg=e=>jd(e),$g=BigInt(0),e_=BigInt(1),t_=e=>e?`"${e}" `:``;function n_(e,t=``){if(typeof e!=`boolean`)throw TypeError(t_(t)+`expected boolean, got type=`+typeof e);return e}function r_(e){if(typeof e==`bigint`){if(!d_(e))throw RangeError(`positive bigint expected, got `+e)}else Gg(e);return e}function i_(e,t=``){if(typeof e!=`number`){let n=t&&`"${t}" `;throw TypeError(n+`expected number, got type=`+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw RangeError(n+`expected safe integer, got `+e)}}function a_(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);return e===``?$g:BigInt(`0x`+e)}function o_(e){return a_(Td(e))}function s_(e){return a_(Td(u_(md(e)).reverse()))}function c_(e,t){if(pd(t),t===0)throw Error(`zero output length is invalid`);e=r_(e);let n=t*2,r=e.toString(16);if(r.length>n)throw RangeError(`number is too large`);return Dd(r.padStart(n,`0`))}function l_(e,t){return c_(e,t).reverse()}function u_(e){return Uint8Array.from(Wg(e))}function d_(e){return typeof e==`bigint`&&$g<=e}function f_(e,t,n){return d_(e)&&d_(t)&&d_(n)&&t<=e&&e<n}function p_(e,t,n,r){if(!f_(t,n,r))throw RangeError(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function m_(e){if(e<$g)throw Error(`expected non-negative bigint, got `+e);return e===$g?0:e.toString(2).length}var h_=e=>(i_(e,`n`),(e_<<BigInt(e))-e_);function g_(e,t={},n={},r=`object`){Kg(e,r),Kg(t,`fields`),Kg(n,`optFields`);function i(t,n,i){let a=r===`object`?`param "${String(t)}"`:`"${r}.${String(t)}"`,o=e[t];if(!Object.hasOwn(e,t)&&(i?o!==void 0:n!==`function`))throw TypeError(`${a} is invalid: expected own property`);if(i&&o===void 0)return;let s=typeof o;if(s!==n||o===null)throw TypeError(`${a} is invalid: expected ${n}, got ${s}`)}let a=(e,t)=>Object.entries(e).forEach(([e,n])=>i(e,n,t));a(t,!1),a(n,!0)}var __=BigInt(0),v_=BigInt(1),y_=BigInt(2),b_=BigInt(3),x_=BigInt(4),S_=BigInt(5),C_=BigInt(7),w_=BigInt(8),T_=BigInt(9),E_=BigInt(15),D_=BigInt(16),O_=BigInt(`0x10000000000000000`);function k_(e,t){if(t<=__)throw Error(`mod: expected positive modulus, got `+t);let n=e%t;return n>=__?n:t+n}function A_(e,t,n){if(n<=v_)throw Error(`pow: expected modulus > 1, got `+n);if(typeof t!=`bigint`)throw TypeError(`invalid exponent: expected bigint, got `+typeof t);if(t<__)throw Error(`invalid exponent, negatives unsupported`);if(t===__)return v_;if(t===v_)return e;let r=e%n;if(r<__&&(r+=n),t<O_){let e=v_;for(;t>__;)t&v_&&(e=e*r%n),r=r*r%n,t>>=v_;return e}let i=[];for(;t>__;)i.push(Number(t&E_)),t>>=x_;let a=Array(16);a[0]=v_,a[1]=r;for(let e=2;e<16;e++)a[e]=a[e-1]*r%n;let o=a[i[i.length-1]];for(let e=i.length-2;e>=0;e--){o=o*o%n,o=o*o%n,o=o*o%n,o=o*o%n;let t=i[e];t!==0&&(o=o*a[t]%n)}return o}function j_(e,t,n){if(n<=v_)throw Error(`pow2: expected modulus > 1, got `+n);if(t<__)throw Error(`pow2: expected non-negative exponent, got `+t);let r=e;for(;t-->__;)r*=r,r%=n;return r}function M_(e,t){if(e===__)throw Error(`invert: expected non-zero number`);if(t<=v_)throw Error(`invert: expected modulus > 1, got `+t);let n=k_(e,t),r=t,i=__,a=v_;for(;n!==__;){let e=r/n,t=r-n*e,o=i-a*e;r=n,n=t,i=a,a=o}if(r!==v_)throw Error(`invert: does not exist`);return k_(i,t)}function N_(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw Error(`Cannot find square root`)}function P_(e,t){if((e&v_)===__)throw Error(t+`: expected odd modulus, got `+e)}function F_(e,t){let n=e,r=(n.ORDER+v_)/x_,i=n.pow(t,r);return N_(n,i,t),i}function I_(e,t){let n=e,r=(n.ORDER-S_)/w_,i=n.mul(t,y_),a=n.pow(i,r),o=n.mul(t,a),s=n.mul(n.mul(o,y_),a),c=n.mul(o,n.sub(s,n.ONE));return N_(n,c,t),c}function L_(e){let t=J_(e),n=R_(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+C_)/D_;return((e,t)=>{let n=e,s=n.pow(t,o),c=n.mul(s,r),l=n.mul(s,i),u=n.mul(s,a),d=n.eql(n.sqr(c),t),f=n.eql(n.sqr(l),t);s=n.cmov(s,c,d),c=n.cmov(u,l,f);let p=n.eql(n.sqr(c),t),m=n.cmov(s,c,p);return N_(n,m,t),m})}function R_(e){if(e<b_)throw Error(`sqrt is not defined for small field`);P_(e,`tonelliShanks`);let t=e-v_,n=0;for(;t%y_===__;)t/=y_,n++;let r=y_,i=J_(e);for(;W_(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return F_;let a=i.pow(r,t),o=(t+v_)/y_;return function(e,r){let i=e;if(i.is0(r))return r;if(W_(i,r)!==1)throw Error(`Cannot find square root`);let s=n,c=i.mul(i.ONE,a),l=i.pow(r,t),u=i.pow(r,o);for(;!i.eql(l,i.ONE);){if(i.is0(l))throw Error(`Cannot find square root: probably non-prime P`);let e=1,t=i.sqr(l);for(;!i.eql(t,i.ONE);)if(e++,t=i.sqr(t),e===s)throw Error(`Cannot find square root`);let n=v_<<BigInt(s-e-1),r=i.pow(c,n);s=e,c=i.sqr(r),l=i.mul(l,c),u=i.mul(u,r)}return u}}function z_(e){return P_(e,`Fp.sqrt`),e%x_===b_?F_:e%w_===S_?I_:e%D_===T_?L_(e):R_(e)}var B_=(e,t)=>(k_(e,t)&v_)===v_,V_=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function H_(e){if(Kg(e,`field`),typeof e.ORDER!=`bigint`)throw TypeError(`param "ORDER" is invalid: expected bigint, got `+typeof e.ORDER);i_(e.BYTES,`BYTES`),i_(e.BITS,`BITS`);for(let t of V_)qg(e[t],`field.`+t);if(e.BYTES<1||e.BITS<1)throw Error(`invalid field: expected BYTES/BITS > 0`);if(e.ORDER<=v_)throw Error(`invalid field: expected ORDER > 1, got `+e.ORDER);return e}function U_(e,t,n=!1){H_(e),Ug(t,`nums`),n_(n,`passZero`);let r=e,i=Array(t.length).fill(n?r.ZERO:void 0),a=t.reduce((e,t,n)=>r.is0(t)?e:(i[n]=e,r.mul(e,t)),r.ONE),o=r.inv(a);return t.reduceRight((e,t,n)=>r.is0(t)?e:(i[n]=r.mul(e,i[n]),r.mul(e,t)),o),i}function W_(e,t){H_(e);let n=e;P_(n.ORDER,`FpLegendre`);let r=(n.ORDER-v_)/y_,i=n.pow(t,r),a=n.eql(i,n.ONE),o=n.eql(i,n.ZERO),s=n.eql(i,n.neg(n.ONE));if(!a&&!o&&!s)throw Error(`invalid Legendre symbol result`);return a?1:o?0:-1}function G_(e,t){if(t!==void 0&&Gg(t),e<=__)throw Error(`invalid n length: expected positive n, got `+e);if(t!==void 0&&t<1)throw Error(`invalid n length: expected positive bit length, got `+t);let n=m_(e);if(t!==void 0&&t<n)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t===void 0?n:t;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}var K_=new WeakMap,q_=class{ORDER;BITS;BYTES;isLE;ZERO=__;ONE=v_;_lengths;_mod;constructor(e,t={}){if(e<=v_)throw Error(`invalid field: expected ORDER > 1, got `+e);let n;this.isLE=!1,typeof t==`object`&&t&&(typeof t.BITS==`number`&&(n=t.BITS),typeof t.sqrt==`function`&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE==`boolean`&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes==`boolean`&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:i}=G_(e,n);if(i>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);this.ORDER=e,this.BITS=r,this.BYTES=i,Object.freeze(this)}create(e){return k_(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw TypeError(`invalid field element: expected bigint, got `+typeof e);return __<=e&&e<this.ORDER}is0(e){return e===__}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&v_)===v_}neg(e){return k_(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return k_(e*e,this.ORDER)}add(e,t){return k_(e+t,this.ORDER)}sub(e,t){return k_(e-t,this.ORDER)}mul(e,t){return k_(e*t,this.ORDER)}pow(e,t){return A_(e,t,this.ORDER)}div(e,t){return k_(e*M_(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return M_(e,this.ORDER)}sqrt(e){let t=K_.get(this);return t||K_.set(this,t=z_(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?l_(e,this.BYTES):c_(e,this.BYTES)}fromBytes(e,t=!1){Wg(e);let{_lengths:n,BYTES:r,isLE:i,ORDER:a,_mod:o}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>r)throw Error(`Field.fromBytes: expected `+n+` bytes, got `+e.length);let t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw Error(`Field.fromBytes: expected `+r+` bytes, got `+e.length);let s=i?s_(e):o_(e);if(o&&(s=k_(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return U_(this,e,!0)}cmov(e,t,n){return n_(n,`condition`),n?t:e}};function J_(e,t={}){return Object.freeze(q_.prototype),new q_(e,t)}var Y_=BigInt(0),X_=BigInt(1),Z_=BigInt(4),Q_=16,$_=128,ev=5,tv=2**31;function nv(e){let t=e;if(typeof t!=`function`)throw TypeError(`"Point" expected constructor, got type=`+typeof e);qg(t.fromAffine,`Point.fromAffine`),qg(t.fromBytes,`Point.fromBytes`),qg(t.fromHex,`Point.fromHex`),Kg(t.BASE,`Point.BASE`),Kg(t.ZERO,`Point.ZERO`),H_(t.Fp),H_(t.Fn)}function rv(e,t){nv(e),sv(t,e);let n=U_(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function iv(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw Error(`invalid window size, expected [`+n+`..`+t+`], got W=`+e)}function av(e,t){let n=e*(4*t+128);if(n>tv)throw Error(`invalid window size: table would need ~`+Math.ceil(n/2**20)+` MiB, max `+tv/2**20+` MiB`)}function ov(e,t){if(e!==void 0){qg(e,`randomBytes`);try{let n=e(t);if(!Zg(n)||n.length!==t)return}catch{return}return e}}function sv(e,t){Ug(e,`points`),e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function cv(e,t,n){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,r)=>{if(!(n===void 0?t.isValid(e):d_(e)&&e<n))throw Error(`invalid scalar at index `+r)})}var lv=new WeakMap;function uv(e){return lv.get(e)||1}function dv(e,t){let n=e.double(),r=[e];for(let e=1;e<t;e++)r.push(r[e-1].add(n));return r}function fv(e,t){let n=2**t,r=n/2,i=BigInt(n-1),a=[];for(;e>Y_;){let t=0;e&X_&&(t=Number(e&i),t>=r&&(t-=n),e-=BigInt(t)),a.push(t),e>>=X_}return a}function pv(e,t,n){let r=2**t,i=r/2,a=BigInt(r-1),o=BigInt(t),s=[];for(let t=0;t<n;t++){let t=Number(e&a);e>>=o,t>i&&(t-=r,e+=X_),s.push(t)}if(e!==Y_)throw Error(`invalid wnaf`);return s}function mv(e,t,n){let r=0;for(let e of n)r=Math.max(r,e.length);let i=e;for(let e=r-1;e>=0;e--){e!==r-1&&(i=i.double());for(let r=0;r<n.length;r++){let a=n[r][e];if(a){let e=t[r][Math.abs(a)-1>>1];i=i.add(a<0?e.negate():e)}}}return i}var hv=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){nv(e),this.randomBytes=ov(t,Q_),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let r=Math.ceil(n/t)+1,i=2**(t-1),a=[],o=e;for(let e=0;e<r;e++){let e=o;for(let t=0;t<i;t++)a.push(e),e=e.add(o);o=a[a.length-1].double()}return{W:t,bits:n,windows:r,comp:a}}wnafCachedCT(e,t){let{W:n,windows:r,comp:i}=e,a=2**(n-1),o=pv(t,n,r),s=this.ZERO,c=this.BASE;for(let e=0;e<r;e++){let t=o[e],n=e*a,r=Math.abs(t)-1,l=i[n];for(let e=1;e<a;e++)l=e===r?i[n+e]:l;let u=l.negate();t===0?c=c.add(i[n]):s=s.add(t<0?u:l)}return{p:s,f:c}}getWnafPrecomputes(e,t,n,r){let i=this.wnafPrecomputes.get(t),a=i?.find(t=>t.W===e&&t.bits===n);return a||(a=this.buildWnafTable(t,e,n),typeof r==`function`&&(a={...a,comp:r(a.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(a)),a}assertPoint(e){if(!(e instanceof this.Point))throw TypeError(`"point" expected Point instance, got type=`+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!f_(t,X_,this.Point.Fn.ORDER))throw Error(`invalid scalar`)}runCT(e,t,n,r){let i=uv(e);return i===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(i,e,n,r),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error(`randomBytes is required for scalar blinding`);let r=this.Point.Fn.BITS+$_,i=this.randomBytes(Q_);if(!Zg(i)||i.length!==Q_)throw Error(`randomBytes returned invalid byte array`);i[0]=i[0]&63|128;let a=t+o_(i)*this.Point.Fn.ORDER;return this.runCT(e,a,r,n)}fixedWindowCT(e,t,n){let r=ev,i=h_(r),a=Array(32);a[0]=this.ZERO;for(let t=1;t<32;t++)a[t]=a[t-1].add(e);let o=Math.ceil(n/r),s=this.ZERO;for(let e=o-1;e>=0;e--){if(e!==o-1)for(let e=0;e<r;e++)s=s.double();let n=Number(t>>BigInt(e*r)&i),c=a[0];for(let e=1;e<32;e++)c=e===n?a[e]:c;s=s.add(c)}return{p:s,f:s}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===X_||e===this.BASE&&(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,r){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,n){if(this.assertPoint(e),!d_(t))throw Error(`invalid scalar`);let r=uv(e);if(r===1||t>=this.Point.Fn.ORDER)return gv(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(r,e,this.bits,n);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),iv(t,this.bits),av((Math.ceil((this.bits+$_)/t)+1)*2**(t-1),this.Point.Fp.BYTES),lv.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return uv(e)!==1}};function gv(e,t,n,r=!1){if(nv(e),sv(t,e),n_(r,`allowOversized`),cv(n,e.Fn,r?e.Fn.ORDER**Z_:void 0),t.length!==n.length)throw Error(`arrays of points and scalars must have equal length`);let i=t.map(e=>dv(e,4)),a=n.map(e=>fv(e,4));return mv(e.ZERO,i,a)}function _v(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return H_(t),t}return J_(e,{isLE:n})}function vv(e,t,n={},r){if(e!==`weierstrass`&&e!==`edwards`)throw Error(`expected curve type "weierstrass" or "edwards"`);if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);g_(n);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(d_(n)&&n!==Y_))throw Error(`CURVE.${e} must be positive bigint`)}let i=_v(t.p,n.Fp,r),a=_v(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}function yv(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var bv=BigInt(0),xv=BigInt(1),Sv=BigInt(2),Cv=BigInt(4),wv=BigInt(8);function Tv(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function Ev(e,t={}){g_(t,{},{},`extraOpts`);let n=t,r=vv(`edwards`,e,n,n.FpFnLE),{Fp:i,Fn:a}=r,o=r.CURVE,{h:s}=o;if(W_(i,o.a)!==1)throw Error(`edwards: CURVE.a must be a square in Fp for complete addition formulas`);if(W_(i,o.d)!==-1)throw Error(`edwards: CURVE.d must be a non-square in Fp for complete addition formulas`);g_(n,{},{uvRatio:`function`,randomBytes:`function`});let c=n.randomBytes===void 0?Qg:n.randomBytes,l=Sv<<BigInt(i.BYTES*8)-xv;function u(e){if(!i.isOdd)throw Error(`Field does not have .isOdd()`);return i.isOdd(e)}let d=n.uvRatio===void 0?(e,t)=>{try{return{isValid:!0,value:i.sqrt(i.div(e,t))}}catch{return{isValid:!1,value:bv}}}:n.uvRatio;if(!Tv(i,o,o.Gx,o.Gy))throw Error(`bad curve params: generator point`);let f=i.eql(o.a,i.neg(i.ONE))?e=>i.neg(e):i.eql(o.a,i.ONE)?e=>e:e=>i.mul(o.a,e);function p(e,t,n=!1){let r=n?xv:bv;return p_(`coordinate `+e,t,r,l),t}function m(e){if(!(e instanceof h))throw Error(`EdwardsPoint expected`)}class h{static BASE=new h(o.Gx,o.Gy,i.ONE,i.mul(o.Gx,o.Gy));static ZERO=new h(i.ZERO,i.ONE,i.ONE,i.ZERO);static Fp=i;static Fn=a;X;Y;Z;T;constructor(e,t,n,r){this.X=p(`x`,e),this.Y=p(`y`,t),this.Z=p(`z`,n,!0),this.T=p(`t`,r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof h)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return p(`x`,t),p(`y`,n),new h(t,n,i.ONE,i.mul(t,n))}static fromBytes(e,t=!1){let n=i.BYTES,{a:r,d:a}=o;e=u_(Wg(e,n,`point`)),n_(t,`zip215`);let s=u_(e),c=e[n-1];s[n-1]=c&-129;let f=s_(s);p_(`point.y`,f,bv,t?l:i.ORDER);let p=i.sqr(f),m=i.sub(p,i.ONE),g=i.sub(i.mulN(a,p),r),{isValid:_,value:v}=d(m,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=u(v),b=!!(c&128);if(!t&&i.is0(v)&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=i.neg(v)),h.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return h.fromBytes(Xg(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=6,t=!0){return _.setWindowSize(this,e),t||this.multiply(Sv),this}assertValidity(){let e=this,{a:t,d:n}=o;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:a,Z:s,T:c}=e,l=i.sqr(r),u=i.sqr(a),d=i.sqr(s),f=i.sqr(d),p=i.mul(l,t),m=i.mul(i.add(p,u),d),h=i.add(f,i.mul(n,i.mul(l,u)));if(!i.eql(m,h))throw Error(`bad point: equation left != right (1)`);let g=i.mul(r,a),_=i.mul(s,c);if(!i.eql(g,_))throw Error(`bad point: equation left != right (2)`)}equals(e){m(e);let{X:t,Y:n,Z:r}=this,{X:a,Y:o,Z:s}=e,c=i.mul(t,s),l=i.mul(a,r),u=i.mul(n,s),d=i.mul(o,r);return i.eql(c,l)&&i.eql(u,d)}is0(){return this.equals(h.ZERO)}negate(){return new h(i.neg(this.X),this.Y,this.Z,i.neg(this.T))}double(){let{X:e,Y:t,Z:n}=this,r=i.sqr(e),a=i.sqr(t),o=i.mul(i.sqr(n),Sv),s=f(r),c=i.addN(e,t),l=i.sub(i.subN(i.sqr(c),r),a),u=i.addN(s,a),d=i.subN(u,o),p=i.subN(s,a),m=i.mul(l,d),g=i.mul(u,p),_=i.mul(l,p),v=i.mul(d,u);return new h(m,g,v,_)}add(e){m(e);let{d:t}=o,{X:n,Y:r,Z:a,T:s}=this,{X:c,Y:l,Z:u,T:d}=e,p=i.mul(n,c),g=i.mul(r,l),_=i.mul(i.mulN(s,t),d),v=i.mul(a,u),y=i.sub(i.subN(i.mulN(i.addN(n,r),i.addN(c,l)),p),g),b=i.subN(v,_),x=i.addN(v,_),S=i.sub(g,f(p)),C=i.mul(y,b),w=i.mul(x,S),T=i.mul(y,S),E=i.mul(b,x);return new h(C,w,E,T)}subtract(e){return m(e),this.add(e.negate())}multiply(e){if(!a.isValidNot0(e))throw RangeError(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=_.mulSecret(this,e,s,g);return g([t,n])[0]}multiplyUnsafe(e){if(!a.isValid(e))throw RangeError(`invalid scalar: expected 0 <= sc < curve.n`);return e===bv?h.ZERO:this.is0()||e===xv?this:_.mulUnsafe(this,e,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return _.mulUnsafe(this,o.n).is0()}toAffine(e){let t=this,n=e;if(n!=null&&typeof n!=`bigint`)throw TypeError(`"invertedZ" expected bigint, got type=`+typeof n);let{X:r,Y:a,Z:o}=t,s=t.is0();n??=s?i.create(wv):i.inv(o);let c=i.mul(r,n),l=i.mul(a,n),u=i.mul(o,n);if(s)return{x:i.ZERO,y:i.ONE};if(!i.eql(u,i.ONE))throw Error(`invZ was invalid`);return{x:c,y:l}}clearCofactor(){return s===xv?this:s===Sv?this.double():s===Cv?this.double().double():s===wv?this.double().double().double():this.multiplyUnsafe(s)}toBytes(){let{x:e,y:t}=this.toAffine(),n=i.toBytes(t);return n[n.length-1]|=u(e)?128:0,n}toHex(){return Jg(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let g=e=>rv(h,e),_=new hv(h,c);return _.bits>=6&&h.BASE.precompute(6),Object.freeze(h.prototype),Object.freeze(h),h}function Dv(e,t,n={}){if(nv(e),typeof t!=`function`)throw Error(`"hash" function param is required`);let r=t,i=n;g_(i,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,zip215:`boolean`,mapToCurve:`function`,toMontgomery:`function`,toMontgomerySecret:`function`});let{prehash:a}=i,{BASE:o,Fp:s,Fn:c}=e,l=r.outputLen,u=2*s.BYTES;if(l!==void 0&&(i_(l,`hash.outputLen`),l!==u))throw Error(`hash.outputLen must be ${u}, got ${l}`);let d=i.randomBytes===void 0?Qg:i.randomBytes,f=i.toMontgomery,p=i.toMontgomerySecret,m=i.adjustScalarBytes===void 0?e=>e:i.adjustScalarBytes,h=i.domain===void 0?(e,t,n)=>{if(n_(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e}:i.domain;function g(e){return c.create(s_(e))}function _(e){let t=T.secretKey;Wg(e,T.secretKey,`secretKey`);let n=Wg(r(e),2*t,`hashedSecretKey`),i=m(n.slice(0,t));return{head:i,prefix:n.slice(t,2*t),scalar:g(i)}}function v(e){let{head:t,prefix:n,scalar:r}=_(e),i=o.multiply(r);return{head:t,prefix:n,scalar:r,point:i,pointBytes:i.toBytes()}}function y(e){return v(e).pointBytes}function b(e=Uint8Array.of(),...t){let n=Yg(...t);return g(r(h(n,Wg(e,void 0,`context`),!!a)))}function x(e,t,n={}){g_(n,{},{},`options`),e=u_(Wg(e,void 0,`message`)),a&&(e=a(e));let{prefix:r,scalar:i,pointBytes:s}=v(t),l=b(n.context,r,e),u=o.multiply(l).toBytes(),d=b(n.context,u,s,e),f=c.create(l+d*i);if(!c.isValid(f))throw Error(`sign failed: invalid s`);return Wg(Yg(u,c.toBytes(f)),T.signature,`result`)}let S={zip215:i.zip215};function C(t,n,r,i=S){g_(i);let{context:s}=i,c=i.zip215===void 0?!!S.zip215:i.zip215,l=T.signature;t=Wg(t,l,`signature`),n=Wg(n,void 0,`message`),r=Wg(r,T.publicKey,`publicKey`),c!==void 0&&n_(c,`zip215`),a&&(n=a(n));let u=l/2,d=t.subarray(0,u),f=s_(t.subarray(u,l)),p,m,h;try{p=e.fromBytes(r,c),m=e.fromBytes(d,c),h=o.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let g=b(s,d,r,n);return m.add(p.multiplyUnsafe(g)).subtract(h).clearCofactor().is0()}let w=s.BYTES,T={secretKey:w,publicKey:w,signature:2*w,seed:w};function E(e){return e=e===void 0?d(T.seed):e,Wg(e,T.seed,`seed`)}function D(e){return Zg(e)&&e.length===T.secretKey}function O(t,n){try{return!!e.fromBytes(t,n===void 0?S.zip215:n)}catch{return!1}}let k={getExtendedPublicKey:v,randomSecretKey:E,isValidSecretKey:D,isValidPublicKey:O,toMontgomery(t){if(f===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return f(e.fromBytes(t))},toMontgomerySecret(e){if(p===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return p(e)}};return Object.freeze(T),Object.freeze(k),Object.freeze({keygen:yv(E,y),getPublicKey:y,sign:x,verify:C,utils:k,Point:e,lengths:T})}var Ov=BigInt(0),kv=BigInt(1),Av=BigInt(2);function jv(e,t){return e+t-(t>>kv<<kv)}function Mv(e){let t=BigInt(6)*e;return(n,r,i)=>{let a=r+i,o=((t+i-r)*n+r)%e;return{x_2:o,x_3:a-o}}}function Nv(e){return g_(e,{P:`bigint`,type:`string`,adjustScalarBytes:`function`,powPminus2:`function`},{randomBytes:`function`,scalarMultBase:`function`}),Object.freeze({...e})}function Pv(e){let t=Nv(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:a,randomBytes:o}=t,s=t.scalarMultBase,c=r===`x25519`;if(!c&&r!==`x448`)throw Error(`invalid type`);let l=o===void 0?Qg:o,u=c?255:448,d=Mv(n),f=c?32:56,p=BigInt(c?9:5),m=BigInt(c?121665:39081),h=c?Av**BigInt(254):Av**BigInt(447),g=h+(c?BigInt(8)*(Av**BigInt(251)-kv):BigInt(4)*(Av**BigInt(445)-kv))+kv,_=e=>k_(e,n),v=y(p);function y(e){return l_(_(e),f)}function b(e){let t=u_(Wg(e,f,`uCoordinate`));return c&&(t[31]&=127),_(s_(t))}function x(e){return s_(i(u_(Wg(e,f,`scalar`))))}let S=new Set(c?[Ov,kv,n-kv,BigInt(`325606250916557431795983626356110631294008115727848805560023387167927233504`),BigInt(`39382357235489614581723060781553021112529911719440698176882885853963445705823`)]:[Ov,kv,n-kv]);function C(e,t){let n=b(t);if(S.has(n))throw Error(`invalid private or public key received`);let r=D(n,x(e));if(r===Ov)throw Error(`invalid private or public key received`);return y(r)}function w(e){if(s===void 0)return C(e,v);let t=x(e);p_(`scalar`,t,h,g);let n=_(s(t));if(n===Ov)throw Error(`invalid private or public key received`);return y(n)}let T=w,E=C;function D(e,t){p_(`u`,e,Ov,n),p_(`scalar`,t,h,g);let r=t,i=e,o=kv,s=Ov,c=e,l=kv,f=r^r>>kv;for(let e=BigInt(u-1);e>=Ov;e--){let t=jv(n,f>>e);({x_2:o,x_3:c}=d(t,o,c)),{x_2:s,x_3:l}=d(t,s,l);let r=o+s,a=_(r*r),u=o-s,p=_(u*u),h=a-p,g=c+l,v=c-l,y=_(v*r),b=_(g*u),x=y+b,S=y-b;c=_(x*x),l=_(i*_(S*S)),o=_(a*p),s=_(h*(a+_(m*h)))}let p=jv(n,r);({x_2:o,x_3:c}=d(p,o,c)),{x_2:s,x_3:l}=d(p,s,l);let v=a(s);return _(o*v)}let O={secretKey:f,publicKey:f,seed:f},k=e=>(e=e===void 0?l(f):e,Wg(e,O.seed,`seed`),e),A={randomSecretKey:k};return Object.freeze(O),Object.freeze(A),Object.freeze({keygen:yv(k,T),getSharedSecret:E,getPublicKey:T,scalarMult:C,scalarMultBase:w,utils:A,GuBytes:v.slice(),lengths:O})}var Fv=BigInt(0),Iv=BigInt(1),Lv=BigInt(2),Rv=BigInt(3),zv=BigInt(5),Bv=BigInt(8),Vv=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),Hv={p:Vv,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:Bv,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function Uv(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=Vv,o=e*e%a*e%a,s=j_(j_(o,Lv,a)*o%a,Iv,a)*e%a,c=j_(s,zv,a)*s%a,l=j_(c,t,a)*c%a,u=j_(l,n,a)*l%a,d=j_(u,r,a)*u%a;return{pow_p_5_8:j_(j_(j_(j_(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,Lv,a)*e%a,b2:o}}function Wv(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Gv=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function Kv(e,t){let n=Vv,r=k_(t*t*t,n),i=Uv(e*k_(r*r*t,n)).pow_p_5_8,a=k_(e*r*i,n),o=k_(t*a*a,n),s=a,c=k_(a*Gv,n),l=o===e,u=o===k_(-e,n),d=o===k_(-e*Gv,n);return l&&(a=s),(u||d)&&(a=c),B_(a,n)&&(a=k_(-a,n)),{isValid:l||u,value:a}}var qv=Ev(Hv,{uvRatio:Kv}),Jv=qv.Fp;function Yv(e){let{y:t}=e;return Jv.toBytes(Jv.div(Iv+t,Iv-t))}function Xv(e){let t=qv.Fp.BYTES;return md(e,t),Wv(Xd(e.subarray(0,t))).subarray(0,t)}function Zv(e){return Dv(qv,Xd,Object.assign({adjustScalarBytes:Wv,toMontgomery:Yv,toMontgomerySecret:Xv,zip215:!0},e))}var Qv=Zv({}),$v=(()=>{let e=Vv,t=t=>{let{pow_p_5_8:n,b2:r}=Uv(t);return k_(j_(n,Rv,e)*r,e)};return Pv({P:e,type:`x25519`,powPminus2:t,adjustScalarBytes:Wv,scalarMultBase:n=>{let r=k_(n,qv.Fn.ORDER);if(r===Fv)return Fv;let i=qv.BASE.multiply(r);return k_((i.Z+i.Y)*t(k_(i.Z-i.Y,e)),e)}})})(),ey=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hd(e),md(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),bd(r)}update(e){return vd(this),this.iHash.update(e),this}digestInto(e){vd(this),yd(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ty=(()=>{let e=((e,t,n)=>new ey(e,t).update(n).digest());return e.create=(e,t)=>new ey(e,t),e})(),ny=Uint8Array.of(0),ry=Uint8Array.of();function iy(e,t,n,r=32,i){hd(e),pd(r,`length`),md(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=ry:md(n,void 0,`info`),!o)return i&&bd(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=ty.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){ny[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(ny).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(ny[0]=o,o>1&&c.update(u),c.update(n).update(ny).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&bd(u),bd(ny),r===s.length)return s;let f=s.slice(0,r);return bd(s),f}var ay=(e,t,n,r,i)=>{hd(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=ty.create(e,n).update(t);return iy(e,a.digest(),r,i,a)},oy={public:[],friends:[]},sy=/^[A-Za-z0-9_-]{22}$/,cy=new TextEncoder,ly=e=>{if(typeof e!=`string`||!e.isWellFormed())return null;let t=e.normalize(`NFC`).trim();return t!==``&&hf(t,{max:500,multiline:!0})===null?t:null},uy=e=>Y(Yd(cy.encode(e)).slice(0,16)),dy=({id:e,name:t,text:n,at:r})=>({id:e,name:t,text:n,at:r}),fy=e=>{if(typeof e!=`object`||!e)return null;let{id:t,name:n,text:r,at:i}=e;return typeof t!=`string`||!sy.test(t)||typeof n!=`string`||!sf(n)||typeof r!=`string`||ly(r)!==r||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,text:r,at:i}},py=(...e)=>{let t=new Map;for(let n of e.flat())t.has(n.id)||t.set(n.id,n);return[...t.values()].sort((e,t)=>t.at-e.at||(e.id<t.id?-1:+(e.id>t.id))).slice(0,20)},my=e=>py(Array.isArray(e)?e.map(fy).filter(e=>e!==null):[]),hy=e=>e.comments??oy,gy=(e,t)=>({public:py(hy(e).public,hy(t).public),friends:py(hy(e).friends,hy(t).friends)}),_y=(e,t)=>{let n=hy(e);return[...n.public,...n.friends].some(e=>e.id===t.id)?e:{...e,comments:{...n,public:py([t],n.public)}}},vy=(e,t)=>{let n=hy(e);return{...e,comments:{public:n.public.filter(e=>!t.includes(e.id)),friends:n.friends.filter(e=>!t.includes(e.id))}}},yy=(e,t)=>{let n=hy(e);return t===`off`?{...e,comments:oy}:t===`friends`?{...e,comments:{public:[],friends:py(n.friends,n.public)}}:e},by=e=>{if(typeof e!=`object`||!e)return null;let{title:t,link:n,image:r}=e;return!Ah(t,150)||!jh(n)||r!==void 0&&!jh(r)?null:r===void 0?{title:t,link:n}:{title:t,link:n,image:r}},xy=e=>{let t=[];for(let n of Array.isArray(e)?e:[]){let e=by(n);e!==null&&!t.some(t=>t.link===e.link)&&t.length<8&&t.push(e)}return t},Sy=e=>xy(e.profile.favourites?.value),Cy=async(e,t,n)=>{let r=by(t);if(r===null)return{ok:!1,reason:`invalid`};let i=!1,a=await Z(e,e=>{let t=Sy(e),a=t.filter(e=>e.link!==r.link);return n?a.length<t.length?{}:(i=t.length>=8,i?{}:{favourites:[...t,r]}):a.length===t.length?{}:{favourites:a}});return i?{ok:!1,reason:`full`}:a},wy=`fkn/social/v1/sign`,Ty=`fkn/social/v1/dh`,Ey=`fkn/social/v1/hello`,Dy=`fkn/social/v1/offer`,Oy=`fkn/social/v1/accept`,ky=`fkn/social/v1/handshake`,Ay=`fkn/social/v1/pair`,jy=`fkn/social/v1/name`,My=`fkn/social/v2/name`,Ny=`fkn/social/v1/name-room`,Py=`fkn/social/v1/request`,Fy=`fkn/social/v1/request-seal`,Iy=`fkn/social/v1/friends`,Ly=`fkn/social/v1/friend-slot`,Ry=`fkn/social/v1/page`,zy=`fkn/social/v1/chat-direct`,By=`fkn/social/v1/chat-self`,Vy=`fkn/social/v1/chat-sign`,Hy=`fkn/social/v1/chat-group-seal`,Uy=`fkn/social/v1/chat-group-msg`,Wy=`fkn/social/v1/chat-group-pair`,Gy=/^[A-Za-z0-9_-]{43}$/,Ky=e=>{if(typeof e!=`string`||e[43]!==`.`||!Gy.test(e.slice(0,43)))return null;let t=e.slice(44);return t.length>=1&&t.length<=300&&!t.includes(`\0`)?e:null},qy=e=>e.slice(44),Jy={blue:{label:`Blue`,light:{accent:`#2f5bd3`,text:`#ffffff`},dark:{accent:`#7c9cff`,text:`#0d1430`}},purple:{label:`Purple`,light:{accent:`#7442c8`,text:`#ffffff`},dark:{accent:`#b99cff`,text:`#1f1236`}},pink:{label:`Pink`,light:{accent:`#b8327a`,text:`#ffffff`},dark:{accent:`#ff8ac4`,text:`#3a0f26`}},red:{label:`Red`,light:{accent:`#c0352b`,text:`#ffffff`},dark:{accent:`#ff8f84`,text:`#3d0f0b`}},orange:{label:`Orange`,light:{accent:`#b04e0f`,text:`#ffffff`},dark:{accent:`#ffa163`,text:`#3a1a05`}},green:{label:`Green`,light:{accent:`#2a7a3b`,text:`#ffffff`},dark:{accent:`#6fd38a`,text:`#0b2a13`}},teal:{label:`Teal`,light:{accent:`#0f7671`,text:`#ffffff`},dark:{accent:`#5fd0c8`,text:`#062a28`}},grey:{label:`Grey`,light:{accent:`#5c5a55`,text:`#ffffff`},dark:{accent:`#bdb9b0`,text:`#1d1c1a`}}},Yy=Object.keys(Jy),Xy={steel:{label:`Steel`,light:!1,bg:`#13161a`,sheet:`#181c21`,panel:`#20252c`,head:`#2b333e`,border:`#38414e`,text:`#f0f2f5`,muted:`#adb5c0`,accent:`#8cb4d8`,accentText:`#0f1720`,pill:`#283647`,skyTop:`#262d37`,skyBot:`#13161a`},midnight:{label:`Midnight`,light:!1,bg:`#11161d`,sheet:`#151c26`,panel:`#1c2431`,head:`#243245`,border:`#34465e`,text:`#eef2f7`,muted:`#a4b2c4`,accent:`#7ea8de`,accentText:`#0c1422`,pill:`#23354c`,skyTop:`#1b283a`,skyBot:`#11161d`},forest:{label:`Forest`,light:!1,bg:`#111714`,sheet:`#151e19`,panel:`#1c2721`,head:`#23372c`,border:`#334d3f`,text:`#edf4ef`,muted:`#a5bdaf`,accent:`#76d690`,accentText:`#0a2412`,pill:`#213a2c`,skyTop:`#1c3126`,skyBot:`#111714`},crimson:{label:`Crimson`,light:!1,bg:`#181214`,sheet:`#20171a`,panel:`#281d21`,head:`#3c242c`,border:`#54353f`,text:`#f7eef0`,muted:`#c4a8b0`,accent:`#ee95a3`,accentText:`#290b12`,pill:`#41252e`,skyTop:`#351d24`,skyBot:`#181214`},slate:{label:`Slate`,light:!1,bg:`#141416`,sheet:`#1b1c1f`,panel:`#222428`,head:`#2d3036`,border:`#3d4149`,text:`#f1f2f4`,muted:`#b2b6be`,accent:`#c4c8d0`,accentText:`#141518`,pill:`#30333b`,skyTop:`#26282e`,skyBot:`#141416`},daylight:{label:`Daylight`,light:!0,bg:`#eceef2`,sheet:`#ffffff`,panel:`#f5f6f9`,head:`#e3e7ef`,border:`#cfd5e0`,text:`#14161a`,muted:`#505662`,accent:`#2752c4`,accentText:`#ffffff`,pill:`#dce5f5`,skyTop:`#d7dfec`,skyBot:`#eceef2`}},Zy=Object.keys(Xy),Qy=`steel`,$y={light:{error:`#b3261e`,warnBg:`#fff4dc`,warnLine:`#e9c46a`},dark:{error:`#ff8a80`,warnBg:`#352b16`,warnLine:`#8a6d1f`}},eb={about:`About`,activity:`Activity`,favourites:`Favourites`,comments:`Comments`},tb=Object.keys(eb),nb={accent:`blue`,theme:Qy,sections:[{id:`about`},{id:`activity`,level:`off`},{id:`favourites`,level:`off`},{id:`comments`,level:`off`}]},rb={accent:`blue`,sections:[`about`]},ib=16,ab=e=>typeof e==`string`&&tb.includes(e),ob=e=>typeof e==`string`&&Object.hasOwn(Jy,e)?e:`blue`,sb=e=>typeof e==`string`&&Object.hasOwn(Xy,e)?e:Qy,cb=new Set([`public`,`friends`,`off`]),lb=(e,t)=>{if(e===`about`)return{id:e};let n=t?.level;return{id:e,level:typeof n==`string`&&cb.has(n)?n:`off`}},ub=e=>{let t=e.profile.page?.value;if(typeof t!=`object`||!t)return nb;let{accent:n,theme:r,sections:i}=t,a=new Map;for(let e of Array.isArray(i)?i:[]){let t=e?.id;ab(t)&&!a.has(t)&&a.set(t,lb(t,e))}for(let e of tb)a.has(e)||a.set(e,lb(e));return{accent:ob(n),theme:sb(r),sections:[...a.values()]}},db=(e,t)=>{let n=e.sections.find(e=>e.id===t);return n!==void 0&&n.id!==`about`?n.level:`off`},fb=(e,t)=>db(ub(e),t),pb=(e,t,n)=>({...e,sections:e.sections.map(e=>e.id===t?{id:t,level:n}:e)}),mb=(e,t,n)=>{let r=e.sections.findIndex(e=>e.id===t),i=r+n;if(r<0||i<0||i>=e.sections.length)return e;let a=[...e.sections];return[a[r],a[i]]=[a[i],a[r]],{...e,sections:a}},hb=(e,t)=>{if(e.profile.page===void 0)return null;let{accent:n,theme:r,sections:i}=ub(e);return{accent:n,...r===`steel`?{}:{theme:r},sections:i.filter(e=>e.id===`about`?t:e.level===`public`).map(({id:e})=>e)}},gb=(e,t)=>ub(e).sections.filter(e=>e.id===`about`?t:e.level!==`off`).map(({id:e})=>e),_b=e=>{if(typeof e!=`object`||!e)return rb;let{accent:t,theme:n,sections:r}=e;if(!Array.isArray(r)||r.length>ib||!r.every(e=>typeof e==`string`))return rb;let i=sb(n);return{accent:ob(t),...i===`steel`?{}:{theme:i},sections:[...new Set(r)].filter(ab)}},vb=(e,t)=>JSON.stringify(e)===JSON.stringify(t),yb=(e,t,n)=>Z(e,()=>vb(t,n)?{}:{page:t}),bb=new TextEncoder,xb=new TextDecoder,Sb=Uint8Array.of(0),Cb=Uint8Array.of(1),wb=(...e)=>{let t=e.map(e=>typeof e==`string`?bb.encode(e):e),n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),r=0;for(let e of t)n.set(e,r),r+=e.length;return n},Tb=(e,...t)=>ty(Yd,e,wb(...t)),Eb=e=>Math.max(8,2**Math.ceil(Math.log2(Math.max(1,e)))),Db=e=>ay(Yd,e.dhSeed,void 0,bb.encode(Iy),32),Ob=(e,t,n)=>Tb(e,`k`,t,Sb,n),kb=(e,t,n)=>{try{return ay(Yd,$v.getSharedSecret(e,t),bb.encode(n),bb.encode(Ly),32)}catch{return null}},Ab=e=>e.map(Y).sort().join(`\0`),jb=(e,t,n,r)=>{let i=Db(e),a=bb.encode(Ab(n)),o=Tb(i,`e`,[...r].sort().join(`\0`),Cb,a).slice(0,16),s=n.map(n=>kb(e.dhSeed,n,t)).filter(e=>e!==null);return{e:o,key:Ob(i,t,o),secret:i,members:a,slots:s}},Mb=e=>({displayName:e.displayName,bio:e.bio,links:e.links,...e.avatar==null?{}:{avatar:{url:e.avatar.url,key:e.avatar.key}},...e.background==null?{}:{background:{url:e.background.url,key:e.background.key}}}),Nb=e=>JSON.stringify({profile:e.profile===null?null:Mb(e.profile),sections:e.sections,feed:e.feed.map(Ih),...e.favourites===void 0||e.favourites.length===0?{}:{favourites:e.favourites.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...e.comments===void 0||e.comments.length===0?{}:{comments:e.comments.map(dy)},...e.panels===void 0||e.panels.length===0?{}:{panels:e.panels.map(xm)},...e.panelOrder===void 0||e.panelOrder.length===0?{}:{panelOrder:e.panelOrder},...e.chatRoom==null?{}:{chatRoom:e.chatRoom}}),Pb=(e,t,n,r)=>{let i=bb.encode(Nb(n)),a=Tb(e.key,`z`,r,Sb,i,Sb,e.members).slice(0,16),o=Hg(e.key,Tb(e.key,`c`,a).slice(0,24),wb(t.roomId,Sb,t.owner)).encrypt(i),s=e.slots.map(t=>({i:Y(Tb(t,`i`,a).slice(0,16)),w:Y(Hg(t,Tb(t,`w`,a).slice(0,24)).encrypt(e.key))}));for(let t=s.length;t<Eb(e.slots.length);t++){let n=ay(Yd,e.secret,a,wb(`p`,String(t)),64);s.push({i:Y(n.slice(0,16)),w:Y(n.slice(16))})}return{e:Y(e.e),z:Y(a),c:Y(o),s:s.sort((e,t)=>e.i<t.i?-1:+(e.i>t.i))}},Fb=(e,t)=>{let n=`A`.repeat(22);return{e:n,z:n,c:`A`.repeat(Math.ceil((bb.encode(Nb(t)).length+16)*4/3)),s:Array.from({length:Eb(e.slots.length)},()=>({i:n,w:`A`.repeat(64)}))}},Ib=/^[A-Za-z0-9_-]{22}$/,Lb=/^[A-Za-z0-9_-]{64}$/,Rb=e=>{if(typeof e!=`object`||!e)return null;let{e:t,z:n,c:r,s:i}=e;if(typeof t!=`string`||!Ib.test(t)||typeof n!=`string`||!Ib.test(n)||typeof r!=`string`||r===``||X(r)===null||!Array.isArray(i)||i.length>4096)return null;let a=[];for(let e of i){let{i:t,w:n}=e??{};if(typeof t!=`string`||!Ib.test(t)||typeof n!=`string`||!Lb.test(n))return null;a.push({i:t,w:n})}return{e:t,z:n,c:r,s:a}},zb=e=>{let t;try{t=JSON.parse(xb.decode(e))}catch{return null}if(typeof t!=`object`||!t)return null;let{profile:n,sections:r,feed:i,favourites:a,comments:o,panels:s,panelOrder:c,chatRoom:l}=t,u=typeof n==`object`&&n?n:null,d=u===null?null:Ef({displayName:u.displayName,bio:u.bio,links:u.links,version:0}),f=u?.avatar===void 0?null:yf(u.avatar)??null,p=u?.background===void 0?null:yf(u.background)??null,m=Array.isArray(r)?[...new Set(r)].filter(e=>typeof e==`string`&&Object.hasOwn(eb,e)):[],h=Cm(s),g=wm(c),_=Ky(l);return{profile:d===null?null:{displayName:d.displayName,bio:d.bio,links:d.links,...f===null?{}:{avatar:f},...p===null?{}:{background:p}},sections:m,feed:Bh(i),favourites:xy(a),comments:my(o),...h.length>0?{panels:h}:{},...g.length>0?{panelOrder:g}:{},..._===null?{}:{chatRoom:_}}},Bb=(e,t,n)=>{let r=X(n.z);try{return zb(Hg(e,Tb(e,`c`,r).slice(0,24),wb(t.roomId,Sb,t.owner)).decrypt(X(n.c)))}catch{return null}},Vb=(e,t,n)=>Bb(Ob(Db(e),t.roomId,X(n.e)),t,n),Hb=(e,t,n,r)=>{let i=kb(e.dhSeed,t,n.roomId);if(i===null)return null;let a=X(r.z),o=Y(Tb(i,`i`,a).slice(0,16)),s=r.s.find(e=>e.i===o);if(s===void 0)return null;try{return Bb(Hg(i,Tb(i,`w`,a).slice(0,24)).decrypt(X(s.w)),n,r)}catch{return null}},Ub=new TextEncoder,Wb={version:0,profile:null,inbox:null},Gb=e=>Y(Yd(Ub.encode(`${Ny}\u0000${e}`))),Kb=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);if(n.length!==32)throw Error(`social: a public key is 32 bytes`);let r=Ub.encode(`${jy}\u0000${e}\u0000${t}\u0000`),i=new Uint8Array(r.length+32);return i.set(r),i.set(n,r.length),i},qb=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return Ub.encode(`${My}\u0000${e}\u0000${t}\u0000${n}`)},Jb=(e,t,n,r={})=>{let{profile:i,inbox:a,displayName:o,pageRoom:s,page:c,favourites:l,panels:u}=t,{feed:d,comments:f,friends:p}=r;return JSON.stringify({k:Y(n.signKey),n:e,version:t.version,profile:i===null?null:{displayName:i.displayName,bio:i.bio,links:i.links,avatar:i.avatar,background:i.background},...a==null?{}:{inbox:{invite:a,dhKey:Y(n.dhKey)}},...o?{displayName:o}:{},...s==null?{}:{pageRoom:s},...c==null?{}:{page:{accent:c.accent,...c.theme===void 0?{}:{theme:c.theme},sections:c.sections}},...d===void 0||d.length===0?{}:{feed:d.map(Ih)},...l===void 0||l.length===0?{}:{favourites:l.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...f===void 0||f.length===0?{}:{comments:f.map(dy)},...u===void 0||u.length===0?{}:{panels:u.map(xm)},...p===void 0?{}:{friends:{e:p.e,z:p.z,c:p.c,s:p.s.map(({i:e,w:t})=>({i:e,w:t}))}}})},Yb=(e,t)=>({t:`social.name`,v:2,b:e,s:t}),Xb=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},Zb=(e,t,n)=>{try{return Qv.verify(e,t(),n,{zip215:!1})}catch{return!1}},Qb=e=>{if(e==null)return null;if(typeof e!=`object`)return;let{invite:t,dhKey:n}=e,r=Ky(t),i=typeof n==`string`?X(n):null;return r!==null&&i?.length===32?{invite:r,dhKey:i}:void 0},$b=(e,t)=>{if(e===null)return null;if(typeof e!=`object`)return;let{displayName:n,bio:r,links:i,avatar:a,background:o}=e,s=Ef({displayName:n,bio:r,links:i,version:t}),[c,l]=[yf(a),yf(o)];if(s!==null&&c!==void 0&&l!==void 0)return{displayName:s.displayName,bio:s.bio,links:s.links,avatar:c,background:l}},ex=(e,t,n)=>{let{n:r,k:i,s:a}=e;if(r!==n||typeof i!=`string`||typeof a!=`string`)return null;let o=X(i),s=X(a);return o?.length!==32||s?.length!==64?null:Zb(s,()=>Kb(t,n,o),o)?{signKey:o,version:null,profile:null,inbox:null,page:rb,feed:[],favourites:[],comments:[],friends:null}:null},tx=(e,t,n,r)=>{let i=Xb(e);if(i===null||i.t!==`social.name`||!sf(r))return null;if(i.v===1)return ex(i,t,r);let{v:a,b:o,s}=i;if(a!==2||typeof o!=`string`||typeof s!=`string`||Ub.encode(o).length>131072)return null;let c=Xb(o);if(c===null||typeof c.k!=`string`||c.n!==r)return null;let l=X(c.k),u=X(s);if(l?.length!==32||u?.length!==64||!Zb(u,()=>qb(t,n,o),l))return null;let{version:d}=c;if(typeof d!=`number`||!Number.isSafeInteger(d)||d<0)return null;let f=$b(c.profile,d),p=Qb(c.inbox);if(f===void 0||p===void 0)return null;let m=c.pageRoom,h=m==null?void 0:Ky(m);if(h===null)return null;let g=c.displayName,_;if(g!==void 0){if(typeof g!=`string`||g.trim().length===0||hf(g,{max:32,multiline:!1})!==null)return null;_=g}let v=Cm(c.panels);return{signKey:l,version:d,profile:f,inbox:p,..._===void 0?{}:{displayName:_},...h===void 0?{}:{pageRoom:h},page:_b(c.page),feed:Bh(c.feed),favourites:xy(c.favourites),comments:my(c.comments),...v.length>0?{panels:v}:{},friends:Rb(c.friends)}},nx=new TextEncoder,rx=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return nx.encode(`${Ry}\u0000${e}\u0000${t}\u0000${n}`)},ix=(e,t,n={})=>{let{profile:r,page:i,favourites:a,panels:o}=e,{feed:s,comments:c,friends:l}=n;return JSON.stringify({k:Y(t.signKey),version:e.version,profile:r===null?null:{displayName:r.displayName,bio:r.bio,links:r.links,avatar:r.avatar,background:r.background},...i==null?{}:{page:{accent:i.accent,...i.theme===void 0?{}:{theme:i.theme},sections:i.sections}},...s===void 0||s.length===0?{}:{feed:s.map(Ih)},...a===void 0||a.length===0?{}:{favourites:a.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...c===void 0||c.length===0?{}:{comments:c.map(dy)},...o===void 0||o.length===0?{}:{panels:o.map(xm)},...l===void 0?{}:{friends:{e:l.e,z:l.z,c:l.c,s:l.s.map(({i:e,w:t})=>({i:e,w:t}))}}})},ax=(e,t)=>({t:`social.page`,v:1,b:e,s:t}),ox=(e,t,n)=>{let r=Xb(e);if(r===null||r.t!==`social.page`)return null;let{v:i,b:a,s:o}=r;if(i!==1||typeof a!=`string`||typeof o!=`string`||nx.encode(a).length>131072)return null;let s=Xb(a);if(s===null||typeof s.k!=`string`)return null;let c=X(s.k),l=X(o);if(c?.length!==32||l?.length!==64||!Zb(l,()=>rx(t,n,a),c))return null;let{version:u}=s;if(typeof u!=`number`||!Number.isSafeInteger(u)||u<0)return null;let d=$b(s.profile,u);if(d===void 0)return null;let f=Cm(s.panels);return{signKey:c,version:u,profile:d,page:s.page===void 0?rb:_b(s.page),feed:Bh(s.feed),favourites:xy(s.favourites),comments:my(s.comments),...f.length>0?{panels:f}:{},friends:Rb(s.friends)}},sx=e=>new TextEncoder().encode(e),cx=()=>crypto.getRandomValues(new Uint8Array(32)),lx=e=>{if(e.length!==32)throw Error(`social: a seed is 32 bytes`);let t=ay(Yd,e,void 0,sx(wy),32),n=ay(Yd,e,void 0,sx(Ty),32);return{signSeed:t,signKey:Qv.getPublicKey(t),dhSeed:n,dhKey:$v.getPublicKey(n)}},ux=1e4,dx=(e,t,n=ux,r=!1)=>e()?Promise.resolve():new Promise((i,a)=>{let o,s=()=>{t(()=>{}),clearTimeout(c),o!==void 0&&clearTimeout(o),i()},c=setTimeout(()=>{t(()=>{}),o!==void 0&&clearTimeout(o),a(Error(`social: the room did not answer in time`))},n);t(()=>{if(e()){if(!r){s();return}o===void 0&&(o=setTimeout(s,0))}})}),fx=async(e,t,n)=>{let r={},i=()=>{},a=await e.on(n=>{n.type===`message`&&n.message.from===e.self.id&&n.message.text===t&&(r.seq??=n.message.seq,i())});try{await e.send(t,n),await dx(()=>r.seq!==void 0,e=>{i=e})}finally{a()}let o=r.seq,s=(t,n)=>e.delete(t,n).catch(()=>{});o>1&&await s(1,o-1),await s(o+1,2**53-1)},px=async e=>{let t=new Map,n=()=>{},r=await e.on(e=>{e.type===`message`&&(t.set(e.message.seq,{seq:e.message.seq,from:e.message.from,text:e.message.text,type:e.message.envelope?.type??null}),n())});try{let r=null,[i,a]=await Promise.all([e.usage(),e.backlog(0,2).catch(e=>(r=e,null))]);if(i?.messages!==1)return null;if(a===null)throw r??Error(`social: backlog failed`);if(a.last===0||a.more)return null;await dx(()=>t.has(a.last),e=>{n=e},ux,!0)}finally{r()}let i=[...t.values()];return i.length===1?i[0]:null},mx=async e=>(await px(e))?.text??null,hx=e=>({type:`object`,properties:{type:{type:`string`,const:e}},required:[`type`],additionalProperties:!1}),gx={type:`page`},_x={type:`record`},vx={type:`request`},yx={type:`chat`},bx={version:2,types:{page:{envelope:hx(`page`),send:`owner`,maxBytes:262144}}},xx={version:1,types:{request:{envelope:hx(`request`),send:`accounts`,maxBytes:65536,perAccount:{messages:16,bytes:131072}}},maxStoredBytes:4e6},Sx={version:1,types:{page:{envelope:hx(`page`),send:`owner`,maxBytes:262144}}},Cx={version:1,types:{chat:{envelope:hx(`chat`),send:`accounts`,maxBytes:65536}},maxStoredBytes:5e7},wx=(e,t)=>e.schema()===null?void 0:t,Tx=e=>{let t=e.schema()?.types;if(t!==void 0)return Object.hasOwn(t,gx.type)?gx:Object.hasOwn(t,_x.type)?_x:void 0},Ex=e=>{let t=e.schema()?.types;return t!==void 0&&Object.hasOwn(t,gx.type)?gx:void 0},Dx=async(e,t)=>{(e.schema()?.version??0)<t.version&&await e.setSchema(t).catch(()=>{})},Ox=new TextEncoder,kx=e=>Ox.encode(e).length,Ax=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),jx={profile:null,sections:[],members:[],left:[]},Mx=`A`.repeat(86),Nx=(e,t,n,r)=>{if(n===null||!e.claimed||e.owner!==e.self.id)return null;let i=r(n.text,e.id,e.owner);if(i!==null&&Ax(i.signKey,t.signKey))return{proof:i,owner:e.owner,currentOwner:!0};if(n.from===e.owner)return null;let a=r(n.text,e.id,n.from);return a!==null&&Ax(a.signKey,t.signKey)?{proof:a,owner:n.from,currentOwner:!1}:null},Px=(e,t,n,r=e.owner)=>{let i=n.friends===null?null:Vb(t,{roomId:e.id,owner:r},n.friends);return{public:n.feed,friends:i?.feed??[],comments:{public:n.comments,friends:i?.comments??[]}}},Fx=(e,t,n,r,i,a,o)=>{let s=n.friends??null,c=s===null?null:jb(t,e.id,s.members,s.left),l=n.commentsLevel===`public`||n.commentsLevel===`friends`,u=r.comments??oy,[d,f,p,m]=[r.public.slice(0,50),r.friends.slice(0,50),!1,!0],[h,g]=[u.public.slice(0,20),u.friends.slice(0,20)];for(;;){let t=s!==null&&c!==null&&m&&(s.profile!==null||f.length>0||s.favourites!==void 0||(s.panels?.length??0)>0||g.length>0||l||s.chatRoom!==void 0)?p?{profile:null,sections:[],feed:[],comments:[],...s.chatRoom===void 0?{}:{chatRoom:s.chatRoom}}:{profile:s.profile,sections:s.sections,feed:f,favourites:s.favourites,comments:g,...s.panels&&s.panels.length>0?{panels:s.panels}:{},...s.panelOrder&&s.panelOrder.length>0?{panelOrder:s.panelOrder}:{},...s.chatRoom===void 0?{}:{chatRoom:s.chatRoom}}:null,r=i(n,{feed:d,comments:h,friends:c===null||t===null?void 0:Fb(c,t)}),u=a(r,Mx);if(kx(r)<=131072&&kx(u)<=196568||d.length+f.length+h.length+g.length===0&&t===null){let r=c===null||t===null?void 0:Pb(c,{roomId:e.id,owner:e.self.id},t,i(n,{feed:d,comments:h})),s=i(n,{feed:d,comments:h,friends:r});return a(s,o(s))}f.length>0?f=f.slice(0,-1):g.length>0?g=g.slice(0,-1):!p&&t!==null&&s?.chatRoom!==void 0?p=!0:t===null?d.length>0?d=d.slice(0,-1):h=h.slice(0,-1):m=!1}},Ix=async(e,t,n,r,i)=>{for(let a=0;a<2;a++){let a=await px(e),o=Nx(e,t,a,r.read);if(o!==null&&o.currentOwner&&(o.proof.version??-1)>n.version)return`newer`;let s=r.prepare?r.prepare(o,n):n,c=r.emptyFeeds?.(s)||o===null?Dh:Px(e,t,o.proof,o.owner),l=i?.(c)??c,u=n.activity===void 0?l:qh(l,n.activity),d=n.commentsLevel===void 0?u:yy(u,n.commentsLevel),f=s.friends==null&&(d.friends.length>0||(d.comments?.friends.length??0)>0)?{...s,friends:jx}:s,p=r.fit(f,d);if(a?.text===p)return`written`;let m=r.envelope();if(a!==null&&m===gx&&a.type===gx.type&&a.from===e.self.id?await e.edit(a.seq,p,m):await fx(e,p,m),(await px(e))?.text===p)return`written`}return`failed`},Lx=`Your name and public page on FKN Social. Unclaiming it takes your page down and frees the name.`,Rx=e=>e?.code,zx=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`]),Bx=(e,t)=>e.open(t,{key:Gb(t),defaults:{send:!1,receive:!0}}),Vx=async e=>{e.defaults().send&&await e.setDefault(`send`,!1).catch(()=>{}),await Dx(e,bx)},Hx=(e,t)=>{let n=Rx(e);return n===`bad-key`||n===`denied`?`taken`:n===`full`?t===`open`?`busy`:`out-of-claims`:`unavailable`},Ux=async(e,t)=>{let n=await mx(e);return n===null?null:tx(n,e.id,e.owner,t)},Wx=async(e,t,n)=>{let r=await Ux(e,t);return r!==null&&Ax(r.signKey,n)},Gx=(e,t,n,r,i=`none`)=>Ix(e,t.keys,n,{read:(e,n,r)=>tx(e,n,r,t.name),prepare:(e,n)=>{if(i===`none`||e===null)return n;let r=e.proof.inbox!==null&&Ax(e.proof.inbox.dhKey,t.keys.dhKey)?e.proof.inbox.invite:null;return{...n,inbox:r,...i===`all`&&e.proof.displayName!==void 0?{displayName:e.proof.displayName}:{},...i===`all`&&e.proof.pageRoom!==void 0?{pageRoom:e.proof.pageRoom}:{}}},emptyFeeds:e=>typeof e.pageRoom==`string`,fit:(n,r)=>Fx(e,t.keys,n,r,(e,n)=>Jb(t.name,e,t.keys,n),(e,t)=>JSON.stringify(Yb(e,t??``)),n=>Y(Qv.sign(qb(e.id,e.self.id,n),t.keys.signSeed))),envelope:()=>Tx(e)},r),Kx=async(e,t,n,r,i)=>{let a;try{a=await Bx(e,n)}catch(e){return{ok:!1,reason:Hx(e,`open`)}}try{try{await a.claim({description:Lx})}catch(e){return{ok:!1,reason:Hx(e,`claim`)}}return await Vx(a),await Gx(a,{keys:t,name:n},r??Wb,i,r===void 0?`all`:`none`).catch(()=>`failed`)===`failed`?{ok:!1,reason:`unrecorded`}:{ok:!0}}finally{await a.leave().catch(()=>{})}},qx=async(e,t)=>{let n;try{n=await Bx(e,t)}catch(e){return Rx(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},Jx=async(e,t,n,r,i)=>{if(!sf(t.name))return`retired`;let a;try{a=await Bx(e,t.name)}catch(e){return Rx(e)===`bad-key`?`taken`:`unknown`}try{if(!a.claimed)return`lost`;if(a.owner!==a.self.id)return`taken`;await Vx(a);let e=await n();if(e===null)return await Wx(a,t.name,t.keys.signKey)?`held`:`unrecorded`;let o=await r(e,async()=>{let e=Nx(a,t.keys,await px(a),(e,n,r)=>tx(e,n,r,t.name));return e===null?Dh:Px(a,t.keys,e.proof,e.owner)});if(o===null)return await Wx(a,t.name,t.keys.signKey)?`held`:`unrecorded`;let s=Gx(a,t,o).catch(()=>`failed`);return i?.refreshClaim!==!1&&await a.claim({description:Lx}).catch(()=>{}),await s===`failed`?`unrecorded`:`held`}catch{return`unknown`}finally{await a.leave().catch(()=>{})}},Yx=async(e,t,n,r)=>{if(!sf(t.name))return`failed`;let i;try{i=await Bx(e,t.name)}catch{return`failed`}try{return!i.claimed||i.owner!==i.self.id?`failed`:await Gx(i,t,n,r,`inbox`)}catch{return`failed`}finally{await i.leave().catch(()=>{})}},Xx=async(e,t,n,r,i)=>{let a=!1,o=await Yx(e,t,n,e=>(a=Hh(e,r.app,r.at-Eh)>=10,a?e:{...e,[i]:Kh(e[i],r)}));return a?`too-many`:o},Zx=async(e,t,n)=>{if(!sf(n))return Dh;let r;try{r=await Bx(e,n)}catch(e){return zx.has(String(Rx(e)))?Dh:null}try{let e=Nx(r,t,await px(r),(e,t,r)=>tx(e,t,r,n));return e===null?Dh:Px(r,t,e.proof,e.owner)}catch{return null}finally{r.leave().catch(()=>{})}},Qx=async(e,t)=>{if(!sf(t.name))return{inbox:null,pageRoom:null,chatRoom:null};let n;try{n=await Bx(e,t.name)}catch{return{inbox:null,pageRoom:null,chatRoom:null}}let r=null,i=null,a=null;try{let e=Nx(n,t.keys,await px(n),(e,n,r)=>tx(e,n,r,t.name));i=e!==null&&e.proof.inbox!==null&&Ax(e.proof.inbox.dhKey,t.keys.dhKey)?e.proof.inbox.invite:null,r=e?.proof.pageRoom??null,e?.proof.friends!=null&&(a=Vb(t.keys,{roomId:n.id,owner:e.owner},e.proof.friends)?.chatRoom??null)}catch{return{inbox:null,pageRoom:null,chatRoom:null}}finally{await n.leave().catch(()=>{})}return{inbox:i,pageRoom:r,chatRoom:a}},$x=async(e,t,n)=>{if(e.join===void 0)return null;let r=null;try{r=await e.join(n);let i=await mx(r),a=i===null?null:ox(i,r.id,r.owner);return a!==null&&Ax(a.signKey,t.keys.signKey)&&a.friends!==null?Vb(t.keys,{roomId:r.id,owner:r.owner},a.friends)?.chatRoom??null:null}catch{return null}finally{r!==null&&await r.leave().catch(()=>{})}},eS=async(e,t,n)=>{if(!sf(t))return!1;let r;try{r=await Bx(e,t)}catch(e){return Rx(e)!==`bad-key`&&null}try{return await Wx(r,t,n)}catch{return null}finally{r.leave().catch(()=>{})}},tS=async(e,t)=>{let n;try{n=await Bx(e,t)}catch(e){let t=String(Rx(e));return t===`full`?{view:{kind:`busy`}}:{view:zx.has(t)?{kind:`none`}:{kind:`unavailable`}}}try{if(!n.claimed)return{view:{kind:`unheld`}};let e=await mx(n),r=e===null?null:tx(e,n.id,n.owner,t);if(r===null)return{view:{kind:`none`}};let i={kind:`shown`,signKey:r.signKey,...r.displayName===void 0?{}:{displayName:r.displayName},profile:r.profile,inbox:r.inbox,page:r.page,feed:r.feed,favourites:r.favourites,comments:r.comments,...r.panels===void 0?{}:{panels:r.panels}};return r.pageRoom!==void 0&&e!==null?{view:i,pageRoom:r.pageRoom,coreRecord:{roomId:n.id,owner:n.owner,text:e}}:{view:r.friends===null||e===null?i:{...i,record:{name:t,roomId:n.id,owner:n.owner,text:e}}}}catch{return{view:{kind:`unavailable`}}}finally{n.leave().catch(()=>{})}},nS=async(e,t)=>(await tS(e,t)).view,rS=async(e,t)=>{let n=await tS(e,t);if(n.view.kind!==`shown`||n.pageRoom===void 0)return n.view;if(e.join===void 0)return{kind:`unavailable`};let r;try{r=await e.join(n.pageRoom)}catch(e){let t=String(Rx(e));return t===`full`?{kind:`busy`}:zx.has(t)?n.view:{kind:`unavailable`}}try{if(!r.claimed)return n.view;let e=await mx(r),i=e===null?null:ox(e,r.id,r.owner);if(i===null||!Ax(i.signKey,n.view.signKey))return n.view;let a={...n.view,profile:i.profile,page:i.page,feed:i.feed,favourites:i.favourites,comments:i.comments,...i.panels===void 0?{}:{panels:i.panels}};return i.friends===null||e===null?a:{...a,record:{name:t,roomId:r.id,owner:r.owner,text:e,...n.coreRecord?{core:n.coreRecord}:{}}}}catch{return{kind:`unavailable`}}finally{r.leave().catch(()=>{})}},iS=`FKNS`,aS=e=>{if(e.length!==32)throw Error(`social: a seed is 32 bytes`);return`${iS}-${(Qd(e).match(/.{1,4}/g)??[]).join(`-`)}`},oS=e=>{let t=ef(e),n=t.length===56&&t.startsWith(`FKNS`)?t.slice(4):t;if(n.length!==52||!$d(n))return null;let r=tf(n);return r!==null&&r.length===32?r:null},sS=new TextEncoder,cS=new TextDecoder,lS=e=>sS.encode(e),uS=Uint8Array.of(0),dS=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},fS=(e,t,n)=>ay(Yd,$v.getSharedSecret(e,t),lS(n),lS(ky),32),pS=(e,t,n,r,i)=>{if(n.length!==32)throw Error(`social: a pairing nonce is 32 bytes`);let[a,o]=[r,i].sort(),s=dS([lS(Ay),uS,lS(a),uS,lS(o)]);return ay(Yd,$v.getSharedSecret(e,t),n,s,32)},mS=(e,t,n,r,i,a)=>dS([lS(e),uS,lS(t),uS,lS(n),uS,lS(r),uS,lS(i),uS,Yd(a)]),hS=(e,t)=>{let n=crypto.getRandomValues(new Uint8Array(24));return dS([n,Hg(e,n).encrypt(t)])},gS=(e,t)=>{if(t.length<=24)return null;try{return Hg(e,t.slice(0,24)).decrypt(t.slice(24))}catch{return null}},_S={"social.offer":Dy,"social.accept":Oy},vS=(e,t,n,r)=>{let i=hS(fS(r.dhSeed,r.theirDhKey,n.roomId),lS(JSON.stringify(t)));return{t:e,v:1,to:n.toMemberId,i:n.id,b:Y(i),s:Y(Qv.sign(mS(_S[e],n.roomId,n.fromMemberId,n.toMemberId,n.id,i),r.signSeed))}},yS=(e,t,n)=>vS(`social.offer`,{n:Y(e.nonce),p:e.profile,x:e.inbox,...e.chatRoom==null?{}:{m:e.chatRoom}},t,n),bS=(e,t,n)=>vS(`social.accept`,{o:e.offerId,p:e.profile,x:e.inbox,...e.chatRoom==null?{}:{m:e.chatRoom}},t,n),xS=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return(t.t===`social.offer`||t.t===`social.accept`)&&t.v===1&&typeof t.to==`string`&&typeof t.i==`string`&&typeof t.b==`string`&&typeof t.s==`string`},SS=(e,t,n,r)=>{if(!xS(t)||t.t!==e)return{ok:!1,reason:`malformed`};if(t.to!==n.selfMemberId)return{ok:!1,reason:`not-for-me`};let i=X(t.b),a=X(t.s);if(!i||!a||a.length!==64)return{ok:!1,reason:`malformed`};let o=mS(_S[e],n.roomId,n.fromMemberId,n.selfMemberId,t.i,i);try{if(!Qv.verify(a,o,r.theirSignKey,{zip215:!1}))return{ok:!1,reason:`bad-signature`}}catch{return{ok:!1,reason:`bad-signature`}}let s=gS(fS(r.dhSeed,r.theirDhKey,n.roomId),i);if(!s)return{ok:!1,reason:`unsealed`};if(s.length>16384)return{ok:!1,reason:`malformed`};try{let e=JSON.parse(cS.decode(s));return typeof e!=`object`||!e?{ok:!1,reason:`malformed`}:{ok:!0,id:t.i,body:e}}catch{return{ok:!1,reason:`malformed`}}},CS=e=>e==null?null:Ky(e)??void 0,wS=(e,t,n)=>{let r=SS(`social.offer`,e,t,n);if(!r.ok)return r;let i=typeof r.body.n==`string`?X(r.body.n):null,a=Ef(r.body.p),o=CS(r.body.x),s=CS(r.body.m);return i?.length!==32||a===null||o===void 0||s===void 0?{ok:!1,reason:`malformed`}:{ok:!0,id:r.id,body:{nonce:i,profile:a,inbox:o,...s===null?{}:{chatRoom:s}}}},TS=(e,t,n)=>{let r=SS(`social.accept`,e,t,n);if(!r.ok)return r;let i=Ef(r.body.p),a=CS(r.body.x),o=CS(r.body.m);return typeof r.body.o!=`string`||i===null||a===void 0||o===void 0?{ok:!1,reason:`malformed`}:{ok:!0,body:{offerId:r.body.o,profile:i,inbox:a,...o===null?{}:{chatRoom:o}}}},ES=(e,t)=>`${e}/${t}`,DS=/^[A-Za-z0-9_-]{8,64}$/,OS=new Set([`general`,`panels`,`layout`,`visibility`]),kS=200,AS=e=>{if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||e.includes(`\0`))return null;let t=e===`/`?`/`:e.replace(/\/+$/,``);if(t===`/`)return{tab:`overview`};let n=t.slice(1).split(`/`);if(n.some(e=>e===``))return null;let[r,i,a]=n;if(n.length===1)switch(r){case`overview`:return{tab:`overview`};case`customize`:return{tab:`customize`,customizeTab:`general`};case`friends`:return{tab:`friends`};case`messages`:return{tab:`messages`};case`inbox`:return{tab:`inbox`};case`apps`:return{tab:`apps`};case`account`:return{tab:`account`};default:return null}if(n.length===2){if(r===`customize`&&i!==void 0&&OS.has(i))return{tab:`customize`,customizeTab:i};if(r===`friends`&&i!==void 0){let e=of(i);return e.ok?{tab:`friends`,friendName:e.name}:null}if(r===`messages`&&i!==void 0){let e=of(i);return e.ok?{tab:`messages`,peerName:e.name}:null}return null}return n.length===3&&r===`messages`&&i===`group`&&a!==void 0&&DS.test(a)?{tab:`messages`,groupId:a}:null},jS=e=>{switch(e.tab){case`overview`:return`/overview`;case`customize`:return`/customize/${e.customizeTab}`;case`friends`:return e.friendName?`/friends/${e.friendName}`:`/friends`;case`messages`:return e.groupId?`/messages/group/${e.groupId}`:e.peerName?`/messages/${e.peerName}`:`/messages`;case`inbox`:return`/inbox`;case`apps`:return`/apps`;case`account`:return`/account`}},MS=e=>typeof e==`string`&&e.length>0&&e.length<=kS&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&AS(e)!==null,NS=new TextEncoder,PS=new TextDecoder,FS=e=>NS.encode(e),IS=Uint8Array.of(0),LS=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},RS=(e,t)=>{let n=typeof e==`string`?X(e):null;return n===null?null:t===void 0||n.length===t?n:null},zS=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},BS=4e3,VS=/^[A-Za-z0-9_-]{16,64}$/,HS=/^[A-Za-z0-9_-]{22}$/,US=e=>{let t=e.replace(/\r\n?/g,`
11
- `).normalize(`NFC`);return t.trim().length===0?null:hf(t,{max:4e3,multiline:!0})===null?t:null},WS=e=>{let t=e.normalize(`NFC`).trim();return t.length===0?null:hf(t,{max:80,multiline:!1})===null?t:null},GS=(e,t)=>{let n=RS(t.signKey,32),r=RS(t.dhKey,32),i=RS(t.pairNonce,32);if(n===null||r===null||i===null)return null;try{return pS(e.dhSeed,r,i,cf(e.signKey),cf(n))}catch{return null}},KS=e=>Y(ty(Yd,e,FS(`${zy}\u0000id`)).slice(0,16)),qS=(e,t)=>ay(Yd,e,FS(t),FS(zy),32),JS=(e,t)=>ay(Yd,e,FS(t),FS(By),32),YS=(e,t)=>ay(Yd,e,FS(t),FS(Hy),32),XS=(e,t,n,r,i)=>{let a=$v.getSharedSecret(e,t);if(a.every(e=>e===0))throw Error(`social: invalid peer agreement key`);let[o,s]=n<r?[n,r]:[r,n];return ay(Yd,a,FS(`${i}\u0000${o}\u0000${s}`),FS(Wy),32)},ZS=(e,t,n)=>ay(Yd,e,FS(`${t}\u0000${n}`),FS(Uy),32),QS=(e,t)=>Y(ty(Yd,e,FS(`gk-tag\u0000${t}`)).slice(0,16)),$S=()=>Y(crypto.getRandomValues(new Uint8Array(16))),eC=(e,t,n,r,i)=>{if(e.includes(`\0`)||t.includes(`\0`)||i.includes(`\0`))throw Error(`social: signed chat field may not contain NUL`);return LS([FS(e),IS,FS(t),IS,FS(n),IS,FS(String(r)),IS,FS(i)])},tC=(e,t,n,r,i,a)=>{if(e.includes(`\0`)||t.includes(`\0`)||i.includes(`\0`))throw Error(`social: signed chat field may not contain NUL`);return FS(`${Vy}\u0000${e}\u0000${t}\u0000${n}\u0000${r}\u0000${i}\u0000${a}`)},nC=e=>{let t=e.ep??0,n=JSON.stringify(e.body),r=Y(Qv.sign(tC(e.roomId,e.ch,e.kind,t,e.id,n),e.signSeed)),i=FS(JSON.stringify({b:n,s:r})),a=crypto.getRandomValues(new Uint8Array(24)),o=Hg(e.key,a,eC(e.roomId,e.ch,e.kind,t,e.id)).encrypt(i),s=new Uint8Array(24+o.length);s.set(a),s.set(o,24);let c={t:`social.chat`,v:1,k:e.kind,ch:e.ch,...e.ep===void 0?{}:{ep:e.ep},...e.p===void 0?{}:{p:e.p},i:e.id,b:Y(s)};return JSON.stringify(c)},rC=(e,t,n)=>{let r=X(e.b);if(r===null||r.length<=24)return null;let i=e.ep??0,a;try{a=Hg(n,r.slice(0,24),eC(t,e.ch,e.k,i,e.i)).decrypt(r.slice(24))}catch{return null}let o=zS(PS.decode(a));if(o===null||typeof o.b!=`string`||typeof o.s!=`string`)return null;let s=RS(o.s,64),c=zS(o.b),l=RS(c?.from,32);if(s===null||c===null||l===null)return null;try{if(!Qv.verify(s,tC(t,e.ch,e.k,i,e.i,o.b),l,{zip215:!1}))return null}catch{return null}return{senderSignKey:l,senderFingerprint:cf(l),body:c}},iC=(e,t,n,r,i,a,o=$S())=>{let s=US(i);if(s===null||!VS.test(o))return null;let c=GS(t,r);if(c===null)return null;let l=KS(c);return nC({roomId:e,kind:`dm`,ch:l,id:o,key:qS(c,l),signSeed:t.signSeed,body:{from:Y(t.signKey),name:n,body:s,at:a}})},aC=e=>{let t=e.id??$S();if(!VS.test(t)||!DS.test(e.groupId))throw Error(`social: invalid group control frame id`);return nC({roomId:e.roomId,kind:`gk`,ch:e.groupId,ep:e.epoch,p:QS(e.sealKey,e.groupId),id:t,key:e.sealKey,signSeed:e.myKeys.signSeed,body:{from:Y(e.myKeys.signKey),action:e.action,groupId:e.groupId,epoch:e.epoch,title:e.title,members:e.members.map(e=>({signKey:e.signKey,dhKey:e.dhKey,name:e.name,...Ky(e.chatRoom)?{chatRoom:Ky(e.chatRoom)}:{}})),key:e.groupKey===null?``:Y(e.groupKey),at:e.at}})},oC=e=>{let t=US(e.body),n=e.id??$S();return t===null||!VS.test(n)||!DS.test(e.groupId)?null:nC({roomId:e.roomId,kind:`gm`,ch:e.groupId,ep:e.epoch,id:n,key:ZS(e.groupKey,e.groupId,e.epoch),signSeed:e.myKeys.signSeed,body:{from:Y(e.myKeys.signKey),name:e.myName,body:t,at:e.at}})},sC=e=>{let t=zS(e);return t===null||t.t!==`social.chat`||t.v!==1||t.k!==`dm`&&t.k!==`gk`&&t.k!==`gm`||typeof t.ch!=`string`||t.ch.length===0||t.ch.length>64||typeof t.i!=`string`||!VS.test(t.i)||typeof t.b!=`string`||t.b.length===0?null:t.k===`dm`?t.ep!==void 0||t.p!==void 0?null:{t:`social.chat`,v:1,k:`dm`,ch:t.ch,i:t.i,b:t.b}:!DS.test(t.ch)||typeof t.ep!=`number`||!Number.isSafeInteger(t.ep)||t.ep<1?null:t.k===`gk`?typeof t.p!=`string`||!HS.test(t.p)?null:{t:`social.chat`,v:1,k:`gk`,ch:t.ch,ep:t.ep,p:t.p,i:t.i,b:t.b}:{t:`social.chat`,v:1,k:`gm`,ch:t.ch,ep:t.ep,i:t.i,b:t.b}},cC=(e,t=!1)=>{if(!Array.isArray(e)||!t&&e.length===0||e.length>32)return null;let n=new Set,r=[];for(let t of e){if(typeof t!=`object`||!t)return null;let{signKey:e,dhKey:i,name:a,chatRoom:o}=t;if(typeof e!=`string`||typeof i!=`string`||typeof a!=`string`||!sf(a))return null;let s=RS(e,32),c=RS(i,32);if(s===null||c===null)return null;let l=o==null?null:Ky(o);if(o!=null&&l===null)return null;let u=cf(s);if(n.has(u))return null;n.add(u),r.push({signKey:e,dhKey:i,name:a,...l===null?{}:{chatRoom:l},fingerprint:u})}return r},lC=(e,t)=>{let n=new Map,r=new Map;for(let i of t){if(i.state!==`active`)continue;let t=RS(i.signKey,32),a=GS(e,i);if(t===null||a===null)continue;let o=KS(a),s={fingerprint:i.fingerprint,name:i.name,signKey:t,secret:a,dmChannel:o,dmKey:qS(a,o)};n.set(i.fingerprint,s),r.set(o,s)}return{friendsByFp:n,dmByChannel:r}},uC=(e,t,n)=>{let{friendsByFp:r,dmByChannel:i}=lC(e,n);return{myKeys:e,myFingerprint:cf(e.signKey),myName:t,friendsByFp:r,dmByChannel:i,dmMessages:new Map,groups:new Map,pendingDm:new Map,pendingGk:new Map,pendingGm:new Map}},dC=(e,t,n)=>{if(!e.has(t)&&e.size>=64){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let r=e.get(t)??[];r.some(e=>e.seq===n.seq&&e.frame.i===n.frame.i)||(r.push(n),r.length>64&&r.shift(),e.set(t,r))},fC=e=>{for(;e.size>500;){let t=null,n=1/0;for(let[r,i]of e)i.seq<n&&(n=i.seq,t=r);if(t===null)break;e.delete(t)}},pC=e=>{if(typeof e!=`string`)return null;let t=US(e);return t===e?t:null},mC=(e,t,n)=>{if(t===e.myFingerprint)return e.myName;let r=e.friendsByFp.get(t);return r===void 0?n?.find(e=>e.fingerprint===t)?.name??t.slice(0,8):r.name},hC=e=>e.reduce((e,t)=>t.controlId<e.controlId?t:e).key,gC=(e,t)=>{for(;e.size>64;){let n=e.keys().next().value;if(n===void 0||n===t)break;e.delete(n)}},_C=(e,t)=>{let n=new Map(e.members.map(e=>[e.fingerprint,e])),r=[];for(let e of t){let t=n.get(e.fingerprint);if(t!==void 0){if(e.signKey!==t.signKey||e.dhKey!==t.dhKey)return null;r.push(t)}else r.push(e)}return r},vC=(e,t,n,r)=>{let i=e.dmByChannel.get(n.ch);if(i===void 0)return`defer`;let a=rC(n,r,i.dmKey);if(a===null)return`drop`;let{senderFingerprint:o,body:s}=a;if(o!==e.myFingerprint&&o!==i.fingerprint)return`drop`;let c=pC(s.body);if(c===null||typeof s.name!=`string`||!sf(s.name)||typeof s.at!=`number`||!Number.isSafeInteger(s.at)||s.at<0)return`drop`;let l=e.dmMessages.get(i.fingerprint);l===void 0&&(l=new Map,e.dmMessages.set(i.fingerprint,l));let u=l.get(n.i);return u===void 0?(l.set(n.i,{id:n.i,seq:t,conversationId:i.fingerprint,senderFingerprint:o,senderName:o===e.myFingerprint?e.myName:i.name,body:c,at:s.at,self:o===e.myFingerprint}),fC(l),`applied`):t<u.seq?(l.set(n.i,{...u,seq:t}),`applied`):`drop`},yC=(e,t)=>{let{friendsByFp:n,dmByChannel:r}=lC(e.myKeys,t);e.friendsByFp=n,e.dmByChannel=r;let i=!1;for(let[t,n]of e.pendingDm)if(e.dmByChannel.has(t)){e.pendingDm.delete(t);for(let t of[...n].sort((e,t)=>e.seq-t.seq))vC(e,t.seq,t.frame,t.roomId)===`applied`&&(i=!0)}return i},bC=(e,t,n,r)=>{let i=n.ch,a=n.ep??0;if(a<1||a>1e6)return`drop`;let o=n.p??``,s=null,c=null,l=null,u=JS(e.myKeys.dhSeed,i);if(QS(u,i)===o&&(s=u,c=`self`,l=e.myFingerprint),s===null)for(let t of e.friendsByFp.values()){let e=YS(t.secret,i);if(QS(e,i)===o){s=e,c=`friend`,l=t.fingerprint;break}}let d=e.groups.get(i);if(s===null&&d!==void 0)for(let t of d.members){if(t.fingerprint===e.myFingerprint)continue;let n=RS(t.dhKey,32);if(n!==null)try{let r=XS(e.myKeys.dhSeed,n,e.myFingerprint,t.fingerprint,i);if(QS(r,i)===o){s=r,c=`member`,l=t.fingerprint;break}}catch{continue}}if(s===null||c===null||l===null)return d===void 0?`defer`:`drop`;let f=rC(n,r,s);if(f===null)return`drop`;let{senderFingerprint:p,body:m}=f;if(p!==l)return`drop`;let h=m.action;if(h!==`create`&&h!==`add`&&h!==`leave`&&h!==`rekey`||m.groupId!==i||m.epoch!==a||typeof m.at!=`number`||!Number.isSafeInteger(m.at)||m.at<0)return`drop`;let g=typeof m.title==`string`?WS(m.title):null,_=cC(m.members,h===`leave`);if(g===null||g!==m.title||_===null)return`drop`;let v=new Set(_.map(e=>e.fingerprint)),y=v.has(e.myFingerprint),b=v.has(p);if(d===void 0){if(h===`rekey`)return`defer`;if(h===`create`){if(a!==1||!b||!y||_.length<2)return`drop`;let t=RS(m.key,32);if(t===null)return`drop`;let r=new Map;return r.set(1,[{key:t,members:v,controlId:n.i}]),e.groups.set(i,{id:i,title:g,epoch:1,members:_,active:!0,key:t,epochKeys:r,messagesById:new Map,createdAt:m.at}),`applied`}if(h===`add`){if(c!==`friend`&&c!==`self`||a<2||!b||!y||_.length<2)return`drop`;let t=RS(m.key,32);if(t===null)return`drop`;let r=new Map;return r.set(a,[{key:t,members:v,controlId:n.i}]),e.groups.set(i,{id:i,title:g,epoch:a,members:_,active:!0,key:t,epochKeys:r,messagesById:new Map,createdAt:m.at}),`applied`}return p!==e.myFingerprint||y||m.key!==``?`drop`:(e.groups.set(i,{id:i,title:g,epoch:a,members:_,active:!1,key:null,epochKeys:new Map,messagesById:new Map,createdAt:m.at}),`applied`)}if(!d.active){if(h!==`add`||c!==`friend`&&c!==`self`||a<=d.epoch||!b||!y||_.length<2||g!==d.title)return`drop`;let e=_C(d,_),t=RS(m.key,32);return e===null||t===null?`drop`:(d.epoch=a,d.members=e,d.active=!0,d.key=t,d.epochKeys.set(a,[{key:t,members:v,controlId:n.i}]),gC(d.epochKeys,a),`applied`)}let x=new Set(d.members.map(e=>e.fingerprint));if(!x.has(p)||g!==d.title)return`drop`;let S=_C(d,_);if(S===null||a<d.epoch)return`drop`;if(a>d.epoch+1)return a<=d.epoch+16?`defer`:`drop`;if(a===d.epoch){if(h!==`rekey`||!b||!y||_.length!==d.members.length||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let e=RS(m.key,32);if(e===null)return`drop`;let t=d.epochKeys.get(a)??[];if(t.some(e=>e.controlId===n.i)||t.length>=4)return`drop`;let r=[...t,{key:e,members:v,controlId:n.i}];return d.epochKeys.set(a,r),d.key=hC(r),`applied`}if(h===`add`){if(!b||!y||_.length!==d.members.length+1||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let e=RS(m.key,32);return e===null?`drop`:(d.epoch=a,d.members=S,d.active=!0,d.key=e,d.epochKeys.set(a,[{key:e,members:v,controlId:n.i}]),gC(d.epochKeys,a),`applied`)}if(h===`leave`)return b||m.key!==``||_.length!==d.members.length-1||!S.every(e=>x.has(e.fingerprint))?`drop`:(d.epoch=a,d.members=S,d.active=y,d.key=null,`applied`);if(h!==`rekey`||!b||!y||_.length!==d.members.length||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let C=RS(m.key,32);return C===null?`drop`:(d.epoch=a,d.members=S,d.active=!0,d.key=C,d.epochKeys.set(a,[{key:C,members:v,controlId:n.i}]),gC(d.epochKeys,a),`applied`)},xC=(e,t,n,r)=>{let i=e.groups.get(n.ch),a=n.ep??0,o=i?.epochKeys.get(a);if(i===void 0||o===void 0||o.length===0)return`defer`;for(let s of o){let o=rC(n,r,ZS(s.key,i.id,a));if(o===null)continue;let{senderFingerprint:c,body:l}=o;if(c!==e.myFingerprint&&!s.members.has(c))continue;let u=pC(l.body);if(u===null||typeof l.name!=`string`||!sf(l.name)||typeof l.at!=`number`||!Number.isSafeInteger(l.at)||l.at<0)return`drop`;let d=i.messagesById.get(n.i);return d===void 0?(i.messagesById.set(n.i,{id:n.i,seq:t,conversationId:i.id,senderFingerprint:c,senderName:mC(e,c,i.members),body:u,at:l.at,self:c===e.myFingerprint}),fC(i.messagesById),`applied`):t<d.seq?(i.messagesById.set(n.i,{...d,seq:t}),`applied`):`drop`}return`drop`},SC=(e,t)=>{let n=!1;for(let r=!0;r;){r=!1;let i=e.pendingGk.get(t);if(i!==void 0&&i.length>0){let a=[],o=[...i].sort((e,t)=>(e.frame.ep??0)-(t.frame.ep??0)||e.seq-t.seq);for(let t of o){let i=bC(e,t.seq,t.frame,t.roomId);i===`applied`?(n=!0,r=!0):i===`defer`&&a.push(t)}a.length===0?e.pendingGk.delete(t):e.pendingGk.set(t,a)}}let r=e.pendingGm.get(t);if(r!==void 0&&r.length>0){let i=[];for(let t of[...r].sort((e,t)=>e.seq-t.seq)){let r=xC(e,t.seq,t.frame,t.roomId);r===`applied`?n=!0:r===`defer`&&i.push(t)}i.length===0?e.pendingGm.delete(t):e.pendingGm.set(t,i)}return n},CC=(e,t,n,r)=>{let i=sC(n);if(i===null)return!1;if(i.k===`dm`){let n=vC(e,t,i,r);return n===`applied`||(n===`defer`&&dC(e.pendingDm,i.ch,{seq:t,roomId:r,frame:i}),!1)}if(i.k===`gk`){let n=bC(e,t,i,r);return n===`applied`?(SC(e,i.ch),!0):(n===`defer`&&dC(e.pendingGk,i.ch,{seq:t,roomId:r,frame:i}),!1)}let a=xC(e,t,i,r);return a===`applied`||(a===`defer`&&dC(e.pendingGm,i.ch,{seq:t,roomId:r,frame:i}),!1)},wC=(e,t,n)=>{let r=!1;for(let i of e.dmMessages.values())for(let[e,a]of i)a.seq>=t&&a.seq<=n&&(i.delete(e),r=!0);for(let i of e.groups.values())for(let[e,a]of i.messagesById)a.seq>=t&&a.seq<=n&&(i.messagesById.delete(e),r=!0);return r},TC=e=>e===void 0||e.size===0?[]:[...e.values()].sort((e,t)=>e.seq-t.seq||e.at-t.at||(e.id<t.id?-1:+(e.id>t.id))),EC=e=>{let t={};for(let[n,r]of e.dmMessages){let i=TC(r).map(t=>({...t,senderName:t.self?e.myName:e.friendsByFp.get(t.senderFingerprint)?.name??t.senderName}));i.length>0&&(t[n]=i)}return{directMessages:t,groups:[...e.groups.values()].map(t=>{let n=t.members.map(n=>({...n,name:mC(e,n.fingerprint,t.members)})),r=TC(t.messagesById).map(t=>({...t,senderName:mC(e,t.senderFingerprint,n)})),i=r.at(-1)?.seq??0;return{id:t.id,title:t.title,epoch:t.epoch,members:n,active:t.active,messages:r,lastSeq:i}}).sort((t,n)=>{let r=t.messages.at(-1)?.at??e.groups.get(t.id)?.createdAt??0;return(n.messages.at(-1)?.at??e.groups.get(n.id)?.createdAt??0)-r||t.id.localeCompare(n.id)})}},DC=`Your encrypted direct and group messages on FKN Social. Unclaiming it deletes stored messages here.`,OC={send:!0,receive:!1,maxMessageBytes:65536},kC=5e3,AC=e=>e?.code,jC=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`,`invalid`]),MC=e=>{let t=e.profile.chatRoom;return t===void 0?void 0:Ky(t.value)},NC=async(e,t)=>{if(t!==void 0){let n=await Z(e,e=>MC(e)===t?{chatRoom:null}:{});if(!n.ok)return n}let n;try{n=await e.rooms.create({defaults:OC,schema:Cx})}catch(e){return{ok:!1,reason:AC(e)===`full`?`busy`:`unavailable`}}try{try{await n.claim({description:DC})}catch(t){if(AC(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>MC(e)===void 0?{chatRoom:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}let t=await Z(e,e=>typeof MC(e)==`string`?{}:{chatRoom:n.invite});return(!t.ok||MC(t.roster)!==n.invite)&&await n.release().catch(()=>{}),t}finally{await n.leave().catch(()=>{})}},PC=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return AC(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},FC=[2e3,5e3,1e4,3e4],IC=(e,t,n,r,i,a)=>{let o=a?.backoffMs??FC,s=a?.sleep??(e=>new Promise(t=>setTimeout(t,e))),c=!1,l=null,u=()=>{},d=r(),f=0,p=uC(t,n,Hf(d)),m=Promise.resolve(),h=e=>{let t=m.then(e,e);return m=t.catch(()=>{}),t},g=async()=>{u(),u=()=>{};let e=l;l=null,e!==null&&await e.leave().catch(()=>{})},_=async t=>{let n=await Z(e,e=>MC(e)===t?{chatRoom:null}:{});n.ok&&(d=n.roster,i.onRoster(n.roster))},v=()=>{i.onUpdate(EC(p))},y=async(t,n)=>{let r;try{r=await e.rooms.join(t)}catch(e){return c?{status:`unavailable`}:AC(e)===`bad-key`?(await _(t),i.onStatus(`none`),{status:`none`,roster:d}):(i.onStatus(`unavailable`),{status:`unavailable`})}if(c)return await r.leave().catch(()=>{}),{status:`unavailable`};l=r;try{if(!r.claimed)return await g(),await _(t),i.onStatus(`none`),{status:`none`,roster:d};if(r.owner!==r.self.id)return await g(),i.onStatus(`taken`),{status:`taken`};if(await Dx(r,Cx),c)return await g(),{status:`unavailable`};if(r.mailbox===null)return await g(),i.onStatus(`not-kept`),{status:`not-kept`};let e=!0,a=new Map,o=()=>{};u=await r.on(n=>{if(!(c||l!==r)){if(n.type===`message`)e?(a.set(n.message.seq,n.message.text),o()):(n.message.seq>f&&(f=n.message.seq),h(async()=>{!c&&CC(p,n.message.seq,n.message.text,r.id)&&v()}));else if(n.type===`deleted`){if(e)for(let e of a.keys())e>=n.from&&e<=n.to&&a.delete(e);h(async()=>{!c&&wC(p,n.from,n.to)&&v()})}else n.type===`claim`&&h(async()=>{c||l!==r||(n.claimed?n.owner===r.self.id?n.mailbox||i.onStatus(`not-kept`):(await g(),i.onStatus(`taken`)):(await g(),await _(t),i.onStatus(`none`)))})}});let s=n;for(;!c;){let e=await r.backlog(s);e.last>s&&await dx(()=>c||a.has(e.last),e=>{o=e},kC,!0).catch(()=>{});let t=[...a].filter(([t])=>t<=e.last).sort(([e],[t])=>e-t);for(let[e]of t)a.delete(e);if(t.length>0&&await h(async()=>{for(let[e,n]of t)CC(p,e,n,r.id)}),e.last>f&&(f=e.last),!e.more||e.last<=s)break;s=e.last}e=!1,o=()=>{};let m=[...a].sort(([e],[t])=>e-t);for(let[e]of m)e>f&&(f=e);return await h(async()=>{for(let[e,t]of m)CC(p,e,t,r.id)}),c||l!==r?{status:`unavailable`}:(i.onStatus(`ready`),v(),r.closed?.then(e=>{c||l!==r||e.reason===`left`||(u(),u=()=>{},l=null,b(t))}),{status:`ready`,roster:d})}catch{return await g(),i.onStatus(`unavailable`),{status:`unavailable`}}},b=async e=>{for(let t=0;!c;t+=1)if(await s(o[Math.min(t,o.length-1)]??2e3),c||(await y(e,f)).status!==`unavailable`)return};return{ready:(async()=>{d=r();let t=MC(d);if(t===void 0){let n=await NC(e);if(c)return{status:`unavailable`};if(n.roster!==void 0&&(d=n.roster,i.onRoster(n.roster)),!n.ok){let e=n.reason===`out-of-claims`?`out-of-claims`:`unavailable`;return i.onStatus(e),{status:e,roster:n.roster}}t=MC(n.roster)}if(t==null)return i.onStatus(`none`),{status:`none`};let n=await y(t,0);return!c&&n.status===`unavailable`&&b(t),n})(),refreshRoster:e=>{d=e,yC(p,Hf(e)),v()},groupState:e=>p.groups.get(e)??null,leave:async()=>{c=!0,await g()}}},LC=async(e,t,n)=>{let r;try{r=await e.join(t)}catch(e){let t=String(AC(e));return t===`full`?`busy`:jC.has(t)?`closed`:`unavailable`}try{if(r.mailbox===null)return`closed`;let e=n(r.id);return e===null?`unavailable`:(await r.send(e,wx(r,yx)),`sent`)}catch(e){let t=String(AC(e));return t===`storage`||t===`quota`||t===`full`?`full`:t===`rate-limited`?`busy`:t===`denied`||t===`blocked`?`closed`:`unavailable`}finally{await r.leave().catch(()=>{})}},RC=async e=>{let t=await cp(e);if(!t.ok)return t;let n=MC(t.roster);if(typeof n==`string`)return{ok:!0,invite:n,roster:t.roster};if(n===null)return{ok:!1,reason:`no-room`};let r=await NC(e);if(!r.ok)return{ok:!1,reason:r.reason===`out-of-claims`?`out-of-claims`:`unavailable`};let i=MC(r.roster);return typeof i==`string`?{ok:!0,invite:i,roster:r.roster}:{ok:!1,reason:`no-room`}},zC=async(e,t,n,r)=>{let i=X(n.signKey);if(i===null)return{outcome:`closed`};let a=cf(i),o=Ky(n.chatRoom),s;if(o===null&&(o=await fT(e.rooms,t,n),o!==null)){let t=await gp(e,a,o);t.ok&&(s=t.roster)}if(o===null)return{outcome:`closed`};let c=await LC(e.rooms,o,r);if(c===`closed`){let i=await fT(e.rooms,t,n);if(i!==null&&i!==o){let t=await gp(e,a,i);return t.ok&&(s=t.roster),c=await LC(e.rooms,i,r),{outcome:c,roster:s,resolvedInvite:i}}}return{outcome:c,roster:s,resolvedInvite:o}},BC=async(e,t,n,r,i=Date.now())=>{let a=US(r);if(a===null)return{ok:!1,reason:`invalid`};let o=await RC(e);if(!o.ok)return o;let s=$S(),c=await zC(e,t.keys,n,e=>iC(e,t.keys,t.name,n,a,i,s));return c.outcome===`closed`?{ok:!1,reason:`no-peer-room`}:c.outcome!==`sent`||await LC(e.rooms,o.invite,e=>iC(e,t.keys,t.name,n,a,i,s))!==`sent`?{ok:!1,reason:`unavailable`}:{ok:!0,roster:c.roster??o.roster}},VC=async(e,t,n,r)=>{let i=X(n.signKey);if(i===null)return null;let a=cf(i),o=r.friends[a]?.value;if(o?.state===`active`){let n=Ky(o.chatRoom)??await fT(e.rooms,t,o);if(n!==null)return n}let s=Ky(n.chatRoom);return s===null?fT(e.rooms,t,n):s},HC=async(e,t,n,r,i)=>{let a=[];for(let o of n){let n=X(o.signKey);if(n===null)return null;let s=cf(n);if(s===i)continue;let c=await VC(e,t,o,r);if(c===null)return null;a.push({member:o,fp:s,invite:c})}return a},UC=async(e,t,n,r,i=Date.now())=>{let a=WS(n);if(a===null||r.length===0)return{ok:!1,reason:`invalid`};let o=await RC(e);if(!o.ok)return o;let s=`grp_${$S()}`,c=crypto.getRandomValues(new Uint8Array(32)),l=[...new Map(r.map(e=>[e.fingerprint,e])).values()].filter(e=>e.fingerprint!==cf(t.keys.signKey));if(l.length===0||l.length+1>32)return{ok:!1,reason:`invalid`};let u=[],d=o.roster;for(let n of l){let r=await VC(e,t.keys,n,d),i=GS(t.keys,n);if(r===null||i===null)return{ok:!1,reason:`no-peer-room`};if(Ky(n.chatRoom)===null){let t=await gp(e,n.fingerprint,r);t.ok&&(d=t.roster)}u.push({friend:n,invite:r,secret:i})}let f=[{signKey:Y(t.keys.signKey),dhKey:Y(t.keys.dhKey),name:t.name,chatRoom:o.invite},...u.map(({friend:e,invite:t})=>({signKey:e.signKey,dhKey:e.dhKey,name:e.name,chatRoom:t}))],p=$S();for(let n of u){let r=YS(n.secret,s),o=await LC(e.rooms,n.invite,e=>aC({roomId:e,myKeys:t.keys,sealKey:r,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p}));if(o===`closed`){let l=await fT(e.rooms,t.keys,n.friend);l!==null&&l!==n.invite&&(o=await LC(e.rooms,l,e=>aC({roomId:e,myKeys:t.keys,sealKey:r,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p})))}if(o!==`sent`)return{ok:!1,reason:o===`closed`?`no-peer-room`:`unavailable`}}let m=JS(t.keys.dhSeed,s);return await LC(e.rooms,o.invite,e=>aC({roomId:e,myKeys:t.keys,sealKey:m,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p}))===`sent`?{ok:!0,roster:d,groupId:s}:{ok:!1,reason:`unavailable`}},WC=async e=>{let t=cf(e.me.keys.signKey),n=e.resolvedTargets??await HC(e.services,e.me.keys,e.members,e.roster,t);if(n===null)return{ok:!1,reason:`no-peer-room`};let r=$S(),i=new Map(Hf(e.roster).map(e=>[e.fingerprint,e])),a=n.length===0,o=null;for(let{member:s,fp:c,invite:l}of n){let n=i.get(c),u=n?GS(e.me.keys,n):null,d;if(u!==null)d=YS(u,e.group.id);else{let n=X(s.dhKey);if(n===null)return{ok:!1,reason:`unavailable`};d=XS(e.me.keys.dhSeed,n,t,c,e.group.id)}let f=l,p=await LC(e.services.rooms,f,t=>aC({roomId:t,myKeys:e.me.keys,sealKey:d,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.nextKey,at:e.at,id:r}));if(p===`closed`){let t=await fT(e.services.rooms,e.me.keys,s);t!==null&&t!==f&&(f=t,p=await LC(e.services.rooms,f,t=>aC({roomId:t,myKeys:e.me.keys,sealKey:d,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.nextKey,at:e.at,id:r})))}p===`sent`?a=!0:o===null&&(o=p===`closed`?`no-peer-room`:`unavailable`)}if(a){let t=JS(e.me.keys.dhSeed,e.group.id);await LC(e.services.rooms,e.ownInvite,n=>aC({roomId:n,myKeys:e.me.keys,sealKey:t,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.action===`leave`?null:e.nextKey,at:e.at,id:r}))!==`sent`&&o===null&&(o=`unavailable`)}return o===null?{ok:!0}:{ok:!1,reason:o}},GC=async(e,t,n,r,i=Date.now())=>{let a=US(r);if(a===null)return{ok:!1,reason:`invalid`};if(!n.active)return{ok:!1,reason:`not-active`};let o=await RC(e);if(!o.ok)return o;let s=cf(t.keys.signKey),c=await HC(e,t.keys,n.members,o.roster,s);if(c===null)return{ok:!1,reason:`no-peer-room`};let l=n.epoch,u=n.key;if(u===null){let r=crypto.getRandomValues(new Uint8Array(32)),a=n.epoch+1,s=n.members.map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}})),d=await WC({services:e,me:t,ownInvite:o.invite,group:n,nextKey:r,nextEpoch:a,action:`rekey`,members:s,roster:o.roster,resolvedTargets:c,at:i});if(!d.ok)return d;l=a,u=r}let d=$S(),f=c.length===0,p=null;for(let{member:r,invite:o}of c){let s=o,c=await LC(e.rooms,s,e=>oC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d}));if(c===`closed`){let o=await fT(e.rooms,t.keys,r);o!==null&&o!==s&&(s=o,c=await LC(e.rooms,s,e=>oC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d})))}c===`sent`?f=!0:p===null&&(p=c===`closed`?`no-peer-room`:`unavailable`)}return f&&await LC(e.rooms,o.invite,e=>oC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d}))!==`sent`&&p===null&&(p=`unavailable`),p===null?{ok:!0,roster:o.roster}:{ok:!1,reason:p}},KC=async(e,t,n,r,i=Date.now())=>{if(!n.active)return{ok:!1,reason:`not-active`};if(n.members.some(e=>e.fingerprint===r.fingerprint)||n.members.length>=32)return{ok:!1,reason:`invalid`};let a=await RC(e);if(!a.ok)return a;let o=await VC(e,t.keys,r,a.roster);if(o===null)return{ok:!1,reason:`no-peer-room`};let s=crypto.getRandomValues(new Uint8Array(32)),c=[...n.members.map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}})),{signKey:r.signKey,dhKey:r.dhKey,name:r.name,chatRoom:o}],l=await WC({services:e,me:t,ownInvite:a.invite,group:n,nextKey:s,nextEpoch:n.epoch+1,action:`add`,members:c,roster:a.roster,at:i});return l.ok?{ok:!0,roster:a.roster}:l},qC=async(e,t,n,r=Date.now())=>{if(!n.active)return{ok:!1,reason:`not-active`};let i=await RC(e);if(!i.ok)return i;let a=cf(t.keys.signKey),o=n.members.filter(e=>e.fingerprint!==a).map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}}));if(o.length===0){let a=JS(t.keys.dhSeed,n.id);return await LC(e.rooms,i.invite,e=>aC({roomId:e,myKeys:t.keys,sealKey:a,groupId:n.id,action:`leave`,epoch:n.epoch+1,title:n.title,members:[],groupKey:null,at:r}))===`sent`?{ok:!0,roster:i.roster}:{ok:!1,reason:`unavailable`}}let s=await WC({services:e,me:t,ownInvite:i.invite,group:n,nextKey:null,nextEpoch:n.epoch+1,action:`leave`,members:o,roster:i.roster,at:r});return s.ok?{ok:!0,roster:i.roster}:s},JC=new TextEncoder,YC=new TextDecoder,XC=2e3,ZC=(e,t)=>{if(e.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return JC.encode(`${Py}\u0000${e}\u0000${t}`)},QC=(e,t)=>ay(Yd,e,JC.encode(t),JC.encode(Fy),32),$C=(e,t,n,r)=>{let i=JSON.stringify({k:Y(r.signKey),d:Y(r.dhKey),...n}),a=Y(Qv.sign(ZC(e,i),r.signSeed)),o=$v.utils.randomSecretKey(),s=crypto.getRandomValues(new Uint8Array(24)),c=Hg(QC($v.getSharedSecret(o,t),e),s).encrypt(JC.encode(JSON.stringify({b:i,s:a}))),l=new Uint8Array(24+c.length);return l.set(s),l.set(c,24),JSON.stringify({t:`social.request`,v:1,e:Y($v.getPublicKey(o)),b:Y(l)})},ew=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},tw=(e,t)=>{let n=typeof e==`string`?X(e):null;return n?.length===t?n:null},nw=(e,t,n,r)=>{let i=tw(n,32),a=typeof r==`string`?X(r):null;if(i===null||a===null||a.length<=24)return null;try{return Hg(QC($v.getSharedSecret(e.dhSeed,i),t),a.slice(0,24)).decrypt(a.slice(24))}catch{return null}},rw=(e,t)=>{if(e.kind===`party`){let n=typeof e.url==`string`?gf(e.url,XC):null;return n!==null&&n===e.url?{...t,kind:`party`,url:n}:null}if(e.kind===`comment`)return ly(e.text)===e.text?{...t,kind:`comment`,text:e.text}:null;if(e.kind!==`friend`&&e.kind!==`accept`)return null;let n=Ef(e.p),r=Ky(e.x),i=e.m===void 0||e.m===null?null:Ky(e.m),a=tw(e.r,32)===null?null:e.r;return n===null||a===null||e.m!==void 0&&e.m!==null&&i===null?null:e.kind===`friend`?r===null?null:{...t,kind:`friend`,p:n,x:r,r:a,...i===null?{}:{m:i}}:r===null&&e.x!==null&&e.x!==void 0?null:{...t,kind:`accept`,p:n,x:r,r:a,...i===null?{}:{m:i}}},iw=(e,t,n)=>{let r=ew(e);if(r===null||r.t!==`social.request`||r.v!==1)return null;let i=nw(n,t,r.e,r.b),a=i===null?null:ew(YC.decode(i));if(a===null||typeof a.b!=`string`||JC.encode(a.b).length>16384)return null;let o=tw(a.s,64),s=ew(a.b),c=tw(s?.k,32);if(s===null||o===null||c===null)return null;try{if(!Qv.verify(o,ZC(t,a.b),c,{zip215:!1}))return null}catch{return null}let{name:l,to:u}=s;if(u!==Y(n.signKey)||typeof l!=`string`||!sf(l))return null;let d=tw(s.d,32);if(d===null)return null;let f=rw(s,{k:s.k,d:s.d,name:l,to:u});return f===null?null:{body:f,signKey:c,dhKey:d}},aw=`Your inbox on FKN Social. Unclaiming it deletes the requests waiting there.`,ow={send:!0,receive:!1,maxMessageBytes:65536},sw=5e3,cw=e=>e?.code,lw=e=>X(e),uw=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),dw=e=>{let t=e.profile.inbox;return t===void 0?void 0:Ky(t.value)},fw=async(e,t)=>{if(t!==void 0){let n=await Z(e,e=>dw(e)===t?{inbox:null}:{});if(!n.ok)return n}let n;try{n=await e.rooms.create({defaults:ow,schema:xx})}catch(e){return{ok:!1,reason:cw(e)===`full`?`busy`:`unavailable`}}try{try{await n.claim({description:aw})}catch(t){if(cw(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>dw(e)===void 0?{inbox:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}let t=await Z(e,e=>typeof dw(e)==`string`?{}:{inbox:n.invite});return(!t.ok||dw(t.roster)!==n.invite)&&await n.release().catch(()=>{}),t}finally{await n.leave().catch(()=>{})}},pw=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return cw(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},mw=(e,t)=>e.friends[cf(t)]?.value.state===`active`,hw=[2e3,5e3,1e4,3e4],gw=(e,t,n,r,i)=>{let a=i?.backoffMs??hw,o=i?.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=null,l=()=>{},u=null,d=n(),f=[],p=new Set,m=new Set,h=0,g=Promise.resolve(),_=e=>{let t=g.then(()=>s?void 0:e(),()=>s?void 0:e());return g=t.catch(()=>{}),t},v=(e,t=e)=>{let n=f.length;return f=f.filter(n=>n.seq<e||n.seq>t),f.length!==n},y=async t=>{let n=c;if(n!==null&&!s)try{n.claimed&&n.owner===n.self.id&&await n.delete(t)}catch{}else u!==null&&await yw(e.rooms,u,t);!s&&v(t)&&r.onWaiting([...f])},b=async()=>{let e=c,t=l;c=null,l=()=>{},t(),e!==null&&await e.leave().catch(()=>{})},x=async t=>{let n=await Z(e,e=>dw(e)===t?{inbox:null}:{});if(n.ok)return d=n.roster,r.onRoster(n.roster),n.roster},S=async(i,a,o,c)=>{if(s||p.has(i))return;p.add(i),i>h&&(h=i),d=n();let l=iw(a,o.id,t);if(l===null||uw(l.signKey,t.signKey)){await y(i);return}let{body:u,signKey:g,dhKey:_}=l,v={signKey:g,dhKey:_,name:u.name,fingerprint:cf(g),confirmed:null};if(u.kind===`accept`){let t=await Sp(e,{signKey:g,dhKey:_,name:u.name,profile:u.p,pairNonce:lw(u.r),linkedVia:`request`,inbox:u.x,chatRoom:u.m},Date.now());if(!t.outcome.ok){p.delete(i),m.add(i);return}if(m.delete(i),d=t.outcome.roster,r.onRoster(t.outcome.roster),t.applied){let e=t.outcome.roster.friends[v.fingerprint]?.value.name??u.name;r.onAccepted([e])}await y(i)}else if(u.kind===`friend`){let e=f.find(e=>e.kind===`friend`&&e.sender.fingerprint===v.fingerprint);if(e!==void 0){if(e.seq>i){y(i);return}f=f.filter(t=>t!==e),y(e.seq)}f=[...f,{kind:`friend`,inbox:o.invite,seq:i,sender:v,request:u,friend:mw(d,g)}],c&&r.onWaiting([...f])}else if(u.kind===`comment`){let e=d.friends[v.fingerprint]?.value;e?.state===`active`&&fb(d,`comments`)!==`off`?(f.some(e=>e.seq===i)||(f=[...f,{kind:`comment`,inbox:o.invite,seq:i,sender:{...v,name:e.name},text:u.text,id:uy(a)}]),c&&r.onWaiting([...f])):y(i)}else mw(d,g)?(f.some(e=>e.seq===i)||(f=[...f,{kind:`party`,inbox:o.invite,seq:i,sender:v,url:u.url}]),c&&r.onWaiting([...f])):y(i)},C=async(t,n,i)=>{let a;try{a=await e.rooms.join(t)}catch(e){if(s)return{status:`unavailable`,inboxTaken:!1};if(cw(e)===`bad-key`){let e=await x(t);return r.onStatus(`none`),{status:`none`,roster:e,inboxTaken:!1}}return r.onStatus(`unavailable`),{status:`unavailable`,inboxTaken:!1}}if(s)return await a.leave().catch(()=>{}),{status:`unavailable`,inboxTaken:!1};c=a;try{if(!a.claimed){await b();let e=await x(t);return r.onStatus(`none`),{status:`none`,roster:e,inboxTaken:!1}}if(a.owner!==a.self.id)return await b(),r.onStatus(`taken`),{status:`taken`,inboxTaken:!0};if(await Dx(a,xx),s)return await b(),{status:`unavailable`,inboxTaken:!1};if(a.mailbox===null)return await b(),r.onStatus(`not-kept`),{status:`not-kept`,inboxTaken:!1};let e=!0,o=new Map,u=[],p=()=>{};l=await a.on(n=>{if(!(s||c!==a)){if(n.type===`message`)e?(o.set(n.message.seq,n.message.text),p()):_(()=>S(n.message.seq,n.message.text,a,!0));else if(n.type===`deleted`){if(e){for(let e of o.keys())e>=n.from&&e<=n.to&&o.delete(e);_(async()=>{!s&&v(n.from,n.to)&&r.onWaiting([...f])})}else _(async()=>{!s&&v(n.from,n.to)&&r.onWaiting([...f])})}else n.type===`claim`&&_(async()=>{s||c!==a||(n.claimed?n.owner===a.self.id?n.mailbox||r.onStatus(`not-kept`):(await b(),r.onStatus(`taken`)):(await b(),await x(t),r.onStatus(`none`)))})}});try{let e=n;for(;!s&&o.size<100;){let t=await a.backlog(e,100-o.size);if(t.last>e&&await dx(()=>s||o.has(t.last),e=>{p=e},sw,!0).catch(()=>{u.push(t.last)}),!t.more||t.last<=e)break;e=t.last}}catch{}e=!1,p=()=>{};let m=[...o].sort(([e],[t])=>e-t).slice(0,100);for(let e of u)y(e);return await _(async()=>{for(let[e,t]of m)await S(e,t,a,!1)}),s||c!==a?{status:`unavailable`,inboxTaken:!1}:(r.onStatus(`ready`),(i||m.length>0)&&r.onWaiting([...f]),a.closed?.then(e=>{s||c!==a||e.reason===`left`||(l(),l=()=>{},c=null,w(t))}),{status:`ready`,roster:d,inboxTaken:!1})}catch{return await b(),r.onStatus(`unavailable`),{status:`unavailable`,inboxTaken:!1}}},w=async e=>{for(let t=0;!s;t+=1){let n=a[Math.min(t,a.length-1)]??2e3;if(await o(n),s)return;let r=m.size>0?Math.min(h,Math.min(...m)-1):h,i=await C(e,r,!1);if(i.status===`ready`||i.status===`none`||i.status===`taken`||i.status===`not-kept`)return}};return{ready:(async()=>{d=n();let t=dw(d);if(t===void 0){let n=await fw(e);if(s)return{status:`unavailable`,inboxTaken:!1};if(n.roster!==void 0&&(d=n.roster,r.onRoster(n.roster)),!n.ok){let e=n.reason===`out-of-claims`?`out-of-claims`:`unavailable`;return r.onStatus(e),{status:e,roster:n.roster,inboxTaken:!1}}t=dw(n.roster)}if(t==null)return r.onStatus(`none`),{status:`none`,inboxTaken:!1};u=t;let i=await C(t,0,!0);return!s&&i.status===`unavailable`&&w(t),i})(),delete:y,leave:async()=>{s=!0,await b()}}},_w=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`,`invalid`]),vw=async(e,t,n,r,i)=>{let a;try{a=await e.join(t)}catch(e){let t=String(cw(e));return t===`full`?`busy`:_w.has(t)?`closed`:`unavailable`}try{return a.mailbox===null?`closed`:(await a.send($C(a.id,n,r,i),wx(a,vx)),`sent`)}catch(e){let t=String(cw(e));return t===`storage`||t===`quota`||t===`full`?`full`:t===`rate-limited`?`busy`:t===`denied`||t===`blocked`?`closed`:`unavailable`}finally{await a.leave().catch(()=>{})}},yw=async(e,t,n)=>{let r;try{r=await e.join(t)}catch{return}try{r.claimed&&r.owner===r.self.id&&await r.delete(n).catch(()=>{})}finally{await r.leave().catch(()=>{})}},bw=async(e,t,n)=>{if(uw(n.signKey,t.keys.signKey))return{ok:!1,reason:`self`};if(t.inbox===null)return{ok:!1,reason:`no-inbox`};if(n.inbox===null)return{ok:!1,reason:`closed`};let{invite:r,dhKey:i}=n.inbox,a=await xp(e,{signKey:n.signKey,dhKey:i,name:n.name,inbox:r},Date.now());if(!a.ok)return a;let o=await vw(e.rooms,r,i,{to:Y(n.signKey),name:t.name,kind:`friend`,p:t.profile,x:t.inbox,r:a.nonce,...t.chatRoom==null?{}:{m:t.chatRoom}},t.keys);return o===`sent`?{ok:!0}:{ok:!1,reason:o}},xw=async(e,t,n,r,i=(t,n)=>yw(e.rooms,t,n))=>{if(!r)return await i(n.inbox,n.seq),{ok:!0};let{sender:a,request:o}=n,s=await yp(e,{signKey:a.signKey,dhKey:a.dhKey,name:a.name,profile:o.p,pairNonce:lw(o.r),linkedVia:`request`,inbox:o.x,chatRoom:o.m},Date.now());return s.ok?await vw(e.rooms,o.x,a.dhKey,{to:o.k,name:t.name,kind:`accept`,p:t.profile,x:t.inbox,r:o.r,...t.chatRoom==null?{}:{m:t.chatRoom}},t.keys)===`sent`?(await i(n.inbox,n.seq),{ok:!0,roster:s.roster}):{ok:!1,reason:`unsent`,roster:s.roster}:s},Sw=async(e,t,n,r)=>{let i=Ky(n.inbox);if(i===null)return{ok:!1,reason:`no-inbox`};let a=gf(r,XC);if(a===null)return{ok:!1,reason:`link`};let o=await vw(e.rooms,i,lw(n.dhKey),{to:n.signKey,name:t.name,kind:`party`,url:a},t.keys);return o===`sent`?{ok:!0}:{ok:!1,reason:o}},Cw=(e,t,n=(t,n)=>yw(e.rooms,t,n))=>n(t.inbox,t.seq),ww=async(e,t,n,r)=>{let i=ly(r);if(i===null)return{ok:!1,reason:`invalid`};let a=await cp(e);if(!a.ok)return a;let o=await nS(e.rooms,n);if(o.kind===`busy`||o.kind===`unavailable`)return{ok:!1,reason:o.kind};if(o.kind!==`shown`||!mw(a.roster,o.signKey))return{ok:!1,reason:`not-friend`};if(o.inbox===null)return{ok:!1,reason:`closed`};let s=await vw(e.rooms,o.inbox.invite,o.inbox.dhKey,{to:Y(o.signKey),name:t.name,kind:`comment`,text:i},t.keys);return s===`sent`?{ok:!0}:{ok:!1,reason:s}},Tw=`Your profile page on FKN Social. Unclaiming it deletes stored activity and comments and moves your profile back to your name room.`,Ew={send:!1,receive:!0},Dw=e=>e?.code,Ow=e=>{let t=e.profile.pageRoom;return t===void 0?void 0:Ky(t.value)},kw=e=>{let t=e.profile.visibility?.value;return t!==void 0&&`invite`in t&&typeof t.invite==`string`},Aw=(e,t)=>{if(kw(e))return!1;if(bf(e).level===`public`)return!0;let n=wf(e);return n.displayName!==``||n.bio!==``||n.links.length>0||(e.profile.avatar?.value??null)!==null||(e.profile.background?.value??null)!==null||e.profile.page!==void 0||Dm(e).length>0||Sy(e).length>0||t!==void 0&&(t.public.length>0||t.friends.length>0||(t.comments?.public.length??0)>0||(t.comments?.friends.length??0)>0)},jw=async e=>{e.defaults().send&&await e.setDefault(`send`,!1).catch(()=>{}),await Dx(e,Sx)},Mw=(e,t,n,r)=>Ix(e,t,n,{read:ox,fit:(n,r)=>Fx(e,t,n,r,(e,n)=>ix(e,t,n),(e,t)=>JSON.stringify(ax(e,t??``)),n=>Y(Qv.sign(rx(e.id,e.self.id,n),t.signSeed))),envelope:()=>Ex(e)},r),Nw=e=>t=>({public:Vh(t.public,e.public),friends:Vh(t.friends,e.friends),comments:gy(t,e)}),Pw=async(e,t,n,r,i)=>{if(i!==void 0&&!(await Z(e,e=>Ow(e)===i?{pageRoom:null}:{})).ok)return{ok:!1,reason:`unavailable`};let a;try{a=await e.rooms.create({defaults:Ew,schema:Sx})}catch{return{ok:!1,reason:`unavailable`}}try{try{await a.claim({description:Tw})}catch(t){if(Dw(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>Ow(e)===void 0?{pageRoom:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}if(await jw(a),await Mw(a,t,n,r).catch(()=>`failed`)===`failed`)return await a.release().catch(()=>{}),{ok:!1,reason:`unavailable`};let i=await Z(e,e=>typeof Ow(e)==`string`?{}:{pageRoom:a.invite});if(i.ok&&Ow(i.roster)===a.invite)return{ok:!0,invite:a.invite,roster:i.roster};if(await a.release().catch(()=>{}),!i.ok)return{ok:!1,reason:`unavailable`};let o=Ow(i.roster);if(typeof o==`string`){let a=await Fw(e,t,o,n,r);return a.status===`ready`?{ok:!0,invite:o,roster:i.roster}:{ok:!1,reason:`unavailable`,roster:a.roster??i.roster}}return{ok:!1,reason:`unavailable`}}finally{await a.leave().catch(()=>{})}},Fw=async(e,t,n,r,i,a)=>{let o=async()=>{let t=await Z(e,e=>Ow(e)===n?{pageRoom:null}:{});return{status:`inline`,roster:t.ok?t.roster:void 0}},s;try{s=await e.rooms.join(n)}catch(e){return Dw(e)===`bad-key`?await o():{status:`unavailable`}}try{if(!s.claimed)return await o();if(s.owner!==s.self.id)return{status:`taken`};if(await jw(s),s.mailbox===null)return{status:`not-kept`};let e=Mw(s,t,r,i).catch(()=>`failed`);return a?.refreshClaim!==!1&&await s.claim({description:Tw}).catch(()=>{}),{status:await e===`failed`?`unavailable`:`ready`}}catch{return{status:`unavailable`}}finally{await s.leave().catch(()=>{})}},Iw=async(e,t,n,r,i)=>{let a;try{a=await e.join(t)}catch{return`failed`}try{return!a.claimed||a.owner!==a.self.id||a.mailbox===null?`failed`:await Mw(a,n,r,i)}catch{return`failed`}finally{await a.leave().catch(()=>{})}},Lw=async(e,t,n,r,i,a)=>{let o=!1,s=await Iw(e,t,n,r,e=>(o=Hh(e,i.app,i.at-Eh)>=10,o?e:{...e,[a]:Kh(e[a],i)}));return o?`too-many`:s},Rw=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return Dw(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},zw=async(e,t,n)=>{let r;try{r=await e.join(n)}catch{return}try{if(!r.claimed||r.owner!==r.self.id||r.mailbox===null)return;let e=Nx(r,t,await px(r),ox);if(e===null||e.currentOwner)return;await jw(r),await Mw(r,t,{version:0,profile:null})}catch{}finally{await r.leave().catch(()=>{})}},Bw=`v1/identity.json`,Vw=1024,Hw=3e3,Uw=({seed:e,name:t})=>{let n=JSON.stringify({v:1,seed:Y(e),name:t,pad:``});return n.replace(`"pad":""`,`"pad":"${` `.repeat(Vw-n.length)}"`)},Ww=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{v:n,seed:r,name:i}=t;if(n!==1)return`newer`;if(typeof r!=`string`||i!==null&&typeof i!=`string`)return null;let a=X(r);return a?.length===32?{seed:a,name:i}:null},Gw=async e=>{let t;try{t=await e.read(Bw)}catch(e){return{ok:!1,refusal:Mf(e)}}if(t===null)return{ok:!0,identity:null};let n=Ww(t);return n===`newer`?{ok:!1,refusal:`newer`}:n?{ok:!0,identity:n}:{ok:!1,refusal:`reset`}},Kw=async(e,t)=>{try{return await e.write(Bw,Uw(t)),null}catch(e){return Mf(e)}},qw=async(e,t)=>{let n=await Gw(e);if(!n.ok||n.identity!==null)return n;let r=await Kw(e,{seed:cx(),name:null});return r===null?(await t(Hw),Gw(e)):{ok:!1,refusal:r}},Jw=(e,t)=>{let n=e=>t()?e():Promise.reject(Error(`social: the FKN account changed`)),{cloud:r,storage:i}=e;return{...e,cloud:{list:()=>n(()=>r.list()),read:e=>n(()=>r.read(e)),write:(e,t)=>n(()=>r.write(e,t)),remove:e=>n(()=>r.remove(e))},storage:{put:e=>n(()=>i.put(e)),get:(e,t)=>n(()=>i.get(e,t)),delete:e=>n(()=>i.delete(e)),list:()=>n(()=>i.list())}}},Yw=e=>({kind:e}),Xw=async({account:e,cloud:t},n)=>{let r=e.encryption().catch(()=>null),i=await e.availability().catch(()=>`unknown`);if(i===`unknown`)return{kind:`unreachable`};if(i===`disconnected`)return{kind:`signed-out`};let a=await r;if(a===null)return{kind:`unreachable`};if(!a.enrolled)return{kind:`no-keys`};if(!a.unlocked)return{kind:`locked`};n?.();let o=await Gw(t);return o.ok?o.identity===null?{kind:`no-identity`}:{kind:`ready`,identity:o.identity}:Yw(o.refusal)},Zw=async(e,t,n)=>{let r=of(t);if(!r.ok)return r;let i=await qw(e.cloud,e.sleep);if(!i.ok)return{ok:!1,reason:i.refusal};let a=i.identity;if(a===null)return{ok:!1,reason:`unreachable`};if(a.name===r.name)return{ok:!0};let o=lx(a.seed),s=typeof n?.pageRoom==`string`,c=a.name===null||s?void 0:await Zx(e.rooms,o,a.name);if(c===null)return{ok:!1,reason:`unavailable`};let l=await Kx(e.rooms,o,r.name,n,c===void 0?void 0:e=>({public:Vh(e.public,c.public),friends:Vh(e.friends,c.friends),comments:gy(e,c)}));if(!l.ok&&l.reason!==`unrecorded`)return l;if(l.ok&&n===void 0){let t=await Qx(e.rooms,{keys:o,name:r.name});t.pageRoom!==null&&await zw(e.rooms,o,t.pageRoom)}if(!l.ok&&a.name!==null)return await qx(e.rooms,r.name)?{ok:!1,reason:`unavailable`}:{ok:!1,reason:`unavailable`,kept:r.name};let u=await Kw(e.cloud,{...a,name:r.name});return u===null?a.name===null||await qx(e.rooms,a.name)?{ok:!0}:{ok:!0,kept:a.name}:{ok:!1,reason:u}},Qw=async(e,t)=>await qx(e.rooms,t)?{ok:!0}:{ok:!1,reason:`unavailable`},$w=async(e,t,n)=>t.name===null?{ok:!1,reason:`empty`}:Kx(e.rooms,lx(t.seed),t.name,n),eT=async(e,t)=>{let n=oS(t);if(n===null)return{ok:!1,reason:`bad-recovery-key`};let r=await Kw(e.cloud,{seed:n,name:null});return r===null?{ok:!0}:{ok:!1,reason:r}},tT=async e=>{let t=await Kw(e.cloud,{seed:cx(),name:null});return t===null?{ok:!0}:{ok:!1,reason:t}},nT=async({cloud:e,rooms:t,storage:n})=>{let r=await cp({cloud:e});if(r.ok)return{ok:!0};if(r.reason!==`reset`)return{ok:!1,reason:r.reason};let i=await Gw(e);if(i.ok&&i.identity?.name!=null){let n={keys:lx(i.identity.seed),name:i.identity.name},r=await Qx(t,n);if(r.inbox!==null||r.pageRoom!==null||r.chatRoom!==null){let i=await cp({cloud:e});if(i.ok)return{ok:!0};if(i.reason!==`reset`)return{ok:!1,reason:i.reason};let a=r.chatRoom??(r.pageRoom===null?null:await $x(t,n,r.pageRoom));r.inbox!==null&&await pw(t,r.inbox),r.pageRoom!==null&&await Rw(t,r.pageRoom),a!==null&&await PC(t,a)}}let a=await n.list().then(({objects:e})=>e,()=>[]);for(let{url:e}of a)await n.delete(e).catch(()=>{});try{let t=(await e.list()).map(({path:e})=>e).filter(e=>e!==Bw);for(let n of t)await e.remove(n);return{ok:!0}}catch(e){return{ok:!1,reason:Mf(e)}}},rT={ok:!1,reason:`none`},iT=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),aT=e=>{if(typeof e!=`object`||!e)return!1;let{roomId:t,owner:n,text:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`},oT=e=>aT(e)&&typeof e.name==`string`&&(e.core===void 0||aT(e.core)),sT=e=>e===null?rT:{ok:!0,...e},cT=e=>{let t=tx(e.text,e.roomId,e.owner,e.name);if(t!==null)return t;if(e.core===void 0)return null;let n=tx(e.core.text,e.core.roomId,e.core.owner,e.name);if(n?.pageRoom===void 0||qy(n.pageRoom)!==e.roomId)return null;let r=ox(e.text,e.roomId,e.owner);return r!==null&&iT(r.signKey,n.signKey)?r:null},lT=async(e,t,n,r)=>{let i=cT(n);if(i?.friends==null)return rT;let a=await t();if(a.kind!==`ready`)return rT;let o=lx(a.identity.seed),s={roomId:n.roomId,owner:n.owner};if(iT(i.signKey,o.signKey))return sT(Vb(o,s,i.friends));let c=await(r?r():cp(e)),l=c.ok?c.roster.friends[cf(i.signKey)]?.value:void 0,u=l?.state===`active`?X(l.dhKey):null;return u?.length===32?sT(Hb(o,u,s,i.friends)):rT},uT=(e,t,n,r)=>{if(r===void 0)return;let i=X(n),a=i?.length===32?cT(r):null;if(a?.friends!=null&&iT(a.signKey,t))return Hb(e,i,{roomId:r.roomId,owner:r.owner},a.friends)?.chatRoom??void 0},dT=async(e,t,n)=>{let r=X(n.signKey);if(r?.length!==32)return null;let i=await rS(e,n.name).catch(()=>null);if(i?.kind!==`shown`||!iT(i.signKey,r))return null;if(i.profile!==null){let e=uT(t,r,n.dhKey,i.record);return{displayName:i.profile.displayName,bio:i.profile.bio,links:i.profile.links,avatar:i.profile.avatar,...e===void 0?{}:{chatRoom:e}}}if(i.record!==void 0){let e=X(n.dhKey),a=e?.length===32?cT(i.record):null;if(a?.friends!=null&&iT(a.signKey,r)){let n=Hb(t,e,{roomId:i.record.roomId,owner:i.record.owner},a.friends);if(n?.profile!=null)return{displayName:n.profile.displayName,bio:n.profile.bio,links:n.profile.links,avatar:yf(n.profile.avatar??null)??null,...n.chatRoom===void 0?{}:{chatRoom:n.chatRoom}};if(n?.chatRoom!==void 0)return{displayName:``,bio:``,links:[],avatar:null,chatRoom:n.chatRoom}}}return null},fT=async(e,t,n)=>{let r=X(n.signKey);if(r?.length!==32)return null;let i=await rS(e,n.name).catch(()=>null);return i?.kind!==`shown`||!iT(i.signKey,r)?null:uT(t,r,n.dhKey,i.record)??null},pT=e=>{let t=null,n=null,r=()=>{if(n!==null)return n;let t=cp(e).then(e=>(!e.ok&&n===t&&(n=null),e));return n=t,t},i=()=>t??=Xw(e,()=>{r()});return{own:async()=>{let e=await i();return e.kind===`ready`?lx(e.identity.seed).signKey:null},friends:t=>lT(e,i,t,r)}},mT=e=>e?.code,hT=e=>[e.profile.avatar?.value??null,e.profile.background?.value??null],gT=e=>{let t=e.profile.visibility?.value;return t!==void 0&&`invite`in t&&typeof t.invite==`string`?t.invite:null},_T=e=>{let t=bf(e).level,n=gT(e)===null,{displayName:r,bio:i,links:a}=wf(e),[o,s]=hT(e),c=n?Am(e):[],l=n?km(e):[],u=MC(e);return{profile:t===`friends`&&n?{displayName:r,bio:i,links:a,...o===null?{}:{avatar:o},...s===null?{}:{background:s}}:null,sections:gb(e,t!==`me`&&n),...fb(e,`favourites`)===`friends`?{favourites:Sy(e)}:{},...c.length>0?{panels:c}:{},...c.length>0&&l.length>0?{panelOrder:jm(e)}:{},...typeof u==`string`?{chatRoom:u}:{},members:Hf(e).map(e=>X(e.dhKey)).filter(e=>e?.length===32),left:Object.entries(e.friends).filter(([,e])=>e.value.state!==`active`).map(([e])=>e).sort()}},vT=e=>{let t=wf(e),n=Math.max(0,...Bf(e).map(({lamport:e})=>e)),r=gT(e)===null,i=bf(e).level===`public`&&r,a=hb(e,i),o=fb(e,`activity`),s=_T(e),c=fb(e,`favourites`)===`public`?Sy(e):void 0,l=r?km(e):[],u=fb(e,`comments`);if(!i)return{version:n,profile:null,page:a,activity:o,favourites:c,commentsLevel:u,...l.length>0?{panels:l}:{},friends:s};let[d,f]=hT(e);return{version:n,profile:{displayName:t.displayName,bio:t.bio,links:t.links,avatar:d,background:f},page:a,activity:o,favourites:c,commentsLevel:u,...l.length>0?{panels:l}:{},friends:s}},yT=(e,t=!1)=>({...vT(e),inbox:t?null:dw(e)??null}),bT=(e,t,n=!1)=>{let r=Math.max(0,...Bf(e).map(({lamport:e})=>e)),i=n?null:dw(e)??null,a=gT(e)===null,o=bf(e).level===`public`&&a,s=t!==null&&o?wf(e).displayName:``;return{version:r,profile:null,inbox:i,...s===``?{}:{displayName:s},...t===null?{}:{pageRoom:t}}},xT=e=>JSON.stringify({inbox:e.inbox??null,displayName:e.displayName??null,pageRoom:e.pageRoom??null}),ST=(e,t=!1)=>{let n=Ow(e);return typeof n==`string`?bT(e,n,t):yT(e,t)},CT=async(e,t,n,r)=>{let i=r?.skipNameIfUnchanged!==!0;if(r?.skipNameIfUnchanged===!0&&r.lastNameStatus===`held`&&n!==null&&!(`then`in n)){let{roster:i,inboxTaken:a}=n,o=Ow(i);if(typeof o==`string`){let n=xT(bT(i,o,a));if(n===r.lastCoreKey){let r=await Fw(e,t.keys,o,vT(i),void 0,{refreshClaim:!1});if(r.status!==`inline`)return{status:`held`,pageStatus:r.status,...r.roster?{roster:r.roster}:{},coreKey:n};let s=r.roster??i;return{status:await Jx(e.rooms,t,()=>Promise.resolve(yT(s,a)),async e=>e,{refreshClaim:!1}),pageStatus:`inline`,...r.roster?{roster:r.roster}:{},coreKey:null}}}}let a=`unused`,o,s=null,c=n!==null&&!(`then`in n)?n:null,l=c?Ow(c.roster):void 0,u=typeof l==`string`?Fw(e,t.keys,l,vT(c.roster),void 0,{refreshClaim:i}):null,d=await Jx(e.rooms,t,()=>Promise.resolve(n),async({roster:n,inboxTaken:r},c)=>{let l=Ow(n);if(typeof l==`string`){u??=Fw(e,t.keys,l,vT(n),void 0,{refreshClaim:i});let c=await u;if(o=c.roster,c.status===`inline`)return a=`inline`,s=null,yT(c.roster??n,r);if(a=c.status,c.status===`unavailable`)return s=null,null;let d=bT(n,l,r);return s=xT(d),d}if(l===void 0){let i=await c();if(!Aw(n,i))return a=`unused`,s=null,yT(n,r);let l=await Pw(e,t.keys,vT(n),Nw(i));if(o=l.roster,l.ok){a=`ready`;let e=bT(l.roster,l.invite,r);return s=xT(e),e}return a=l.reason===`out-of-claims`?`out-of-claims`:`unavailable`,s=null,yT(l.roster??n,r)}return a=`inline`,s=null,yT(n,r)},{refreshClaim:i}),f=await Promise.resolve(n);if(f!==null&&u===null&&typeof Ow(f.roster)==`string`&&(u=Fw(e,t.keys,Ow(f.roster),vT(f.roster),void 0,{refreshClaim:i})),u!==null){let e=await u;a=e.status,e.roster!==void 0&&(o=e.roster)}return{status:d,pageStatus:a,...o?{roster:o}:{},coreKey:d===`held`?s:null}},wT=async(e,t,n)=>{for(let r=0;r<2;r++){let r=await cp(e);if(!r.ok)return`failed`;let i=Ow(r.roster);if(typeof i==`string`&&e.rooms.join!==void 0){let a=await Iw(e.rooms,i,t.keys,vT(r.roster),n);if(a!==`newer`)return a}else{let i=await Yx(e.rooms,t,yT(r.roster),n);if(i!==`newer`)return i}}return`failed`},TT=async(e,t,n,r)=>{let i={id:n.id,name:n.sender.name,text:n.text,at:Date.now()};return await wT(e,t,e=>_y(e,i))===`written`&&(await Cw(e,n,r),!0)},ET=async(e,t,n=!1)=>{let r=await Z(e,e=>bf(e).level===`public`?{}:{visibility:{level:`public`}});if(!r.ok)return r;let i=await CT(e,t,{roster:r.roster,inboxTaken:n});return{ok:!0,roster:i.roster??r.roster,status:i.status,pageStatus:i.pageStatus}},DT=async(e,t,n=!1)=>{let r;try{r=await e.join(t)}catch(e){return mT(e)===`bad-key`}try{return r.claimed?r.owner===r.self.id?(await r.release(),!0):!n:!0}catch{return!1}finally{await r.leave().catch(()=>{})}},OT=async(e,t,n,r,i=!1)=>{let a=gT(n);if(a!==null&&!await DT(e.rooms,a))return{ok:!1,reason:`unavailable`};let o=bf(n).level,s=o===`public`,c=o===`friends`&&r===`me`,l=[],u=await Z(e,e=>{if(s){let t=hT(e);return l=t.some(e=>e!==null)?t:hT(n),bf(e).level===r&&t.every(e=>e===null)?{}:{visibility:{level:r},avatar:null,background:null}}if(bf(e).level===`public`)return{};if(c){let t=hT(e);if(t.some(e=>e!==null))return l=t,{visibility:{level:r},avatar:null,background:null}}return{visibility:{level:r}}});if(!u.ok)return u;let d=await CT(e,t,{roster:u.roster,inboxTaken:i});return typeof Ow(u.roster)==`string`&&d.pageStatus!==`ready`&&d.pageStatus!==`inline`?{ok:!1,reason:`unavailable`,pageStatus:d.pageStatus}:(await qp(e.storage,l),{ok:!0,roster:d.roster??u.roster,status:d.status,pageStatus:d.pageStatus})},kT=async(e,t)=>{let n=gT(t);if(n===null)return{ok:!0,roster:t};if(!await DT(e.rooms,n,!0))return{ok:!1,reason:`unavailable`};let r=[],i=await Z(e,e=>gT(e)===n?(r=hT(e),{visibility:{level:`friends`},avatar:null,background:null}):{});return i.ok&&await qp(e.storage,r),i},AT=e=>Array.isArray(e)?Th.filter(t=>e.includes(t)):[],jT=(e,t)=>{let n=e.apps[t]?.value;if(typeof n!=`object`||!n)return null;let{kinds:r,level:i,state:a,presence:o,publishingAsked:s,connectedAt:c}=n;return{kinds:AT(r),level:i===`public`?`public`:`friends`,state:a===`asked`||a===`allowed`?a:`stopped`,...o===`allowed`||o===`blocked`?{presence:o}:{},...typeof s==`boolean`?{publishingAsked:s}:{},...typeof c==`number`&&Number.isSafeInteger(c)&&c>=0?{connectedAt:c}:{}}},MT=e=>e?.state===`allowed`?{state:`allowed`,kinds:e.kinds}:e?.state===`asked`?{state:`asked`}:{state:`off`},NT=e=>e.reason===`locked`?`locked`:`unavailable`,PT=async e=>{let t=await Xw(e);if(t.kind===`locked`)return`locked`;if(t.kind===`no-identity`)return`no-name`;if(t.kind!==`ready`)return`unavailable`;let{seed:n,name:r}=t.identity;if(r===null)return`no-name`;let i=await cp(e);return i.ok?{me:{keys:lx(n),name:r},roster:i.roster}:NT(i)},FT=(e,t)=>e.length===t.length&&e.every(e=>t.includes(e)),IT=(e,t)=>{let n=async(n,r)=>{let i=await PT(e);if(typeof i==`string`)return{state:i};let a=jT(i.roster,n);if(r(a)===null)return MT(a);let o=await fp(e,n,e=>{let t=r(jT(e,n));return t===null?null:{grant:t}});return o.ok&&t?.onRosterChange?.(),o.ok?MT(jT(o.roster,n)):{state:NT(o)}},r=Promise.resolve(),i=e=>{let t=r.then(e,e);return r=t.catch(()=>{}),t};return{publishing:async t=>{let n=await PT(e);return typeof n==`string`?{state:n}:MT(jT(n.roster,t))},allow:(e,t)=>{let r=AT(t?.kinds);return n(e,e=>r.length===0||e?.state===`allowed`||e?.state===`asked`&&FT(e.kinds,r)?null:{kinds:r,level:e?.level??`friends`,state:`asked`,...e?.presence===void 0?{}:{presence:e.presence},...e?.connectedAt===void 0?{}:{connectedAt:e.connectedAt}})},stop:e=>n(e,e=>e===null||e.state===`stopped`?null:{...e,state:`stopped`}),publish:(t,n)=>i(async()=>{for(let r=0;r<2;r++){let r=await PT(e);if(typeof r==`string`)return{ok:!1,reason:r};let i=jT(r.roster,t),a=fb(r.roster,`activity`);if(i?.state!==`allowed`||a===`off`)return{ok:!1,reason:`not-allowed`};let o=zh(n,t,Date.now());if(o===null)return{ok:!1,reason:`invalid`};if(!i.kinds.includes(o.kind))return{ok:!1,reason:`not-allowed`};let s=Ow(r.roster),c=typeof s==`string`?await Lw(e.rooms,s,r.me.keys,vT(r.roster),o,i.level):await Xx(e.rooms,r.me,yT(r.roster),o,i.level);if(c===`written`)return{ok:!0,id:o.id};if(c!==`newer`)return{ok:!1,reason:c===`too-many`?`too-many`:`unavailable`}}return{ok:!1,reason:`unavailable`}})}},LT=async(e,t,n)=>{let r=!1;return{outcome:await fp(e,t,e=>jT(e,t)===null?(r=!0,{grant:{kinds:[],level:`friends`,state:`stopped`,presence:`allowed`,publishingAsked:!1,connectedAt:n}}):(r=!1,null)),wrote:r}},RT=(e,t,n)=>fp(e,t,e=>{let r=jT(e,t);if(r===null)return null;let i={...r,...n},a=i.state===`allowed`&&r.state!==`allowed`&&fb(e,`activity`)===`off`?pb(ub(e),`activity`,i.level):void 0;return a===void 0&&JSON.stringify(i)===JSON.stringify(r)?null:{grant:i,page:a}}),zT=new TextEncoder,BT=e=>zT.encode(e),VT=0,HT=e=>{let t=[e.roomId,e.memberId,String(e.at),e.name,e.displayName,e.avatarUrl];for(let e of t)if(e.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);if(e.signKey.length!==32||e.dhKey.length!==32)throw Error(`social: a public key is 32 bytes`);let n=[BT(Ey),Uint8Array.of(VT),BT(e.roomId),Uint8Array.of(VT),BT(e.memberId),Uint8Array.of(VT),BT(String(e.at)),Uint8Array.of(VT),e.signKey,Uint8Array.of(VT),e.dhKey,Uint8Array.of(VT),BT(e.name.normalize(`NFC`)),Uint8Array.of(VT),BT(e.displayName.normalize(`NFC`)),Uint8Array.of(VT),BT(e.avatarUrl)],r=n.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i},UT=(e,t)=>({t:`social.hello`,v:1,k:Y(e.signKey),d:Y(e.dhKey),h:e.name,n:e.displayName,i:e.avatarUrl===``?null:e.avatarUrl,a:e.at,s:Y(Qv.sign(HT(e),t))}),WT=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.t===`social.hello`&&typeof t.k==`string`&&typeof t.d==`string`&&typeof t.h==`string`&&typeof t.n==`string`&&(t.i===null||typeof t.i==`string`)&&typeof t.a==`number`&&typeof t.s==`string`},GT=(e,t,n)=>{if(!WT(e))return{ok:!1,reason:`malformed`};if(e.v!==1)return{ok:!1,reason:`unsupported-version`};let r=X(e.k),i=X(e.d),a=X(e.s);if(!r||!i||!a)return{ok:!1,reason:`malformed`};if(r.length!==32||i.length!==32)return{ok:!1,reason:`bad-key`};if(a.length!==64||!Number.isSafeInteger(e.a))return{ok:!1,reason:`malformed`};let o={roomId:t,memberId:n,at:e.a,signKey:r,dhKey:i,name:e.h,displayName:e.n,avatarUrl:e.i??``},s;try{s=HT(o)}catch{return{ok:!1,reason:`malformed`}}try{if(!Qv.verify(a,s,r,{zip215:!1}))return{ok:!1,reason:`bad-signature`}}catch{return{ok:!1,reason:`bad-signature`}}return{ok:!0,hello:o}},KT=(e,t)=>({roomId:e,selfMemberId:t,participants:new Map,keyByMember:new Map}),qT=(e,t)=>({memberId:e,status:`silent`,identity:null,nickname:null,refusal:null,self:e===t}),JT=(e,t)=>{e.participants.has(t)||e.participants.set(t,qT(t,e.selfMemberId))},YT=(e,t)=>{e.participants.delete(t),e.keyByMember.delete(t)},XT=(e,t,n)=>{e.participants.set(t,{...qT(t,e.selfMemberId),status:`unverified`,refusal:n})},ZT=(e,t,n)=>({fingerprint:cf(t),handle:uf(e.h,t),name:e.h,displayName:e.n,avatar:e.i,signKey:e.k,dhKey:e.d,shortFingerprint:df(t)}),QT=e=>X(e),$T=(e,t,n,r,i)=>{if(typeof n!=`object`||!n)return!1;let a=n;if(a.t!==`social.hello`)return!1;if(JT(e,t),typeof a.h!=`string`||!sf(a.h)||typeof a.n!=`string`||hf(a.n,{max:32,multiline:!1})!==null)return XT(e,t,`bad-name`),!0;if(typeof a.a!=`number`||Math.abs(a.a-r)>6e5)return XT(e,t,`stale`),!0;let o=GT(n,e.roomId,t);if(!o.ok)return XT(e,t,o.reason),!0;let s=n,c=ZT(s,QT(s.k),QT(s.d));for(let[n,r]of e.keyByMember)if(n!==t&&r===s.k)return XT(e,n,`duplicate-key`),XT(e,t,`duplicate-key`),e.keyByMember.set(t,s.k),!0;e.keyByMember.set(t,s.k);let l=i.friendByFingerprint(c.fingerprint),u=l===null?i.friendNamed(c.name)?`rekeyed`:`verified`:`friend`;return e.participants.set(t,{memberId:t,status:u,identity:c,nickname:l?.nickname??null,refusal:null,self:t===e.selfMemberId}),!0},eE=e=>[...e.participants.values()].sort((e,t)=>e.memberId.localeCompare(t.memberId)),tE=/^[A-Za-z0-9_-]+$/,nE=43,rE=(e,t)=>`${e}/i#${t.key}.${t.nonce}.${t.roomId}`,iE=e=>{if(e[nE]!==`.`||e[87]!==`.`)return null;let t=e.slice(0,nE),n=e.slice(44,87),r=e.slice(88);return r.length===0||!tE.test(t)||!tE.test(n)?null:{roomId:r,key:t,nonce:n}},aE=9e5,oE=1e4,sE={t:`social.whois`,v:1},cE=e=>({state:e,listeners:new Set}),lE=(e,t)=>{e.state=t;for(let n of e.listeners)n(t)},uE=e=>t=>(e.listeners.add(t),()=>{e.listeners.delete(t)}),dE=()=>Y(crypto.getRandomValues(new Uint8Array(16))),fE=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t?t:null}catch{return null}},pE=(e,t)=>JSON.stringify(UT({roomId:e.id,memberId:e.self.id,at:Date.now(),signKey:t.keys.signKey,dhKey:t.keys.dhKey,name:t.name,displayName:``,avatarUrl:``},t.keys.signSeed)),mE=(e,t,n,r,i,a,o)=>{let s=KT(t.id,t.self.id);$T(s,r,i,a,{friendByFingerprint:()=>null,friendNamed:()=>!1});let c=s.participants.get(r)?.identity;if(!c)return null;let l={memberId:r,fingerprint:c.fingerprint,name:c.name,displayName:c.displayName,signKey:X(c.signKey),dhKey:X(c.dhKey),confirmed:null,friend:n(c.fingerprint)};return eS(e.rooms,l.name,l.signKey).then(e=>o({...l,confirmed:e})),l},hE=async(e,t,n)=>{if(e.writerId===null)return{ok:!1,reason:`no-writer`};let r;try{r=await e.rooms.create({members:2})}catch{return{ok:!1,reason:`unavailable`}}let i=crypto.getRandomValues(new Uint8Array(32)),a=r.invite.indexOf(`.`),o=rE(Vu,{key:r.invite.slice(0,a),nonce:Y(i),roomId:r.invite.slice(a+1)}),s=Date.now()+aE,c=cE({kind:`waiting`}),l=new Map,u=null,d=null,f=!1,p=()=>{},m=()=>`peer`in c.state?c.state.peer:null,h=()=>c.state.kind===`friends`,g=async e=>{h()||lE(c,e),!f&&(f=!0,clearTimeout(x),p(),await r.leave().catch(()=>{}))},_=async()=>{let t=m();if(d===null||t===null)return;let n=await yp(e,d,Date.now());n.ok?await g({kind:`friends`,peer:t}):lE(c,{kind:`unsaved`,peer:t,reason:n.reason})},v=(t,i,a)=>{let o=m();if(o!==null&&o.memberId===t)return;let s=mE(e,r,n,t,i,a,e=>{m()?.memberId===e.memberId&&c.state.kind===`joined`&&lE(c,{kind:`joined`,peer:e})});s!==null&&(c.state.kind===`waiting`||c.state.kind===`left`)&&lE(c,{kind:`joined`,peer:s})},y=async(e,n)=>{let a=m();if(c.state.kind!==`offered`||a===null||a.memberId!==e)return;let o=TS(n,{roomId:r.id,fromMemberId:e,selfMemberId:r.self.id},{dhSeed:t.keys.dhSeed,theirSignKey:a.signKey,theirDhKey:a.dhKey});o.ok&&l.get(o.body.offerId)===e&&(d={signKey:a.signKey,dhKey:a.dhKey,name:a.name,profile:o.body.profile,pairNonce:i,linkedVia:`invite`,inbox:o.body.inbox,chatRoom:o.body.chatRoom},await _())},b=e=>{if(e.type===`left`&&d===null&&e.id===m()?.memberId&&(c.state.kind===`joined`||c.state.kind===`offered`)){lE(c,{kind:`left`});return}if(e.type!==`message`||e.message.from===r.self.id)return;let{from:n,text:i,at:a}=e.message,o=fE(i);o?.t===`social.whois`?(r.send(pE(r,t)).catch(()=>{}),c.state.kind===`offered`&&m()?.memberId===n&&u!==null&&r.send(u).catch(()=>{})):o?.t===`social.hello`?v(n,o,a):o?.t===`social.accept`&&y(n,o)},x=setTimeout(()=>void g({kind:`closed`}),aE);return p=await r.on(b),r.closed.then(()=>void g({kind:`closed`})),{ok:!0,invite:{link:o,expiresAt:s,state:()=>c.state,on:uE(c),add:async()=>{let e=m();if(c.state.kind!==`joined`||e===null)return!1;let n=dE(),a=JSON.stringify(yS({nonce:i,profile:t.profile,inbox:t.inbox,chatRoom:t.chatRoom},{roomId:r.id,fromMemberId:r.self.id,toMemberId:e.memberId,id:n},{signSeed:t.keys.signSeed,dhSeed:t.keys.dhSeed,theirDhKey:e.dhKey}));try{await r.send(a)}catch{return!1}return l.set(n,e.memberId),u=a,lE(c,{kind:`offered`,peer:e}),!0},saveAgain:_,close:()=>g({kind:`closed`})}}},gE=new Set([`bad-key`,`invalid`,`not-found`,`denied`,`blocked`,`closed`]),_E=(e,t,n,r)=>{let i=cE({kind:`joining`}),a=X(n.nonce),o=null,s=()=>{},c,l=null,u=null,d=!1,f=()=>`host`in i.state?i.state.host:null,p=()=>[`friends`,`closed`,`in-use`,`unavailable`].includes(i.state.kind),m=async e=>{p()||lE(i,e),!d&&(d=!0,clearTimeout(c),s(),await o?.leave().catch(()=>{}))},h=(n,o,s,u)=>{if(o!==n.owner)return;let d=fE(s);if(d?.t===`social.hello`&&f()===null){let a=mE(e,n,r,o,d,u,e=>{let t=i.state;`host`in t&&t.host?.memberId===e.memberId&&lE(i,{...t,host:e})});if(a===null)return;clearTimeout(c),lE(i,{kind:`waiting`,host:a}),n.send(pE(n,t)).catch(()=>{})}else if(d?.t===`social.offer`){let e=f();if(e===null||i.state.kind!==`waiting`&&i.state.kind!==`offered`)return;let r=wS(d,{roomId:n.id,fromMemberId:o,selfMemberId:n.self.id},{dhSeed:t.keys.dhSeed,theirSignKey:e.signKey,theirDhKey:e.dhKey});if(!r.ok||a===null||!vE(r.body.nonce,a))return;l={id:r.id,nonce:r.body.nonce,profile:r.body.profile,inbox:r.body.inbox,chatRoom:r.body.chatRoom},lE(i,{kind:`offered`,host:e,profile:r.body.profile})}},g=async e=>{if(o!==null&&u!==null){try{await o.send(u)}catch{lE(i,{kind:`unsent`,host:e});return}await m({kind:`friends`,host:e})}};return(async()=>{let t;try{t=await e.rooms.join(`${n.key}.${n.roomId}`)}catch(e){let t=e?.code;lE(i,t===`full`?{kind:`in-use`}:gE.has(String(t))?{kind:`closed`}:{kind:`unavailable`});return}if(o=t,t.owner===t.self.id)return void m({kind:`closed`});if(d)return void t.leave().catch(()=>{});s=await t.on(e=>{e.type===`left`&&e.id===t.owner&&m({kind:`closed`}),e.type===`message`&&h(t,e.message.from,e.message.text,e.message.at)}),t.closed.then(()=>void m({kind:`closed`})),lE(i,{kind:`waiting`,host:null}),c=setTimeout(()=>{f()===null&&m({kind:`closed`})},oE),await t.send(JSON.stringify(sE)).catch(()=>{})})(),{state:()=>i.state,on:uE(i),accept:async()=>{let n=i.state;if(n.kind!==`offered`&&n.kind!==`failed`||l===null||o===null)return;let r=n.host;lE(i,{kind:`accepting`,host:r,profile:l.profile});let a=await yp(e,{signKey:r.signKey,dhKey:r.dhKey,name:r.name,profile:l.profile,pairNonce:l.nonce,linkedVia:`invite`,inbox:l.inbox,chatRoom:l.chatRoom},Date.now());if(!a.ok){lE(i,{kind:`failed`,host:r,profile:l.profile,reason:a.reason});return}u=JSON.stringify(bS({offerId:l.id,profile:t.profile,inbox:t.inbox,chatRoom:t.chatRoom},{roomId:o.id,fromMemberId:o.self.id,toMemberId:r.memberId,id:dE()},{signSeed:t.keys.signSeed,dhSeed:t.keys.dhSeed,theirDhKey:r.dhKey})),await g(r)},sendAgain:async()=>{let e=f();i.state.kind===`unsent`&&e!==null&&await g(e)},decline:()=>m({kind:`closed`})}},vE=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),yE={started:`start`,watched:`watch`,completed:`finish`,rated:`rate`},bE=e=>Th.filter(t=>e.includes(t)),xE=(e,t,n)=>{let r=n||Ph(e),i=bE(t).map(e=>yE[e]);return i.length===0?`${r} asks to post to your page.`:`${r} asks to post when you ${i.length===1?i[0]:`${i.slice(0,-1).join(`, `)} or ${i.at(-1)}`} something.`},SE=()=>{let[e,t]=K(!1),[n,r]=K(null);return{busy:e,problem:n,run:async n=>{if(e)return!1;t(!0),r(null);let i=await n();return t(!1),r(i),i===null}}},CE=({asks:e,actions:t,names:n,onAnswered:r})=>{let{busy:i,problem:a,run:o}=SE(),s=J(new Map),c=new Set(e.map(({app:e})=>e));for(let e of s.current.keys())c.has(e)||s.current.delete(e);let l=(e,t)=>{let n=s.current.get(e);if(n!==void 0)return n;let r=bE(t);return s.current.set(e,r),r},u=async(e,n)=>{await o(()=>t.change(e,n))&&r?.()};return e.length===0?null:Q(`div`,{className:`social-stack`,"data-social-asks":!0,children:[e.map(({app:e,grant:t})=>{let r=l(e,t.kinds);return Q(`div`,{className:`social-invite`,"data-social-ask":e,children:[Q(`p`,{children:xE(e,r,n?.[e])}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-social-allow":!0,"aria-disabled":i,onClick:()=>void u(e,{state:`allowed`,kinds:r}),children:`Allow`}),Q(`button`,{type:`button`,"data-social-not-now":!0,"aria-disabled":i,onClick:()=>void u(e,{state:`stopped`}),children:`Not now`})]})]},e)}),Q(uh,{children:a})]})},wE=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`}],TE=[{presence:`allowed`,label:`Share`},{presence:`blocked`,label:`Block`}],EE=({app:e,grant:t,actions:n,displayName:r})=>{let{busy:i,problem:a,run:o}=SE(),[s,c]=K(!1),l=J(null),u=Ph(e),d=r||u,f=t.presence??`allowed`,p=t=>void o(()=>n.change(e,t)),m=e=>Th.filter(n=>n===e?!t.kinds.includes(n):t.kinds.includes(n)),h=()=>{c(!1),l.current?.focus()},g=async()=>{await o(()=>n.remove(e))&&h()};return Q(`li`,{className:`social-section`,"data-social-app":e,"data-social-app-state":t.state,"data-social-app-presence":f,children:[Q(`span`,{className:`social-choice-label`,children:d}),d!==u&&Q(`span`,{className:`social-muted`,children:u}),t.publishingAsked!==!1&&Q(G,{children:[Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`What it posts`}),Q(`div`,{className:`social-checks`,role:`group`,"aria-label":`What it posts`,children:Th.map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`checkbox`,value:e,checked:t.kinds.includes(e),"aria-disabled":i,onChange:()=>p({kinds:m(e)})}),Q(`span`,{className:`social-choice-label`,children:wh[e]})]},e))})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Who sees its posts`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees its posts`,children:wE.map(({level:n,label:r})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`app-level-${e}`,value:n,checked:t.level===n,"aria-disabled":i,onChange:()=>p({level:n})}),Q(`span`,{className:`social-choice-label`,children:r})]},n))})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,"data-social-app-switch":!0,"aria-disabled":i,onClick:()=>p(t.state===`allowed`?{state:`stopped`}:{state:`allowed`,kinds:bE(t.kinds)}),children:t.state===`allowed`?`Stop`:`Allow`}),Q(`button`,{type:`button`,"data-social-app-delete":!0,ref:l,"aria-disabled":i,onClick:()=>{i||c(!0)},children:`Delete everything it posted`})]}),s&&Q(`div`,{className:`social-warn`,"data-social-delete-app":!0,children:[Q(`p`,{children:[`Delete everything `,d,` posted?`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-social-delete-confirm":!0,ref:lh,"aria-disabled":i,onClick:()=>void g(),children:`Delete`}),Q(`button`,{type:`button`,"aria-disabled":i,onClick:()=>{i||h()},children:`Cancel`})]})]})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Room identity`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Room identity`,children:TE.map(({presence:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`app-presence-${e}`,value:t,checked:f===t,"aria-disabled":i,onChange:()=>p({presence:t})}),Q(`span`,{className:`social-choice-label`,children:n})]},t))}),Q(`span`,{className:`social-muted`,children:`Applies the next time this app joins a room.`})]}),Q(uh,{children:a})]})},DE=({apps:e,actions:t,names:n})=>Q(`ul`,{className:`social-list`,"data-social-apps":!0,children:e.map(({app:e,grant:r})=>Q(EE,{app:e,grant:r,actions:t,displayName:n?.[e]},e))}),OE=e=>t=>{t.key===`Enter`&&e()},kE=({name:e,label:t,placeholder:n,value:r,onChange:i,onSubmit:a})=>{let o=of(r);return Q(G,{children:[Q(`input`,{name:e,"aria-label":t,autoComplete:`off`,autoCapitalize:`none`,spellcheck:!1,maxLength:40,placeholder:n,value:r,onChange:e=>i(e.currentTarget.value),onKeyDown:OE(a)}),!o.ok&&o.reason!==`empty`&&Q(`p`,{className:`social-muted`,children:th(o.reason)})]})},AE=({label:e,onPick:t})=>{let[n,r]=K(``),[i,a]=K(!1),[o,s]=K(null),c=of(n),l=async()=>{if(!c.ok||i)return;a(!0),s(null);let e=await t(c.name);a(!1),e.ok||s(e.reason)};return Q(`div`,{children:[Q(kE,{name:`name`,label:`Name`,placeholder:`your name`,value:n,onChange:e=>{r(e),s(null)},onSubmit:()=>void l()}),c.ok&&c.name!==n&&Q(`p`,{className:`social-muted`,children:[`Saved as `,c.name]}),Q(eh,{reason:o}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-submit":!0,className:`social-primary`,"aria-disabled":!c.ok||i,onClick:()=>void l(),children:i?`Claiming...`:e})})]})},jE=({onRestore:e})=>{let[t,n]=K(``),[r,i]=K(!1),[a,o]=K(null),s=async()=>{if(r||t.trim()===``)return;i(!0),o(null);let n=await e(t);i(!1),n.ok||o(n.reason)};return Q(`div`,{children:[Q(`input`,{name:`recovery-key`,"aria-label":`Recovery key`,autoComplete:`off`,spellcheck:!1,placeholder:`FKNS-...`,value:t,onChange:e=>{n(e.currentTarget.value),o(null)},onKeyDown:OE(()=>void s())}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-submit":!0,"aria-disabled":t.trim()===``||r,onClick:()=>void s(),children:r?`Restoring...`:`Restore`})})]})},ME=({identity:e,fresh:t})=>{let[n,r]=K(t),i=aS(e.seed);return Q(G,{children:[Q(`h2`,{children:t?`Save your recovery key`:`Recovery key`}),Q(`p`,{className:`social-muted`,children:`Keep it somewhere private: anyone holding it can act as you.`}),n&&Q(`code`,{className:`social-key`,"data-recovery-key":!0,children:i}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,onClick:()=>r(!n),children:n?`Hide`:`Show recovery key`}),n&&Q(Sh,{text:i})]})]})},NE={lost:`Your account no longer holds this name.`,unrecorded:`Your name's record is missing. Check that Messages kept is on for it under Rooms in your FKN settings, then write it again.`,taken:`Someone else holds this name now.`,retired:`Names like this one are no longer given out.`},PE={lost:`Claim it again`,unrecorded:`Write it again`},FE=({status:e,onClaimAgain:t,onRename:n})=>{let[r,i]=K(!1),[a,o]=K(null),s=NE[e];if(s===void 0)return null;let c=async()=>{if(r)return;i(!0);let e=await t();i(!1),o(e.ok?null:e.reason)},l=PE[e];return Q(`div`,{className:`social-warn`,role:`status`,children:[Q(`p`,{children:s}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:[l!==void 0&&Q(`button`,{type:`button`,className:`social-primary`,"aria-disabled":r,onClick:()=>void c(),children:r?`Claiming...`:l}),Q(`button`,{type:`button`,onClick:n,children:`Pick another name`})]})]})},IE=({name:e,onGiveBack:t})=>{let[n,r]=K(!1),[i,a]=K(null),o=async()=>{if(n)return;r(!0);let e=await t();r(!1),a(e.ok?null:e.reason)};return Q(`div`,{className:`social-warn`,role:`status`,"data-social-kept":e,children:[Q(`p`,{children:[`Your FKN account still holds `,e,`.`]}),Q(eh,{reason:i}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":n,onClick:()=>void o(),children:n?`Giving back...`:`Give it back`})})]})},LE=({identity:e,fresh:t,status:n,actions:r,avatar:i=null,avatarUrl:a,openRename:o=!1,onRenameOpened:s})=>{let[c,l]=K(!1),[u,d]=K(null),f=lx(e.seed);q(()=>{o&&(l(!0),s?.())},[o,s]);let p=async e=>{let t=await r.rename(e);return t.ok&&l(!1),(t.ok||t.kept!==void 0)&&d(t.kept??null),t},m=async e=>{let t=await r.giveBack(e);return t.ok&&d(null),t};return Q(G,{children:[Q(`div`,{className:`social-card`,"data-social-claim":n,children:[Q(vh,{signKey:f.signKey,src:i,url:a,avatarAlt:`${e.name}'s avatar`}),Q(`div`,{children:[Q(`div`,{className:`social-name`,"data-social-name":!0,style:ch(e.name),children:e.name}),Q(`div`,{className:`social-muted`,children:`Your name on FKN Social`})]})]}),Q(FE,{status:n,onClaimAgain:r.claimAgain,onRename:()=>l(!0)}),u!==null&&Q(IE,{name:u,onGiveBack:()=>m(u)}),c?Q(G,{children:[Q(`h2`,{children:`Change your name`}),Q(`p`,{className:`social-muted`,children:[e.name,` is given back.`]}),Q(AE,{label:`Change name`,onPick:p}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>l(!1),children:`Cancel`})})]}):Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>l(!0),children:`Change name`})}),Q(ME,{identity:e,fresh:t})]})},RE=`FKN rooms did not answer. Try again in a moment.`,zE=(e,t)=>({closed:`${t} is not taking friend requests.`,full:`${t}'s inbox is full. Try again later.`,busy:RE,unavailable:RE})[e],BE=(e,t)=>({...nh,self:`This is you.`,"no-inbox":`You need an inbox to send friend requests.`,closed:zE(`closed`,t),full:zE(`full`,t),busy:RE,unavailable:RE})[e],VE={none:`You have no inbox.`,"out-of-claims":`No inbox: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`,taken:`Someone else holds your inbox now.`,"not-kept":`Your inbox keeps no messages. Turn on Messages kept for it under Rooms in your FKN settings.`,unavailable:RE},HE={...nh,"out-of-claims":VE[`out-of-claims`],busy:RE,unavailable:RE},UE=[`none`,`out-of-claims`,`taken`],WE=({onMake:e})=>{let[t,n]=K(!1),[r,i]=K(null),a=async()=>{if(t)return;n(!0);let r=await e();n(!1),i(r.ok?null:HE[r.reason])};return Q(G,{children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-make-inbox":!0,"aria-disabled":t,onClick:()=>void a(),children:t?`Making an inbox...`:`Make an inbox`})}),r!==null&&Q(`p`,{className:`social-error`,role:`alert`,children:r})]})},GE=({status:e,onMake:t})=>e===`ready`?null:Q(`div`,{className:`social-stack`,"data-social-inbox-line":e,children:[Q(`p`,{className:`social-warn-text`,children:VE[e]}),UE.includes(e)&&Q(WE,{onMake:t})]}),KE=e=>{try{return new URL(e).host}catch{return e}},qE=({signKey:e,name:t,displayName:n=``,storage:r,avatar:i=null})=>Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:e,name:t,storage:r,avatar:i,small:!0}),Q(`div`,{children:[Q(`div`,{className:`social-person-name`,children:n||t}),n!==``&&n!==t&&Q(`div`,{className:`social-muted`,children:t})]})]}),JE=({waiting:e,actions:t,storage:n})=>{let[r,i]=K(!1),[a,o]=K(null),[s,c]=K(!1),{sender:l,request:u}=e,d=async n=>{if(r)return;i(!0);let a=await t.answer(e,n);i(!1),c(!a.ok&&a.reason===`unsent`),o(a.ok||a.reason===`unsent`?null:nh[a.reason])};return Q(`div`,{className:`social-invite`,"data-social-request":l.name,"data-social-confirmed":String(l.confirmed),children:[Q(`p`,{children:[l.name,` sent you a friend request.`]}),Q(qE,{signKey:l.signKey,name:l.name,displayName:u.p.displayName,storage:n,avatar:u.p.avatar??null}),l.confirmed===!1&&Q(`p`,{className:`social-warn-text`,children:`Their name room does not confirm this name.`}),e.friend&&Q(`p`,{className:`social-muted`,children:`Already in your list.`}),s&&Q(`p`,{className:`social-error`,role:`alert`,children:[`Your answer did not reach `,l.name,`.`]}),a!==null&&Q(`p`,{className:`social-error`,role:`alert`,children:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-accept-request":!0,"aria-disabled":r,onClick:()=>void d(!0),children:s?`Send again`:`Accept`}),!s&&Q(`button`,{type:`button`,"data-decline-request":!0,"aria-disabled":r,onClick:()=>void d(!1),children:`Decline`})]})]})},YE=({waiting:e,site:t,actions:n,storage:r,avatar:i})=>{let[a,o]=K(!1),s=t(),c=async()=>{s!==null&&await s.open(e.url).catch(()=>o(!0))};return Q(`div`,{className:`social-invite`,"data-social-party":e.sender.name,children:[Q(`p`,{children:[e.sender.name,` invited you to a party at `,KE(e.url),`.`]}),Q(qE,{signKey:e.sender.signKey,name:e.sender.name,storage:r,avatar:i??null}),Q(`div`,{className:`social-row`,children:[s!==null&&Q(`button`,{type:`button`,className:`social-primary`,"data-open-party":!0,onClick:()=>void c(),children:`Open`}),Q(Sh,{text:e.url}),Q(`button`,{type:`button`,"data-dismiss-party":!0,onClick:()=>void n.dismiss(e),children:`Dismiss`})]}),a&&Q(`p`,{className:`social-muted`,children:`It did not open. Copy it instead.`})]})},XE=({waiting:e,actions:t,storage:n,avatar:r})=>{let[i,a]=K(!1),[o,s]=K(!1),c=async()=>{if(i)return;a(!0);let n=await t.approve(e);a(!1),s(!n)};return Q(`div`,{className:`social-invite`,"data-social-comment":e.sender.name,children:[Q(`p`,{children:[e.sender.name,` commented on your page.`]}),Q(qE,{signKey:e.sender.signKey,name:e.sender.name,storage:n,avatar:r??null}),Q(`p`,{className:`social-bio`,"data-social-comment-text":!0,children:e.text}),o&&Q(`p`,{className:`social-error`,role:`alert`,children:`FKN rooms did not answer, so nothing changed. Try again in a moment.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-approve-comment":!0,"aria-disabled":i,onClick:()=>void c(),children:`Approve`}),Q(`button`,{type:`button`,"data-delete-comment":!0,"aria-disabled":i,onClick:()=>{i||t.dismiss(e)},children:`Delete`})]})]})},ZE=({status:e,waiting:t,accepted:n,site:r,actions:i,onMake:a,storage:o,friendAvatars:s})=>Q(`div`,{className:`social-stack`,"data-social-inbox-status":e??`loading`,children:[n.map(e=>Q(`p`,{"data-social-accepted":e,children:[e,` accepted your friend request.`]},e)),t.map(e=>e.kind===`friend`?Q(JE,{waiting:e,actions:i,storage:o},e.seq):e.kind===`comment`?Q(XE,{waiting:e,actions:i,storage:o,avatar:s?.[e.sender.fingerprint]??null},e.seq):Q(YE,{waiting:e,site:r,actions:i,storage:o,avatar:s?.[e.sender.fingerprint]??null},e.seq)),e!==null&&Q(GE,{status:e,onMake:a})]}),QE=(e,t)=>({unheld:`Nobody holds the name ${t} on FKN Social right now.`,none:`${t}'s page shows nothing right now. Try again in a moment.`,busy:RE,unavailable:RE,malformed:`This link is incomplete. Ask for the link again.`})[e.kind],$E=({onAdd:e})=>{let[t,n]=K(``),r=of(t),i=()=>{r.ok&&(e(r.name),n(``))};return Q(`div`,{"data-social-add-by-name":!0,children:[Q(kE,{name:`friend-name`,label:`Friend's name`,placeholder:`their name`,value:t,onChange:n,onSubmit:i}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-add-by-name":!0,"aria-disabled":!r.ok,onClick:i,children:`Request friend`})})]})},eD=({name:e,own:t,isFriend:n,read:r,send:i,onMake:a,onClose:o,storage:s})=>{let[c,l]=K(e===null?{kind:`malformed`}:null),[u,d]=K(!1),[f,p]=K(null),m=J(null);q(()=>{let e=document.activeElement;return m.current?.focus(),()=>{e instanceof HTMLElement&&e!==document.body&&e.isConnected&&(document.activeElement===document.body||m.current?.contains(document.activeElement))&&e.focus()}},[]),q(()=>{if(e===null)return;let t=!0;return r(e).then(e=>{t&&l(e)}),()=>{t=!1}},[e,r]);let h=e??``,g=c?.kind===`shown`&&e!==null?{name:e,signKey:c.signKey,inbox:c.inbox}:null,_=g===null?null:Jm(g.signKey,t)?{ok:!1,reason:`self`}:g.inbox===null?{ok:!1,reason:`closed`}:null,v=f??_,y=_===null?g:null,b=v===null?c===null?`loading`:c.kind===`shown`?`ready`:c.kind:v.ok?`sent`:v.reason,x=async()=>{y===null||u||(d(!0),p(await i(y)),d(!1))};return Q(`div`,{ref:m,tabIndex:-1,className:`social-invite`,"data-social-send-request":b,children:[Q(`h2`,{children:e===null?`Add a friend`:`Add ${h} as a friend`}),c===null&&Q(`div`,{className:`social-inline-loader`,children:[Q(`span`,{className:`social-loader-track social-loader-track-sm`,"aria-hidden":`true`,children:Q(`span`,{className:`social-loader-bar`})}),Q(`span`,{className:`social-muted`,children:`Loading...`})]}),c!==null&&c.kind!==`shown`&&Q(`p`,{children:QE(c,h)}),c?.kind===`shown`&&Q(qE,{signKey:c.signKey,name:h,displayName:c.profile?.displayName??c.displayName,storage:s,avatar:c.profile?.avatar??null}),y!==null&&n(y.signKey)&&Q(`p`,{className:`social-muted`,children:`Already in your list.`}),v?.ok===!0&&Q(`p`,{role:`status`,children:`Sent.`}),v?.ok===!1&&Q(`p`,{className:`social-error`,role:`alert`,children:BE(v.reason,h)}),v?.ok===!1&&v.reason===`no-inbox`&&Q(WE,{onMake:async()=>{let e=await a();return e.ok&&p(null),e}}),Q(`div`,{className:`social-row`,children:[y!==null&&v?.ok!==!0&&Q(`button`,{type:`button`,className:`social-primary`,"data-send-request":!0,"aria-disabled":u,onClick:()=>void x(),children:u?`Sending...`:`Send friend request`}),Q(`button`,{type:`button`,"data-close-request":!0,onClick:o,children:`Close`})]})]})},tD=e=>X(e.signKey)??new Uint8Array(32),nD=(e,t)=>e.nickname??((t==null?e.profile.displayName:t.displayName)||e.name),rD=(e,t)=>t==null?e.profile.avatar??null:t.avatar,iD=({friends:e,onOpen:t,focusRef:n,storage:r,profiles:i})=>e.length===0?Q(`p`,{className:`social-muted`,"data-social-friends":`0`,children:`No friends yet.`}):Q(`ul`,{className:`social-list`,"data-social-friends":e.length,children:e.map(e=>{let a=i?.[e.fingerprint],o=nD(e,a);return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-person`,"data-social-friend":e.name,ref:n?.(e.fingerprint),onClick:()=>t(e.fingerprint),children:[Q(bh,{signKey:tD(e),name:e.name,storage:r,avatar:rD(e,a),small:!0}),Q(`span`,{children:[Q(`span`,{className:`social-person-name`,children:o}),o!==e.name&&Q(`span`,{className:`social-muted`,children:[` `,e.name]})]})]})},e.fingerprint)})}),aD={invite:`Met through an invite link.`,party:`Met in a party.`,request:`Met through a friend request.`},oD=(e,t)=>e.ok?`Sent.`:e.reason===`link`?`A party link starts with https:// and has at most ${XC.toLocaleString(`en`)} characters.`:e.reason===`no-inbox`?`${t} has no inbox.`:e.reason===`closed`?`${t} cannot take party invites right now.`:zE(e.reason,t),sD=({name:e,onInvite:t})=>{let[n,r]=K(``),[i,a]=K(!1),[o,s]=K(null),c=async()=>{if(i||n.trim()===``)return;a(!0);let e=await t(n);a(!1),s(e),e.ok&&r(``)};return Q(`div`,{className:`social-stack`,"data-social-party-invite":!0,children:[Q(`label`,{className:`social-label`,children:[`Party link`,Q(`input`,{name:`party-link`,autoComplete:`off`,inputMode:`url`,value:n,onChange:e=>{r(e.currentTarget.value),s(null)},onKeyDown:e=>{e.key===`Enter`&&c()}})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-send-party":!0,"aria-disabled":i||n.trim()===``,onClick:()=>void c(),children:i?`Sending...`:`Send invite`})}),o!==null&&Q(`p`,{className:o.ok?`social-muted`:`social-error`,role:o.ok?`status`:`alert`,children:oD(o,e)})]})},cD=({friend:e,site:t,onNickname:n,onRemove:r,onBack:i,onInvite:a,onMessage:o,storage:s,live:c})=>{let[l,u]=K(e.nickname??``),[d,f]=K(!1),[p,m]=K(!1),[h,g]=K(null),_=async e=>{if(p)return;m(!0);let t=await e();m(!1),g(t.ok?null:nh[t.reason])},v=l.trim(),y=v===(e.nickname??``),b=nD(e,c),x=c==null?e.profile.displayName:c.displayName,S=c==null?e.profile.bio:c.bio,C=c==null?e.profile.links:c.links;return Q(`div`,{className:`social-stack`,"data-social-friend-view":e.name,children:[Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:tD(e),name:e.name,storage:s,avatar:rD(e,c)}),Q(`div`,{children:[Q(`div`,{className:`social-name`,tabIndex:-1,ref:lh,style:ch(b),children:b}),b!==e.name&&Q(`div`,{className:`social-muted`,children:e.name})]})]}),x!==``&&e.nickname!==null&&Q(`p`,{children:x}),S!==``&&Q(`p`,{className:`social-bio`,"data-social-bio":!0,children:S}),C.map(e=>Q(Ch,{url:e,site:t},e)),Q(`p`,{className:`social-muted`,children:[`Friends since `,new Date(e.linkedAt).toLocaleDateString(`en`,{year:`numeric`,month:`long`,day:`numeric`}),`.`,` `,aD[e.linkedVia]]}),a!==void 0&&Ky(e.inbox)!==null&&Q(G,{children:[Q(`h2`,{children:`Invite to a party`}),Q(sD,{name:e.name,onInvite:a})]}),Q(`label`,{className:`social-label`,children:[`Nickname, only for you`,Q(`input`,{name:`nickname`,autoComplete:`off`,maxLength:64,value:l,onChange:e=>u(e.currentTarget.value)})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":p||y,onClick:()=>{y||_(()=>n(v===``?null:v))},children:`Save nickname`})}),Q(uh,{children:h}),Q(`div`,{className:`social-row`,children:[o!==void 0&&Q(`button`,{type:`button`,className:`social-primary`,"data-social-message-friend":!0,onClick:o,children:`Message`}),Q(`button`,{type:`button`,onClick:i,children:`Back to friends`}),d?Q(`button`,{type:`button`,className:`social-danger`,"aria-disabled":p,onClick:()=>void _(r),children:[`Remove `,e.name]}):Q(`button`,{type:`button`,onClick:()=>f(!0),children:`Remove`})]})]})},lD=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(lD||{}),uD=[0,1],dD=[1,0],fD=[2,3],pD=[3,2],mD={L:uD,M:dD,Q:fD,H:pD},hD=/^\d*$/,gD=/^[A-Z0-9 $%*+./:-]*$/,_D=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,vD=1,yD=40,bD=3,xD=3,SD=40,CD=10,wD=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],TD=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],ED=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<vD||e>yD)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,lD.Timing),this.setFunctionModule(e,6,e%2==0,lD.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,OD(r,e));this.setFunctionModule(8,7,OD(r,6)),this.setFunctionModule(8,8,OD(r,7)),this.setFunctionModule(7,8,OD(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,OD(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,OD(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,OD(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=OD(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,lD.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,lD.Alignment)}setFunctionModule(e,t,n,r=lD.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==UD(t,n))throw RangeError(`Invalid argument`);let r=TD[n[0]][t],i=wD[n[0]][t],a=Math.floor(HD(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=WD(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=GD(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(HD(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=OD(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=bD:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*SD),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*SD}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=bD:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*SD),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*SD}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=xD)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*CD,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function DD(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function OD(e,t){return!!(e>>>t&1)}var kD=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},AD=[1,10,12,14],jD=[2,9,11,13],MD=[4,8,16,16];function ND(e,t){return e[Math.floor((t+7)/17)+1]}function PD(e){let t=[];for(let n of e)DD(n,8,t);return new kD(MD,e.length,t)}function FD(e){if(!RD(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);DD(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new kD(AD,e.length,t)}function ID(e){if(!zD(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=_D.indexOf(e.charAt(n))*45;r+=_D.indexOf(e.charAt(n+1)),DD(r,11,t)}return n<e.length&&DD(_D.indexOf(e.charAt(n)),6,t),new kD(jD,e.length,t)}function LD(e){return e===``?[]:RD(e)?[FD(e)]:zD(e)?[ID(e)]:[PD(VD(e))]}function RD(e){return hD.test(e)}function zD(e){return gD.test(e)}function BD(e,t){let n=0;for(let r of e){let e=ND(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function VD(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function HD(e){if(e<vD||e>yD)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function UD(e,t){return Math.floor(HD(e)/8)-wD[t[0]][e]*TD[t[0]][e]}function WD(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=KD(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=KD(n,2)}return t}function GD(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=KD(t,e))}return n}function KD(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function qD(e,t,n=1,r=40,i=-1,a=!0){if(!(vD<=n&&n<=r&&r<=yD)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=UD(o,t)*8,i=BD(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[dD,fD,pD])a&&s<=UD(o,e)*8&&(t=e);let c=[];for(let t of e){DD(t.mode[0],4,c),DD(t.numChars,ND(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=UD(o,t)*8;DD(0,Math.min(4,l-c.length),c),DD(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)DD(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new ED(o,t,u,i)}function JD(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?LD(e):Array.isArray(e)?[PD(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=qD(c,mD[n],i,a,o,r),u=YD({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function YD(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=lD.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var XD=({text:e})=>{let{size:t,data:n}=JD(e,{ecc:`L`,border:2}),r=``;return n.forEach((e,t)=>e.forEach((e,n)=>{e&&(r+=`M${n} ${t}h1v1h-1z`)})),Q(`svg`,{className:`social-qr`,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`QR code of the invite link`,shapeRendering:`crispEdges`,children:[Q(`rect`,{width:t,height:t,fill:`#fff`}),Q(`path`,{d:r,fill:`#000`})]})},ZD=(e,t)=>{let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`},QD=()=>{let[e,t]=K(()=>Date.now());return q(()=>{let e=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(e)},[]),e},$D=({peer:e,storage:t,avatar:n=null})=>Q(`div`,{className:`social-stack`,"data-social-peer":e.name,"data-social-confirmed":String(e.confirmed),children:[Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:e.signKey,name:e.name,storage:t,avatar:n,small:!0}),Q(`div`,{children:[Q(`div`,{className:`social-person-name`,children:e.displayName||e.name}),Q(`div`,{className:`social-muted`,children:e.name})]})]}),e.confirmed===!1&&Q(`p`,{className:`social-warn-text`,children:`This name could not be confirmed.`}),e.friend&&Q(`p`,{className:`social-muted`,children:`Already your friend.`})]}),eO=({profile:e,site:t})=>Q(G,{children:[e.bio!==``&&Q(`p`,{className:`social-bio`,children:e.bio}),e.links.map(e=>Q(Ch,{url:e,site:t},e))]}),tO=({link:e,expiresAt:t,state:n,onAdd:r,onClose:i,onSaveAgain:a,onDismiss:o})=>{let s=QD(),[c,l]=K(!1),u=n.kind!==`friends`&&n.kind!==`closed`,d=n.kind===`joined`||n.kind===`offered`||n.kind===`unsaved`;return Q(`div`,{className:`social-invite`,"data-social-host":n.kind,children:[u&&!d&&Q(G,{children:[Q(`code`,{className:`social-key`,"data-invite-link":!0,children:e}),Q(`div`,{className:`social-row`,children:Q(Sh,{text:e,label:`Copy link`})}),Q(XD,{text:e}),Q(`p`,{className:`social-muted`,children:[`This link works while this tab is open, for `,ZD(t,s),` more.`]})]}),Q(`div`,{className:`social-stack`,role:`status`,children:[n.kind===`waiting`&&Q(`p`,{children:`Waiting for someone to open the link.`}),n.kind===`left`&&Q(`p`,{children:`They left. The link still works until it ends.`}),n.kind===`joined`&&Q(G,{children:[Q(`p`,{children:`Someone opened your link:`}),Q($D,{peer:n.peer}),c&&Q(`p`,{className:`social-error`,role:`alert`,children:`The offer did not go out. Try again in a moment.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-add":!0,onClick:()=>void r().then(e=>l(!e)),children:[`Add `,n.peer.name]})})]}),n.kind===`offered`&&Q(G,{children:[Q($D,{peer:n.peer}),Q(`p`,{children:[`Waiting for `,n.peer.name,` to accept.`]})]}),n.kind===`unsaved`&&Q(G,{children:[Q($D,{peer:n.peer}),Q(`p`,{className:`social-error`,role:`alert`,children:[n.peer.name,` accepted, but your friend list was not saved. `,nh[n.reason]]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:a,children:`Save again`})})]}),n.kind===`friends`&&Q(`p`,{"data-social-done":!0,children:[`You and `,n.peer.name,` are now friends.`]}),n.kind===`closed`&&Q(`p`,{children:`This invite has ended.`})]}),Q(`div`,{className:`social-row`,children:u?Q(`button`,{type:`button`,"data-close-invite":!0,onClick:i,children:`Close the invite`}):Q(`button`,{type:`button`,onClick:o,children:`Done`})})]})},nO=`This browser keeps no site data for FKN Social. Allow site data, then open the link again.`,rO=({state:e,site:t,onAccept:n,onDecline:r,onSendAgain:i,onDismiss:a,storage:o})=>{let s=e.kind===`friends`||e.kind===`closed`||e.kind===`in-use`||e.kind===`unavailable`,c=e.kind===`accepting`;return Q(`div`,{className:`social-invite`,"data-social-guest":e.kind,children:[Q(`h2`,{children:`An invite to be friends`}),Q(`div`,{className:`social-stack`,role:`status`,children:[e.kind===`joining`&&Q(`p`,{children:`Opening the invite...`}),e.kind===`waiting`&&(e.host===null?Q(`p`,{children:`Waiting for the person who made it to answer...`}):Q(G,{children:[Q($D,{peer:e.host}),Q(`p`,{children:[`Waiting for `,e.host.name,` to add you.`]})]})),(e.kind===`offered`||e.kind===`accepting`||e.kind===`failed`)&&Q(G,{children:[Q($D,{peer:{...e.host,displayName:e.profile.displayName},storage:o,avatar:e.profile.avatar??null}),Q(eO,{profile:e.profile,site:t}),e.kind===`failed`&&Q(`p`,{className:`social-error`,role:`alert`,children:e.reason===`no-writer`?nO:nh[e.reason]}),Q(`div`,{className:`social-row`,children:[(e.kind!==`failed`||e.reason!==`no-writer`)&&Q(`button`,{type:`button`,className:`social-primary`,"data-accept":!0,"aria-disabled":c,onClick:()=>{c||n()},children:c?`Accepting...`:e.kind===`failed`?`Try again`:`Accept`}),Q(`button`,{type:`button`,"aria-disabled":c,onClick:()=>{c||r()},children:`Decline`})]})]}),e.kind===`unsent`&&Q(G,{children:[Q(`p`,{className:`social-error`,role:`alert`,children:[e.host.name,` is in your friend list, but your answer did not reach them.`]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:i,children:`Send again`})})]}),e.kind===`friends`&&Q(`p`,{"data-social-done":!0,children:[`You and `,e.host.name,` are now friends.`]}),e.kind===`in-use`&&Q(`p`,{children:`Someone else is already using this invite. Ask for a new link.`}),e.kind===`unavailable`&&Q(`p`,{children:`FKN rooms did not answer. Open the link again in a moment.`}),e.kind===`closed`&&Q(`p`,{children:`This invite is no longer open. Ask for a new link.`})]}),s&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:a,children:`Done`})})]})},iO=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`},{level:`off`,label:`Off`}],aO={activity:`Delete all activity?`,comments:`Delete all comments?`},oO=(e,t)=>Object.keys(aO).filter(n=>db(e,n)!==`off`&&db(t,n)===`off`),sO=({layout:e,onPreview:t,onSave:n})=>{let[r,i]=K(e),[a,o]=K(e),[s,c]=K(!1),[l,u]=K(null),[d,f]=K(!1),[p,m]=K(null),h=J(null),g=J(null),_=J(!1),v=e=>{_.current=!0,e?E(!0):m(null)},y=e=>{e!==null&&_.current&&(_.current=!1,e.focus())},b=JSON.stringify(e),[x,S]=K(b);b!==x&&(S(b),b!==JSON.stringify(a)&&(JSON.stringify(r)===JSON.stringify(a)&&i(e),o(e)));let C=e=>{i(e),u(null),f(!1),m(null)},w=(e,t)=>{g.current=`${e}-${t===-1?`up`:`down`}`,C(n=>mb(n,e,t))};gu(()=>{t?.(r)},[r,t]),gu(()=>{if(g.current===null)return;let e=g.current;g.current=null,h.current?.querySelector(`[data-social-move="${e}"]`)?.focus()},[r.sections]);let T=(e,t)=>C(n=>pb(n,e,t)),E=async(e=!1)=>{if(s)return;let t=oO(a,r);if(!e&&t.length>0)return m(t.length>1?`Delete all activity and comments?`:aO[t[0]]);m(null),c(!0);let i=await n(r,a);c(!1),i.ok&&o(r),f(i.ok),u(i.ok?null:nh[i.reason])};return Q(`div`,{className:`social-stack`,"data-social-page-editor":!0,"data-social-theme":r.theme,"data-social-accent":r.accent,children:[Q(`div`,{className:`social-stack`,role:`radiogroup`,"aria-label":`Theme`,children:[Q(`span`,{className:`social-label`,children:`Theme`}),Q(`div`,{className:`social-swatch-row`,children:Zy.map(e=>Q(`label`,{className:`social-choice social-tile`,children:[Q(`input`,{type:`radio`,name:`theme`,value:e,checked:r.theme===e,onChange:()=>C(t=>({...t,theme:e}))}),Q(`span`,{className:`social-swatch`,"data-social-theme-swatch":e,style:{background:`linear-gradient(135deg, ${Xy[e].bg} 0% 50%, ${Xy[e].accent} 50% 100%)`},"aria-hidden":`true`}),Q(`span`,{className:`social-choice-label`,children:Xy[e].label})]},e))})]}),Q(`div`,{className:`social-stack`,role:`radiogroup`,"aria-label":`Colour`,children:[Q(`span`,{className:`social-label`,children:`Colour`}),Q(`div`,{className:`social-swatch-row`,children:Yy.map(e=>Q(`label`,{className:`social-choice social-tile`,children:[Q(`input`,{type:`radio`,name:`accent`,value:e,checked:r.accent===e,onChange:()=>C(t=>({...t,accent:e}))}),Q(`span`,{className:`social-swatch`,"data-social-accent":e,"aria-hidden":`true`}),Q(`span`,{className:`social-choice-label`,children:Jy[e].label})]},e))})]}),Q(`span`,{className:`social-label`,children:`Sections`}),Q(`ul`,{className:`social-list`,ref:h,children:r.sections.map((e,t)=>{let n=eb[e.id],i=e=>e===-1?t===0:t===r.sections.length-1;return Q(`li`,{className:`social-section`,"data-social-section":e.id,children:[Q(`div`,{className:`social-section-head`,children:[Q(`span`,{className:`social-choice-label`,children:n}),Q(`div`,{className:`social-section-moves`,children:[[-1,`up`],[1,`down`]].map(([t,r])=>Q(`button`,{type:`button`,"aria-label":`Move ${n} ${r}`,"aria-disabled":i(t),"data-social-move":`${e.id}-${r}`,onClick:()=>{i(t)||w(e.id,t)},children:[Q(t===-1?Km:qm,{}),`Move `,r]},t))})]}),e.id!==`about`&&Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees ${n}`,children:iO.map(({level:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`${e.id}-level`,value:t,checked:e.level===t,onChange:()=>T(e.id,t)}),Q(`span`,{className:`social-choice-label`,children:n})]},t))})]},e.id)})}),Q(uh,{children:l}),p===null?Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-save-layout":!0,ref:y,"aria-disabled":s,onClick:()=>void E(),children:s?`Saving...`:`Save layout`}),d&&Q(`span`,{className:`social-muted`,"data-social-layout-saved":!0,children:`Saved`})]}):Q(`div`,{className:`social-warn`,"data-social-drop-activity":!0,children:[Q(`p`,{children:p}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-social-drop-confirm":!0,onClick:()=>v(!0),children:`Delete`}),Q(`button`,{type:`button`,onClick:()=>v(!1),children:`Cancel`})]})]})]})},cO=(e,t)=>{if(t===``)return;let n=e.at(-1);n?.kind===`text`?e[e.length-1]={kind:`text`,text:n.text+t}:e.push({kind:`text`,text:t})},lO=e=>e===` `||e===` `||e===`
12
- `||e===`\r`,uO=e=>{if(/\s/.test(e))return null;let t=gf(e);if(t===null)return null;let n=new URL(t);return n.username===``&&n.password===``?t:null},dO=e=>{let t=[],n=[],r=!1,i=0;for(;i<e.length;){if(e[i]==="`"){if(!r){let t=e.indexOf("`",i+1);if(t>i+1){i=t+1;continue}t<0&&(r=!0)}i+=1;continue}if(e[i]===`*`){if(e[i+1]===`*`){let n=i+2;for(;e[n]===`*`;)n+=1;i>0&&!lO(e[i-1])&&t.push(n-2),i=n;continue}i>0&&e[i-1]!==`*`&&!lO(e[i-1])&&n.push(i)}i+=1}return{bold:t,italic:n}},fO=(e,t)=>{let{bold:n,italic:r}=t<2?dO(e):{bold:[],italic:[]},i=0,a=0,o=!1,s=!1,c=[],l=0;for(;l<e.length;){let u=e[l];if(u==="`"){if(!o){let t=e.indexOf("`",l+1);if(t>l+1){c.push({kind:`code`,text:e.slice(l+1,t)}),l=t+1;continue}t<0&&(o=!0)}}else if(u===`[`){let t=l+1;for(;t<e.length;){let n=e[t];if(n===`]`||n===`[`||n===`
13
- `)break;t+=1}if(e[t]===`]`&&e[t+1]===`(`&&!s){let n=e.indexOf(`)`,t+2);if(n<0)s=!0;else{let r=uO(e.slice(t+2,n));if(r!==null){let i=e.slice(l+1,t).trim()||r;c.push({kind:`link`,label:i,href:r}),l=n+1;continue}}}}else if(t<2&&u===`*`){if(e[l+1]===`*`){if(!lO(e[l+2])){for(;i<n.length&&n[i]<=l+2;)i+=1;if(i<n.length){let r=n[i++];c.push({kind:`strong`,children:fO(e.slice(l+2,r),t+1)}),l=r+2;continue}}}else if(!lO(e[l+1])){for(;a<r.length&&r[a]<=l+1;)a+=1;if(a<r.length){let n=r[a++];c.push({kind:`em`,children:fO(e.slice(l+1,n),t+1)}),l=n+1;continue}}}cO(c,u),l+=1}return c},pO=e=>e.startsWith(`### `)?{level:3,body:e.slice(4)}:e.startsWith(`## `)?{level:2,body:e.slice(3)}:e.startsWith(`# `)?{level:1,body:e.slice(2)}:null,mO=e=>e.startsWith(`- `)||e.startsWith(`* `)?e.slice(2):null,hO=e=>{let t=e.replaceAll(`\r
10
+ `).trim();return t!==``&&hf(t,{max:2e3,multiline:!0})===null?t:null},hm=e=>{if(e===void 0)return;let t=e.normalize(`NFC`).trim();if(t!==``)return hf(t,{max:120,multiline:!1})===null?t:null},gm=e=>typeof e==`string`&&dm.test(e),_m=e=>typeof e==`string`&&e.trim()===e&&e!==``&&hf(e,{max:80,multiline:!1})===null,vm=e=>typeof e==`string`&&e.trim()===e&&e!==``&&hf(e,{max:2e3,multiline:!0})===null,ym=e=>{if(e!==void 0)return typeof e!=`string`||e.trim()!==e||e===``||hf(e,{max:120,multiline:!1})!==null?null:e},bm=e=>{if(typeof e!=`object`||!e)return null;let{url:t,key:n,caption:r}=e,i=yf({url:t,key:n}),a=ym(r);return i==null||a===null?null:a===void 0?{url:i.url,key:i.key}:{url:i.url,key:i.key,caption:a}},xm=e=>e.kind===`text`?{id:e.id,kind:`text`,title:e.title,body:e.body}:{id:e.id,kind:`artwork`,title:e.title,items:e.items.map(({url:e,key:t,caption:n})=>n===void 0||n===``?{url:e,key:t}:{url:e,key:t,caption:n})},Sm=e=>{if(typeof e!=`object`||!e)return null;let{id:t,kind:n,title:r}=e;if(!gm(t)||!_m(r))return null;if(n===`text`){let{body:n}=e;return vm(n)?{id:t,kind:`text`,title:r,body:n}:null}if(n===`artwork`){let{items:n}=e;if(!Array.isArray(n)||n.length===0||n.length>4)return null;let i=[];for(let e of n){let t=bm(e);t!==null&&!i.some(e=>e.url===t.url)&&i.push(t)}return i.length>0?{id:t,kind:`artwork`,title:r,items:i}:null}return null},Cm=e=>{let t=[];for(let n of Array.isArray(e)?e:[]){let e=Sm(n);e!==null&&!t.some(t=>t.id===e.id)&&t.length<6&&t.push(e)}return t},wm=e=>{let t=new Set;for(let n of Array.isArray(e)?e:[])if(gm(n)&&t.add(n),t.size>=12)break;return[...t]},Tm=new Set([`public`,`friends`,`off`]),Em=e=>{if(typeof e!=`object`||!e)return null;let{id:t,kind:n,title:r,level:i}=e;if(!gm(t)||!_m(r)||typeof i!=`string`||!Tm.has(i))return null;if(n===`text`){let{body:n}=e;return vm(n)?{id:t,kind:`text`,title:r,body:n,level:i}:null}if(n===`artwork`){let{items:n}=e;if(!Array.isArray(n)||n.length>4)return null;let a=[];for(let e of n){if(typeof e!=`object`||!e)continue;let{picture:t,caption:n}=e,r=yf(t),i=ym(n);r!=null&&i!==null&&!a.some(e=>e.picture.url===r.url)&&a.push(i===void 0?{picture:r}:{picture:r,caption:i})}return{id:t,kind:`artwork`,title:r,items:a,level:i}}return null},Dm=e=>{let t=[];for(let n of Array.isArray(e.profile.panels?.value)?e.profile.panels.value:[]){let e=Em(n);e!==null&&!t.some(t=>t.id===e.id)&&t.length<6&&t.push(e)}return t},Om=e=>e.level===`off`?null:e.kind===`text`?{id:e.id,kind:`text`,title:e.title,body:e.body}:e.items.length===0?null:{id:e.id,kind:`artwork`,title:e.title,items:e.items.map(({picture:e,caption:t})=>t===void 0?{url:e.url,key:e.key}:{url:e.url,key:e.key,caption:t})},km=e=>Dm(e).filter(e=>e.level===`public`).map(Om).filter(e=>e!==null),Am=e=>Dm(e).filter(e=>e.level===`friends`).map(Om).filter(e=>e!==null),jm=e=>Dm(e).filter(e=>Om(e)!==null).map(e=>e.id),Mm=e=>e.kind===`artwork`?e.items.map(e=>e.picture):[],Nm=async(e,t)=>{let n=pm(t.title);if(n===null)return{ok:!1,reason:`title`};let r=mm(t.body);if(r===null)return{ok:!1,reason:`body`};let i=!1,a=await Z(e,e=>{let a=Dm(e);return a.length>=6?(i=!0,{}):{panels:[...a,{id:fm(),kind:`text`,title:n,body:r,level:t.level}]}});return i?{ok:!1,reason:`full`}:a},Pm=async(e,t)=>{let n=pm(t.title);if(n===null)return{ok:!1,reason:`title`};let r=!1,i=await Z(e,e=>{let i=Dm(e);return i.length>=6?(r=!0,{}):{panels:[...i,{id:fm(),kind:`artwork`,title:n,items:[],level:t.level}]}});return r?{ok:!1,reason:`full`}:i},Fm=async(e,t,n)=>{let r=pm(n.title);if(r===null)return{ok:!1,reason:`title`};let i=mm(n.body);if(i===null)return{ok:!1,reason:`body`};let a=!1,o=await Z(e,e=>{let n=Dm(e),o=n.findIndex(e=>e.id===t&&e.kind===`text`);if(o<0)return a=!0,{};let s=[...n];return s[o]={...n[o],title:r,body:i},{panels:s}});return a?{ok:!1,reason:`not-found`}:o},Im=async(e,t,n)=>{let r=pm(n.title);if(r===null)return{ok:!1,reason:`title`};let i={};for(let[e,t]of Object.entries(n.captions)){let n=hm(t);if(n===null)return{ok:!1,reason:`caption`};i[e]=n}let a=!1,o=await Z(e,e=>{let n=Dm(e),o=n.findIndex(e=>e.id===t&&e.kind===`artwork`);if(o<0)return a=!0,{};let s=n[o],c=s.items.map(e=>{if(!Object.hasOwn(i,e.picture.url))return e;let t=i[e.picture.url];return t===void 0?{picture:e.picture}:{picture:e.picture,caption:t}}),l=[...n];return l[o]={...s,title:r,items:c},{panels:l}});return a?{ok:!1,reason:`not-found`}:o},Lm=async(e,t,n)=>Z(e,e=>{let r=Dm(e),i=r.findIndex(e=>e.id===t),a=i+n;if(i<0||a<0||a>=r.length)return{};let o=[...r];return[o[i],o[a]]=[o[a],o[i]],{panels:o}}),Rm=async(e,t,n)=>{let r=[],i=await Z(e,e=>{let i=Dm(e),a=i.findIndex(e=>e.id===t);if(a<0)return{};let o=i[a];if(o.level===n)return{};let s=o.level===`public`&&n!==`public`||o.level===`friends`&&n===`off`,c=[...i];return o.kind===`artwork`&&s&&o.items.length>0?(r=Mm(o),c[a]={...o,items:[],level:n}):c[a]={...o,level:n},{panels:c}});return{outcome:i,dropped:i.ok?r:[]}},zm=async(e,t)=>{let n=[],r=await Z(e,e=>{let r=Dm(e),i=r.find(e=>e.id===t);return i===void 0?{}:(n=Mm(i),{panels:r.filter(e=>e.id!==t)})});return{outcome:r,dropped:r.ok?n:[]}},Bm=async(e,t,n,r)=>{let i=hm(r);if(i===null)return{ok:!1,reason:`caption`};let a=await Jp(e.storage,n,Op);if(!a.ok)return a;let o=null,s=await Z(e,e=>{let n=Dm(e),r=n.findIndex(e=>e.id===t&&e.kind===`artwork`);if(r<0)return o=`not-found`,{};let s=n[r];if(s.level===`off`)return o=`off`,{};if(s.items.length>=4)return o=`items-full`,{};let c=i===void 0?{picture:a.picture}:{picture:a.picture,caption:i},l=[...n];return l[r]={...s,items:[...s.items,c]},{panels:l}});return(!s.ok||o!==null)&&await qp(e.storage,[a.picture]),o===null?s:{ok:!1,reason:o}},Vm=async(e,t,n)=>{let r=[],i=await Z(e,e=>{let i=Dm(e),a=i.findIndex(e=>e.id===t&&e.kind===`artwork`);if(a<0)return{};let o=i[a],s=o.items.find(e=>e.picture.url===n);if(s===void 0)return{};r=[s.picture];let c=[...i];return c[a]={...o,items:o.items.filter(e=>e.picture.url!==n)},{panels:c}});return{outcome:i,dropped:i.ok?r:[]}},Hm=Symbol.for(`pv`),Um=0;Array.isArray;function Q(e,t,n,r,i,a){t||={};var o,s,c=t;if(`ref`in c&&typeof e!=`function`)for(s in c={},t)s==`ref`?o=t[s]:c[s]=t[s];var l={type:e,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:Hm,__v:--Um,__i:-1,__u:0};return(i||a)&&(l.__source=i,l.__self=a),W.vnode&&W.vnode(l),l}var Wm=({size:e=18})=>Q(`svg`,{width:e,height:e,viewBox:`0 0 20 20`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2.25`,y:`2.25`,width:`15.5`,height:`15.5`}),Q(`path`,{d:`M2.25 10h8.5V2.25`}),Q(`rect`,{x:`11.5`,y:`11.5`,width:`3.75`,height:`3.75`,fill:`currentColor`,stroke:`none`})]}),Gm=({id:e})=>{switch(e){case`overview`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`2`,width:`5`,height:`5`}),Q(`rect`,{x:`9`,y:`2`,width:`5`,height:`5`}),Q(`rect`,{x:`2`,y:`9`,width:`5`,height:`5`}),Q(`rect`,{x:`9`,y:`9`,width:`5`,height:`5`})]});case`customize`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`path`,{d:`M2 4h12M2 8h12M2 12h12`}),Q(`rect`,{x:`4`,y:`2.5`,width:`2.5`,height:`3`,fill:`currentColor`}),Q(`rect`,{x:`9.5`,y:`6.5`,width:`2.5`,height:`3`,fill:`currentColor`}),Q(`rect`,{x:`5`,y:`10.5`,width:`2.5`,height:`3`,fill:`currentColor`})]});case`friends`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2.5`,y:`3`,width:`4.5`,height:`4.5`}),Q(`path`,{d:`M1.5 13.5V10h6.5v3.5`}),Q(`rect`,{x:`9.5`,y:`4`,width:`4`,height:`4`}),Q(`path`,{d:`M9.5 10h4.5v3.5`})]});case`messages`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`path`,{d:`M2 2.5h12v9H6.5L3 14.5v-3H2z`}),Q(`path`,{d:`M5 6h6M5 8.5h4`})]});case`inbox`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`3`,width:`12`,height:`10`}),Q(`path`,{d:`M2 8.5h3.5l1.5 2h2l1.5-2H14`})]});case`apps`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`2`,y:`2.5`,width:`12`,height:`11`}),Q(`path`,{d:`M2 6h12M6 6v7.5`})]});case`account`:return Q(`svg`,{className:`social-ico`,width:16,height:16,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:[Q(`rect`,{x:`3`,y:`2.5`,width:`5.5`,height:`5.5`}),Q(`path`,{d:`M8.5 5.25H14V8M11.75 5.25V7.5`}),Q(`path`,{d:`M2.5 13.5h11`})]})}},Km=()=>Q(`svg`,{className:`social-ico`,width:13,height:13,viewBox:`0 0 14 14`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:Q(`path`,{d:`M7 11.5V3M3.5 6.5 7 3l3.5 3.5`})}),qm=()=>Q(`svg`,{className:`social-ico`,width:13,height:13,viewBox:`0 0 14 14`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`square`,strokeLinejoin:`miter`,"aria-hidden":`true`,children:Q(`path`,{d:`M7 2.5V11M3.5 7.5 7 11l3.5-3.5`})});new URL(Vu).host;var Jm=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Ym=({children:e})=>Q(`main`,{className:`social-shell`,children:Q(`section`,{className:`social-panel`,children:[Q(`div`,{className:`social-panel-mark`,"aria-hidden":`true`,children:Q(Wm,{size:18})}),e]})}),Xm=({label:e,state:t,error:n})=>Q(`main`,{className:`social-loader-stage`,"data-social-state":t,children:Q(`div`,{className:`social-loader-box`,children:[n,Q(`div`,{className:`social-loader-mark`,"aria-hidden":`true`,children:Q(Wm,{size:24})}),Q(`div`,{className:`social-loader-brand`,children:`FKN Social`}),Q(`div`,{className:`social-loader-track`,"aria-hidden":`true`,children:Q(`div`,{className:`social-loader-bar`})}),Q(`p`,{className:`social-loader-status`,role:`status`,children:e})]})}),Zm=`Your FKN storage is locked on this device, so nothing changed. Unlock it under Security in your FKN settings, then try again.`,Qm=`Your saved friend list will not open, so nothing changed. If you downloaded your FKN data before, bring it back under Security in your FKN settings.`,$m={empty:`Pick a name.`,"too-short":`A name has at least 3 characters.`,"too-long":`A name has at most 20 characters.`,characters:`Use lowercase letters and digits, with single underscores between them.`,reserved:`That name is reserved. Try another.`,taken:`That name is taken. Try another.`,"out-of-claims":`No claimed rooms left. Unclaim one under Rooms in your FKN settings, then try again.`,busy:`That name has too many connections right now. Close other FKN Social tabs, or try again in a moment.`,unrecorded:`The name's record could not be written. Check that Messages kept is on for it under Rooms in your FKN settings, then try again.`,unavailable:`FKN rooms did not answer. Try again in a moment.`,unreachable:`FKN could not be reached. Check your connection, then try again.`,locked:Zm,reset:`Your saved identity will not open, so nothing changed. Reload the page, then enter your recovery key.`,"list-reset":Qm,newer:`This needs a newer FKN Social. Reload the page to update.`,"no-writer":`This browser keeps no site data for FKN Social. Allow site data, then reload.`,"bad-recovery-key":`That is not a recovery key. A recovery key starts with FKNS, followed by 52 letters and digits.`},eh=({reason:e})=>e===null?null:Q(`p`,{className:`social-error`,role:`alert`,children:$m[e]}),th=e=>$m[e],nh={reset:Qm,locked:Zm,unreachable:`FKN could not be reached, so nothing changed. Check your connection, then try again.`,"no-writer":`This browser keeps no site data for FKN Social. Allow site data, then reload.`,newer:`Your friend list was saved by a newer FKN Social. Reload the page to update.`},rh={"display-name":`A display name has at most 32 characters, and no control or text direction characters.`,bio:`A bio has at most ${_f.toLocaleString(`en`)} characters, and no control or text direction characters.`,links:`You can list at most 5 links.`,link:`Each link starts with https:// and has at most 200 characters.`},ih={title:`Give the panel a title of at most 80 characters, with no control or text direction characters.`,body:`Write panel text of at most ${um.toLocaleString(`en`)} characters, with no control or text direction characters.`,caption:`A caption has at most 120 characters, with no control or text direction characters.`,full:`You can have up to 6 panels. Delete one to add another.`,"items-full":`Each artwork panel holds up to 4 pictures. Remove one to add another.`,"not-found":`That panel is no longer on your page. Reload to see the latest list.`,off:`Set this panel to Friends or Public before uploading artwork.`,"sync-failed":`Your panel changed, but FKN rooms did not update yet. Reload in a moment to sync your page.`},ah=`FKN rooms did not answer, so nothing changed. Try again in a moment.`,oh={...nh,unavailable:ah,"out-of-claims":$m[`out-of-claims`],"not-public":`Your profile is set to Only me, so the picture was not saved. Reload the page.`,"too-large":`That picture is too large or could not be made small enough. Pick another.`,kind:`Pick a PNG, JPEG, GIF or WebP picture.`,quota:`Your FKN storage is full, so the picture was not published. Free some space, then try again.`,"too-many":`FKN is not accepting new files from your account right now, so the picture was not published. Try again later.`,"storage-unavailable":`FKN storage did not answer, so the picture was not published. Try again in a moment.`},sh=e=>{let t=e.replace(/[a-ln-vx-z0-9_]/g,``).length;return t*1.05+(e.length-t)*.72},ch=e=>({fontSize:`clamp(0.875rem, ${100/Math.max(1,...e.split(/\s+/).map(sh))}cqi, 1.75rem)`}),lh=e=>{e?.focus()},uh=({children:e})=>e===null?null:Q(`p`,{className:`social-error`,role:`alert`,children:e}),dh=({signKey:e,label:t=`Your identicon`,small:n=!1})=>{let{hue:r,cells:i}=ff(e);return Q(`svg`,{className:n?`social-identicon social-identicon-small`:`social-identicon`,viewBox:`0 0 6 6`,role:`img`,"aria-label":t,children:[Q(`rect`,{width:6,height:6,fill:`hsl(${r} 45% 92%)`}),i.map((e,t)=>e&&Q(`rect`,{x:.5+t%5,y:.5+Math.floor(t/5),width:1,height:1,fill:`hsl(${r} 55% 42%)`},t))]})},fh=64,ph=33554432,mh=new WeakMap,hh=(e,t)=>{let n=0;for(let t of e.values())n+=t.bytes;for(let[r,i]of e){if(e.size<=fh&&n<=ph)break;r!==t&&(e.delete(r),n-=i.bytes)}},gh=(e,t,n)=>{let r=mh.get(e);r===void 0&&(r=new Map,mh.set(e,r));let i=`${t.url}\0${t.key}\0${n}`,a=r.get(i);if(a!==void 0)return r.delete(i),r.set(i,a),a.promise;let o={bytes:0,promise:Qp(e,t,n).then(e=>e===null?(r.get(i)===o&&r.delete(i),null):(r.get(i)===o&&(o.bytes=e.size,r.delete(i),r.set(i,o),hh(r,i)),e))};return r.set(i,o),hh(r,i),o.promise},_h=(e,t,n)=>{let r=t?.url??null,i=t?.key??null,[a,o]=K({storage:null,url:null,key:null,max:0,objectUrl:null});return q(()=>{if(r===null||i===null){o(e=>e.objectUrl===null&&e.url===null?e:{storage:null,url:null,key:null,max:0,objectUrl:null});return}let t=!0,a=null;return gh(e,{url:r,key:i},n).then(s=>{let c=s===null?null:URL.createObjectURL(s);if(!t){c!==null&&URL.revokeObjectURL(c);return}a=c,o({storage:e,url:r,key:i,max:n,objectUrl:c})}),()=>{t=!1,a!==null&&URL.revokeObjectURL(a)}},[e,r,i,n]),r===null||i===null?null:a.storage===e&&a.url===r&&a.key===i&&a.max===n?a.objectUrl:void 0},vh=({signKey:e,src:t,url:n,label:r=`Your identicon`,avatarAlt:i=`Your avatar`,small:a=!1})=>{let o=a?`social-identicon social-identicon-small`:`social-identicon`;return t===void 0?Q(`span`,{className:o,"data-social-avatar-reading":!0,"aria-hidden":`true`}):t===null?Q(dh,{signKey:e,label:r,small:a}):Q(`img`,{className:`${o} social-avatar-img`,src:t,alt:i,"data-social-avatar":n})},yh={get:()=>Promise.reject(Error(`social: no storage`))},bh=({signKey:e,name:t,storage:n,avatar:r=null,small:i=!1})=>{let a=_h(n??yh,n===void 0?null:r,wp.avatar);return r===null||n===void 0?Q(dh,{signKey:e,label:`${t}'s identicon`,small:i}):Q(vh,{signKey:e,src:a,url:r.url,label:`${t}'s identicon`,avatarAlt:`${t}'s avatar`,small:i})},xh=async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},Sh=({text:e,label:t=`Copy`})=>{let[n,r]=K(null);return Q(G,{children:[Q(`button`,{type:`button`,onClick:()=>void xh(e).then(e=>r(e?`Copied`:`Copy did not work. Select the text and copy it.`)),children:t}),n!==null&&Q(`span`,{className:`social-muted`,role:`status`,"data-social-copied":n===`Copied`,children:n})]})},Ch=({url:e,site:t})=>{let[n,r]=K(!1),i=t();return Q(`div`,{className:`social-link`,"data-social-link":e,children:[Q(`div`,{className:`social-link-bar`,children:[Q(`span`,{className:`social-link-text`,children:e}),Q(`div`,{className:`social-link-actions`,children:[i!==null&&Q(`button`,{type:`button`,"data-open-link":!0,onClick:()=>void i.open(e).catch(()=>r(!0)),children:`Open`}),Q(Sh,{text:e})]})]}),n&&Q(`p`,{className:`social-muted`,children:`It did not open. Copy it instead.`})]})},wh={started:`Started`,watched:`Watched`,completed:`Finished`,rated:`Rated`},Th=Object.keys(wh),Eh=36e5,Dh={public:[],friends:[]},Oh=/^[A-Za-z0-9_-]{22}$/,kh=RegExp(`^[\\x20-\\x7e]{1,64}$`),Ah=(e,t)=>typeof e==`string`&&e!==``&&e.isWellFormed()&&hf(e,{max:t,multiline:!1})===null,jh=e=>typeof e==`string`&&gf(e,300)===e,Mh=e=>{try{return new URL(e)}catch{return null}},Nh=e=>Ah(e,100),Ph=e=>{let t=Mh(e);return t!==null&&(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e?t.host:e},Fh=(e,t)=>{let n=Mh(t);return n?.protocol!==`https:`||n.origin!==t||Mh(e)?.origin===t},Ih=({id:e,app:t,at:n,kind:r,title:i,link:a,detail:o,image:s,subject:c})=>({id:e,app:t,at:n,kind:r,title:i,link:a,...o===void 0?{}:{detail:o},...s===void 0?{}:{image:s},...c===void 0?{}:{subject:c}}),Lh=e=>{if(typeof e!=`object`||!e)return null;let{id:t,app:n,at:r,kind:i,title:a,detail:o,link:s,image:c,subject:l}=e;return typeof t!=`string`||!Oh.test(t)||!Ah(n,100)||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||typeof i!=`string`||!Object.hasOwn(wh,i)||!Ah(a,150)||!jh(s)||!Fh(s,n)||o!==void 0&&!Ah(o,40)||c!==void 0&&!jh(c)||l!==void 0&&(typeof l!=`string`||!kh.test(l))?null:Ih({id:t,app:n,at:r,kind:i,title:a,link:s,detail:o,image:c,subject:l})},Rh=e=>typeof e==`string`?e.normalize(`NFC`).trim():e,zh=(e,t,n)=>{if(typeof e!=`object`||!e)return null;let{kind:r,title:i,detail:a,link:o,image:s,subject:c}=e,l=Rh(a),u=e=>typeof e==`string`?gf(e,300)??``:e;return Lh({id:Y(crypto.getRandomValues(new Uint8Array(16))),app:t,at:n,kind:r,title:Rh(i),link:u(o),...l===void 0||l===``?{}:{detail:l},...s===void 0?{}:{image:u(s)},...c===void 0?{}:{subject:c}})},Bh=e=>{if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let e=Lh(r);if(!(e===null||t.has(e.id))&&(t.add(e.id),n.push(e),n.length===50))break}return n},Vh=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((e,t)=>t.at-e.at||(e.id<t.id?-1:+(e.id>t.id))).slice(0,50)},Hh=(e,t,n)=>[...e.public,...e.friends].filter(e=>e.app===t&&e.at>n).length,Uh=(e,t)=>({...e,public:e.public.filter(e=>!t.includes(e.id)),friends:e.friends.filter(e=>!t.includes(e.id))}),Wh=(e,t)=>({...e,public:e.public.filter(e=>e.app!==t),friends:e.friends.filter(e=>e.app!==t)}),Gh=(e,t)=>({...e,public:e.public.filter(e=>e.app!==t),friends:Vh(e.friends,e.public.filter(e=>e.app===t))}),Kh=(e,t)=>[t,...e.filter(e=>e.id!==t.id)].slice(0,50),qh=(e,t)=>t===`off`?{...e,public:[],friends:[]}:t===`friends`?{...e,public:[],friends:Vh(e.friends,e.public)}:e,Jh=/^fkn:app:[a-z0-9]+$/,Yh=e=>Jh.test(e),Xh=async(e,t)=>{if(!Yh(e))return null;let n=t?.fetch??globalThis.fetch,r=t?.apiOrigin??Uu;try{let t=await n(`${r}/v1/apps/${encodeURIComponent(e)}/keys`);if(!t.ok)return null;let i=await t.json(),a=typeof i?.name==`string`?i.name:typeof i?.list?.name==`string`?i.list.name:null;return a!==null&&Ah(a,100)?a:null}catch{return null}},Zh=e=>{let t=new Map,n=new Map;return r=>{if(!Yh(r))return Promise.resolve(null);let i=t.get(r);if(i!==void 0)return Promise.resolve(i);let a=n.get(r);if(a!==void 0)return a;let o=Xh(r,e).then(e=>(n.delete(r),e!==null&&t.set(r,e),e),()=>(n.delete(r),null));return n.set(r,o),o}};function Qh(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var $h=e=>e?`"${e}" `:``;function eg(e,t=``){if(typeof e!=`boolean`)throw TypeError($h(t)+`expected boolean, got type=`+typeof e);return e}function tg(e,t=``){if(typeof e!=`number`)throw TypeError($h(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError($h(t)+`expected integer >= 0, got `+e);return e}function ng(e,t,n=``){if(Qh(e)&&(t===void 0||e.length===t))return e;t!==void 0&&tg(t,`length`);let r=Qh(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=$h(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var rg=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function ig(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function ag(e,t){ng(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function og(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function sg(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function cg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var lg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ug(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function dg(e){for(let t=0;t<e.length;t++)e[t]=ug(e[t]);return e}var fg=lg?e=>e:dg;function pg(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function mg(e,t){if(pg(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function hg(e,t){return rg(e,`defaults`),rg(t,`opts`),Object.assign(e,t)}function gg(e,t){if(e=ng(e),t=ng(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function _g(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var vg=(e,t)=>{function n(n,...r){if(ng(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];ng(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Qh(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&ng(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);ng(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,ng(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(ng(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function yg(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(ng(t,e,`output`),n&&!xg(t))throw Error(`invalid output, must be aligned`);return t}function bg(e,t,n){tg(e),tg(t),eg(n);let r=new Uint8Array(16),i=cg(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function xg(e){return e.byteOffset%4==0}function Sg(e){return Uint8Array.from(ng(e))}var Cg=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),wg=fg(og(Cg(`expand 16-byte k`))),Tg=fg(og(Cg(`expand 32-byte k`)));function $(e,t){return e<<t|e>>>32-t}var Eg=64,Dg=16,Og=2**32-1,kg=Uint32Array.of();function Ag(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Eg),u=og(l),d=lg&&xg(i)&&xg(a),f=d?og(i):kg,p=d?og(a):kg;if(!lg){for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),fg(u),o>=Og)throw Error(`arx: counter overflow`);let f=Math.min(Eg,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}return}for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Og)throw Error(`arx: counter overflow`);let h=Math.min(Eg,c-m);if(d&&h===Eg){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Dg;t++)n=e+t,p[n]=f[n]^u[t];m+=Eg;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function jg(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=hg({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return tg(i),tg(o),eg(a),eg(n),(t,s,c,l,u=0)=>{ng(t,void 0,`key`),ng(s,void 0,`nonce`),ng(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=yg(d,l,!1),f&&mg(c,l),tg(u),u<0||u>=Og)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=Sg(t)),g=Tg;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=wg,p.push(h);else throw ng(t,32,`arx key`),Error(`invalid key size`);(!lg||!xg(s))&&p.push(s=Sg(s));let _=og(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(lg)r(g,_,og(e),_);else{let t=fg(Uint32Array.from(g));r(t,_,og(e),_),sg(t),fg(_)}s=s.subarray(16)}else lg||fg(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=fg(og(s));try{return Ag(e,g,_,y,c,l,u,o),l}finally{sg(...p)}}}function Mg(e,t){return e[t++]&255|(e[t++]&255)<<8}var Ng=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Sg(ng(e,32,`key`));let t=Mg(e,0),n=Mg(e,2),r=Mg(e,4),i=Mg(e,6),a=Mg(e,8),o=Mg(e,10),s=Mg(e,12),c=Mg(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Mg(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=Mg(e,t+0),_=Mg(e,t+2),v=Mg(e,t+4),y=Mg(e,t+6),b=Mg(e,t+8),x=Mg(e,t+10),S=Mg(e,t+12),C=Mg(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),O=i[4]+((y>>>4|b<<12)&8191),k=i[5]+(b>>>1&8191),A=i[6]+((b>>>14|x<<2)&8191),j=i[7]+((x>>>11|S<<5)&8191),M=i[8]+((S>>>8|C<<8)&8191),N=i[9]+(C>>>5|r),P=0,F=P+w*o+5*h*T+5*m*E+5*p*D+5*f*O;P=F>>>13,F&=8191,F+=5*d*k+5*u*A+5*l*j+5*c*M+5*s*N,P+=F>>>13,F&=8191;let I=P+w*s+T*o+5*h*E+5*m*D+5*p*O;P=I>>>13,I&=8191,I+=5*f*k+5*d*A+5*u*j+5*l*M+5*c*N,P+=I>>>13,I&=8191;let L=P+w*c+T*s+E*o+5*h*D+5*m*O;P=L>>>13,L&=8191,L+=5*p*k+5*f*A+5*d*j+5*u*M+5*l*N,P+=L>>>13,L&=8191;let R=P+w*l+T*c+E*s+D*o+5*h*O;P=R>>>13,R&=8191,R+=5*m*k+5*p*A+5*f*j+5*d*M+5*u*N,P+=R>>>13,R&=8191;let ee=P+w*u+T*l+E*c+D*s+O*o;P=ee>>>13,ee&=8191,ee+=5*h*k+5*m*A+5*p*j+5*f*M+5*d*N,P+=ee>>>13,ee&=8191;let te=P+w*d+T*u+E*l+D*c+O*s;P=te>>>13,te&=8191,te+=k*o+5*h*A+5*m*j+5*p*M+5*f*N,P+=te>>>13,te&=8191;let z=P+w*f+T*d+E*u+D*l+O*c;P=z>>>13,z&=8191,z+=k*s+A*o+5*h*j+5*m*M+5*p*N,P+=z>>>13,z&=8191;let ne=P+w*p+T*f+E*d+D*u+O*l;P=ne>>>13,ne&=8191,ne+=k*c+A*s+j*o+5*h*M+5*m*N,P+=ne>>>13,ne&=8191;let re=P+w*m+T*p+E*f+D*d+O*u;P=re>>>13,re&=8191,re+=k*l+A*c+j*s+M*o+5*h*N,P+=re>>>13,re&=8191;let ie=P+w*h+T*m+E*p+D*f+O*d;P=ie>>>13,ie&=8191,ie+=k*u+A*l+j*c+M*s+N*o,P+=ie>>>13,ie&=8191,P=(P<<2)+P|0,P=P+F|0,F=P&8191,P>>>=13,I+=P,i[0]=F,i[1]=I,i[2]=L,i[3]=R,i[4]=ee,i[5]=te,i[6]=z,i[7]=ne,i[8]=re,i[9]=ie}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;sg(n)}update(e){ig(this),ng(e),e=Sg(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,sg(this.h,this.r,this.buffer,this.pad)}digestInto(e){ig(this),ag(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},Pg=_g(32,e=>new Ng(e));function Fg(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I=b,L=x;for(let e=0;e<a;e+=2)S=S+E|0,P=$(P^S,16),A=A+P|0,E=$(E^A,12),S=S+E|0,P=$(P^S,8),A=A+P|0,E=$(E^A,7),C=C+D|0,F=$(F^C,16),j=j+F|0,D=$(D^j,12),C=C+D|0,F=$(F^C,8),j=j+F|0,D=$(D^j,7),w=w+O|0,I=$(I^w,16),M=M+I|0,O=$(O^M,12),w=w+O|0,I=$(I^w,8),M=M+I|0,O=$(O^M,7),T=T+k|0,L=$(L^T,16),N=N+L|0,k=$(k^N,12),T=T+k|0,L=$(L^T,8),N=N+L|0,k=$(k^N,7),S=S+D|0,L=$(L^S,16),M=M+L|0,D=$(D^M,12),S=S+D|0,L=$(L^S,8),M=M+L|0,D=$(D^M,7),C=C+O|0,P=$(P^C,16),N=N+P|0,O=$(O^N,12),C=C+O|0,P=$(P^C,8),N=N+P|0,O=$(O^N,7),w=w+k|0,F=$(F^w,16),A=A+F|0,k=$(k^A,12),w=w+k|0,F=$(F^w,8),A=A+F|0,k=$(k^A,7),T=T+E|0,I=$(I^T,16),j=j+I|0,E=$(E^j,12),T=T+E|0,I=$(I^T,8),j=j+I|0,E=$(E^j,7);let R=0;r[R++]=o+S|0,r[R++]=s+C|0,r[R++]=c+w|0,r[R++]=l+T|0,r[R++]=u+E|0,r[R++]=d+D|0,r[R++]=f+O|0,r[R++]=p+k|0,r[R++]=m+A|0,r[R++]=h+j|0,r[R++]=g+M|0,r[R++]=_+N|0,r[R++]=v+P|0,r[R++]=y+F|0,r[R++]=b+I|0,r[R++]=x+L|0}function Ig(e,t,n,r){let i=lg?e:fg(e.slice(0,4)),a=lg?t:fg(t.slice(0,8)),o=lg?n:fg(n.slice(0,4)),s=new Uint32Array(16);Fg(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,fg(r),lg||sg(i,a,o),sg(s)}var Lg=jg(Fg,{counterRight:!1,counterLength:8,extendNonceFn:Ig,allowShortKeys:!1}),Rg=new Uint8Array(16),zg=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Rg.subarray(n))},Bg=new Uint8Array(32);function Vg(e,t,n,r,i){i!==void 0&&ng(i,void 0,`AAD`);let a=e(t,n,Bg),o=bg(r.length,i?i.length:0,!0),s=Pg.create(a);i&&zg(s,i),zg(s,r),s.update(o);let c=s.digest();return sg(a,o),c}var Hg=vg({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=yg(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Vg(e,t,n,s,r);return a.set(c,o),sg(c),a},decrypt(i,a){a=yg(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Vg(e,t,n,o,r);if(!gg(s,c))throw sg(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),sg(c),a}}))(Lg));function Ug(e,t,n=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}var Wg=(e,t,n)=>md(e,t,n),Gg=pd;function Kg(e,t=`object`){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`);return e}function qg(e,t){if(typeof e!=`function`)throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Jg=Td,Yg=(...e)=>Od(...e),Xg=e=>Dd(e),Zg=dd,Qg=e=>jd(e),$g=BigInt(0),e_=BigInt(1),t_=e=>e?`"${e}" `:``;function n_(e,t=``){if(typeof e!=`boolean`)throw TypeError(t_(t)+`expected boolean, got type=`+typeof e);return e}function r_(e){if(typeof e==`bigint`){if(!d_(e))throw RangeError(`positive bigint expected, got `+e)}else Gg(e);return e}function i_(e,t=``){if(typeof e!=`number`){let n=t&&`"${t}" `;throw TypeError(n+`expected number, got type=`+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw RangeError(n+`expected safe integer, got `+e)}}function a_(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);return e===``?$g:BigInt(`0x`+e)}function o_(e){return a_(Td(e))}function s_(e){return a_(Td(u_(md(e)).reverse()))}function c_(e,t){if(pd(t),t===0)throw Error(`zero output length is invalid`);e=r_(e);let n=t*2,r=e.toString(16);if(r.length>n)throw RangeError(`number is too large`);return Dd(r.padStart(n,`0`))}function l_(e,t){return c_(e,t).reverse()}function u_(e){return Uint8Array.from(Wg(e))}function d_(e){return typeof e==`bigint`&&$g<=e}function f_(e,t,n){return d_(e)&&d_(t)&&d_(n)&&t<=e&&e<n}function p_(e,t,n,r){if(!f_(t,n,r))throw RangeError(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function m_(e){if(e<$g)throw Error(`expected non-negative bigint, got `+e);return e===$g?0:e.toString(2).length}var h_=e=>(i_(e,`n`),(e_<<BigInt(e))-e_);function g_(e,t={},n={},r=`object`){Kg(e,r),Kg(t,`fields`),Kg(n,`optFields`);function i(t,n,i){let a=r===`object`?`param "${String(t)}"`:`"${r}.${String(t)}"`,o=e[t];if(!Object.hasOwn(e,t)&&(i?o!==void 0:n!==`function`))throw TypeError(`${a} is invalid: expected own property`);if(i&&o===void 0)return;let s=typeof o;if(s!==n||o===null)throw TypeError(`${a} is invalid: expected ${n}, got ${s}`)}let a=(e,t)=>Object.entries(e).forEach(([e,n])=>i(e,n,t));a(t,!1),a(n,!0)}var __=BigInt(0),v_=BigInt(1),y_=BigInt(2),b_=BigInt(3),x_=BigInt(4),S_=BigInt(5),C_=BigInt(7),w_=BigInt(8),T_=BigInt(9),E_=BigInt(15),D_=BigInt(16),O_=BigInt(`0x10000000000000000`);function k_(e,t){if(t<=__)throw Error(`mod: expected positive modulus, got `+t);let n=e%t;return n>=__?n:t+n}function A_(e,t,n){if(n<=v_)throw Error(`pow: expected modulus > 1, got `+n);if(typeof t!=`bigint`)throw TypeError(`invalid exponent: expected bigint, got `+typeof t);if(t<__)throw Error(`invalid exponent, negatives unsupported`);if(t===__)return v_;if(t===v_)return e;let r=e%n;if(r<__&&(r+=n),t<O_){let e=v_;for(;t>__;)t&v_&&(e=e*r%n),r=r*r%n,t>>=v_;return e}let i=[];for(;t>__;)i.push(Number(t&E_)),t>>=x_;let a=Array(16);a[0]=v_,a[1]=r;for(let e=2;e<16;e++)a[e]=a[e-1]*r%n;let o=a[i[i.length-1]];for(let e=i.length-2;e>=0;e--){o=o*o%n,o=o*o%n,o=o*o%n,o=o*o%n;let t=i[e];t!==0&&(o=o*a[t]%n)}return o}function j_(e,t,n){if(n<=v_)throw Error(`pow2: expected modulus > 1, got `+n);if(t<__)throw Error(`pow2: expected non-negative exponent, got `+t);let r=e;for(;t-->__;)r*=r,r%=n;return r}function M_(e,t){if(e===__)throw Error(`invert: expected non-zero number`);if(t<=v_)throw Error(`invert: expected modulus > 1, got `+t);let n=k_(e,t),r=t,i=__,a=v_;for(;n!==__;){let e=r/n,t=r-n*e,o=i-a*e;r=n,n=t,i=a,a=o}if(r!==v_)throw Error(`invert: does not exist`);return k_(i,t)}function N_(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw Error(`Cannot find square root`)}function P_(e,t){if((e&v_)===__)throw Error(t+`: expected odd modulus, got `+e)}function F_(e,t){let n=e,r=(n.ORDER+v_)/x_,i=n.pow(t,r);return N_(n,i,t),i}function I_(e,t){let n=e,r=(n.ORDER-S_)/w_,i=n.mul(t,y_),a=n.pow(i,r),o=n.mul(t,a),s=n.mul(n.mul(o,y_),a),c=n.mul(o,n.sub(s,n.ONE));return N_(n,c,t),c}function L_(e){let t=J_(e),n=R_(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+C_)/D_;return((e,t)=>{let n=e,s=n.pow(t,o),c=n.mul(s,r),l=n.mul(s,i),u=n.mul(s,a),d=n.eql(n.sqr(c),t),f=n.eql(n.sqr(l),t);s=n.cmov(s,c,d),c=n.cmov(u,l,f);let p=n.eql(n.sqr(c),t),m=n.cmov(s,c,p);return N_(n,m,t),m})}function R_(e){if(e<b_)throw Error(`sqrt is not defined for small field`);P_(e,`tonelliShanks`);let t=e-v_,n=0;for(;t%y_===__;)t/=y_,n++;let r=y_,i=J_(e);for(;W_(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return F_;let a=i.pow(r,t),o=(t+v_)/y_;return function(e,r){let i=e;if(i.is0(r))return r;if(W_(i,r)!==1)throw Error(`Cannot find square root`);let s=n,c=i.mul(i.ONE,a),l=i.pow(r,t),u=i.pow(r,o);for(;!i.eql(l,i.ONE);){if(i.is0(l))throw Error(`Cannot find square root: probably non-prime P`);let e=1,t=i.sqr(l);for(;!i.eql(t,i.ONE);)if(e++,t=i.sqr(t),e===s)throw Error(`Cannot find square root`);let n=v_<<BigInt(s-e-1),r=i.pow(c,n);s=e,c=i.sqr(r),l=i.mul(l,c),u=i.mul(u,r)}return u}}function z_(e){return P_(e,`Fp.sqrt`),e%x_===b_?F_:e%w_===S_?I_:e%D_===T_?L_(e):R_(e)}var B_=(e,t)=>(k_(e,t)&v_)===v_,V_=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function H_(e){if(Kg(e,`field`),typeof e.ORDER!=`bigint`)throw TypeError(`param "ORDER" is invalid: expected bigint, got `+typeof e.ORDER);i_(e.BYTES,`BYTES`),i_(e.BITS,`BITS`);for(let t of V_)qg(e[t],`field.`+t);if(e.BYTES<1||e.BITS<1)throw Error(`invalid field: expected BYTES/BITS > 0`);if(e.ORDER<=v_)throw Error(`invalid field: expected ORDER > 1, got `+e.ORDER);return e}function U_(e,t,n=!1){H_(e),Ug(t,`nums`),n_(n,`passZero`);let r=e,i=Array(t.length).fill(n?r.ZERO:void 0),a=t.reduce((e,t,n)=>r.is0(t)?e:(i[n]=e,r.mul(e,t)),r.ONE),o=r.inv(a);return t.reduceRight((e,t,n)=>r.is0(t)?e:(i[n]=r.mul(e,i[n]),r.mul(e,t)),o),i}function W_(e,t){H_(e);let n=e;P_(n.ORDER,`FpLegendre`);let r=(n.ORDER-v_)/y_,i=n.pow(t,r),a=n.eql(i,n.ONE),o=n.eql(i,n.ZERO),s=n.eql(i,n.neg(n.ONE));if(!a&&!o&&!s)throw Error(`invalid Legendre symbol result`);return a?1:o?0:-1}function G_(e,t){if(t!==void 0&&Gg(t),e<=__)throw Error(`invalid n length: expected positive n, got `+e);if(t!==void 0&&t<1)throw Error(`invalid n length: expected positive bit length, got `+t);let n=m_(e);if(t!==void 0&&t<n)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t===void 0?n:t;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}var K_=new WeakMap,q_=class{ORDER;BITS;BYTES;isLE;ZERO=__;ONE=v_;_lengths;_mod;constructor(e,t={}){if(e<=v_)throw Error(`invalid field: expected ORDER > 1, got `+e);let n;this.isLE=!1,typeof t==`object`&&t&&(typeof t.BITS==`number`&&(n=t.BITS),typeof t.sqrt==`function`&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE==`boolean`&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes==`boolean`&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:i}=G_(e,n);if(i>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);this.ORDER=e,this.BITS=r,this.BYTES=i,Object.freeze(this)}create(e){return k_(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw TypeError(`invalid field element: expected bigint, got `+typeof e);return __<=e&&e<this.ORDER}is0(e){return e===__}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&v_)===v_}neg(e){return k_(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return k_(e*e,this.ORDER)}add(e,t){return k_(e+t,this.ORDER)}sub(e,t){return k_(e-t,this.ORDER)}mul(e,t){return k_(e*t,this.ORDER)}pow(e,t){return A_(e,t,this.ORDER)}div(e,t){return k_(e*M_(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return M_(e,this.ORDER)}sqrt(e){let t=K_.get(this);return t||K_.set(this,t=z_(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?l_(e,this.BYTES):c_(e,this.BYTES)}fromBytes(e,t=!1){Wg(e);let{_lengths:n,BYTES:r,isLE:i,ORDER:a,_mod:o}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>r)throw Error(`Field.fromBytes: expected `+n+` bytes, got `+e.length);let t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw Error(`Field.fromBytes: expected `+r+` bytes, got `+e.length);let s=i?s_(e):o_(e);if(o&&(s=k_(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return U_(this,e,!0)}cmov(e,t,n){return n_(n,`condition`),n?t:e}};function J_(e,t={}){return Object.freeze(q_.prototype),new q_(e,t)}var Y_=BigInt(0),X_=BigInt(1),Z_=BigInt(4),Q_=16,$_=128,ev=5,tv=2**31;function nv(e){let t=e;if(typeof t!=`function`)throw TypeError(`"Point" expected constructor, got type=`+typeof e);qg(t.fromAffine,`Point.fromAffine`),qg(t.fromBytes,`Point.fromBytes`),qg(t.fromHex,`Point.fromHex`),Kg(t.BASE,`Point.BASE`),Kg(t.ZERO,`Point.ZERO`),H_(t.Fp),H_(t.Fn)}function rv(e,t){nv(e),sv(t,e);let n=U_(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function iv(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw Error(`invalid window size, expected [`+n+`..`+t+`], got W=`+e)}function av(e,t){let n=e*(4*t+128);if(n>tv)throw Error(`invalid window size: table would need ~`+Math.ceil(n/2**20)+` MiB, max `+tv/2**20+` MiB`)}function ov(e,t){if(e!==void 0){qg(e,`randomBytes`);try{let n=e(t);if(!Zg(n)||n.length!==t)return}catch{return}return e}}function sv(e,t){Ug(e,`points`),e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function cv(e,t,n){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,r)=>{if(!(n===void 0?t.isValid(e):d_(e)&&e<n))throw Error(`invalid scalar at index `+r)})}var lv=new WeakMap;function uv(e){return lv.get(e)||1}function dv(e,t){let n=e.double(),r=[e];for(let e=1;e<t;e++)r.push(r[e-1].add(n));return r}function fv(e,t){let n=2**t,r=n/2,i=BigInt(n-1),a=[];for(;e>Y_;){let t=0;e&X_&&(t=Number(e&i),t>=r&&(t-=n),e-=BigInt(t)),a.push(t),e>>=X_}return a}function pv(e,t,n){let r=2**t,i=r/2,a=BigInt(r-1),o=BigInt(t),s=[];for(let t=0;t<n;t++){let t=Number(e&a);e>>=o,t>i&&(t-=r,e+=X_),s.push(t)}if(e!==Y_)throw Error(`invalid wnaf`);return s}function mv(e,t,n){let r=0;for(let e of n)r=Math.max(r,e.length);let i=e;for(let e=r-1;e>=0;e--){e!==r-1&&(i=i.double());for(let r=0;r<n.length;r++){let a=n[r][e];if(a){let e=t[r][Math.abs(a)-1>>1];i=i.add(a<0?e.negate():e)}}}return i}var hv=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){nv(e),this.randomBytes=ov(t,Q_),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let r=Math.ceil(n/t)+1,i=2**(t-1),a=[],o=e;for(let e=0;e<r;e++){let e=o;for(let t=0;t<i;t++)a.push(e),e=e.add(o);o=a[a.length-1].double()}return{W:t,bits:n,windows:r,comp:a}}wnafCachedCT(e,t){let{W:n,windows:r,comp:i}=e,a=2**(n-1),o=pv(t,n,r),s=this.ZERO,c=this.BASE;for(let e=0;e<r;e++){let t=o[e],n=e*a,r=Math.abs(t)-1,l=i[n];for(let e=1;e<a;e++)l=e===r?i[n+e]:l;let u=l.negate();t===0?c=c.add(i[n]):s=s.add(t<0?u:l)}return{p:s,f:c}}getWnafPrecomputes(e,t,n,r){let i=this.wnafPrecomputes.get(t),a=i?.find(t=>t.W===e&&t.bits===n);return a||(a=this.buildWnafTable(t,e,n),typeof r==`function`&&(a={...a,comp:r(a.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(a)),a}assertPoint(e){if(!(e instanceof this.Point))throw TypeError(`"point" expected Point instance, got type=`+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!f_(t,X_,this.Point.Fn.ORDER))throw Error(`invalid scalar`)}runCT(e,t,n,r){let i=uv(e);return i===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(i,e,n,r),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error(`randomBytes is required for scalar blinding`);let r=this.Point.Fn.BITS+$_,i=this.randomBytes(Q_);if(!Zg(i)||i.length!==Q_)throw Error(`randomBytes returned invalid byte array`);i[0]=i[0]&63|128;let a=t+o_(i)*this.Point.Fn.ORDER;return this.runCT(e,a,r,n)}fixedWindowCT(e,t,n){let r=ev,i=h_(r),a=Array(32);a[0]=this.ZERO;for(let t=1;t<32;t++)a[t]=a[t-1].add(e);let o=Math.ceil(n/r),s=this.ZERO;for(let e=o-1;e>=0;e--){if(e!==o-1)for(let e=0;e<r;e++)s=s.double();let n=Number(t>>BigInt(e*r)&i),c=a[0];for(let e=1;e<32;e++)c=e===n?a[e]:c;s=s.add(c)}return{p:s,f:s}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===X_||e===this.BASE&&(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,r){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,n){if(this.assertPoint(e),!d_(t))throw Error(`invalid scalar`);let r=uv(e);if(r===1||t>=this.Point.Fn.ORDER)return gv(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(r,e,this.bits,n);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),iv(t,this.bits),av((Math.ceil((this.bits+$_)/t)+1)*2**(t-1),this.Point.Fp.BYTES),lv.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return uv(e)!==1}};function gv(e,t,n,r=!1){if(nv(e),sv(t,e),n_(r,`allowOversized`),cv(n,e.Fn,r?e.Fn.ORDER**Z_:void 0),t.length!==n.length)throw Error(`arrays of points and scalars must have equal length`);let i=t.map(e=>dv(e,4)),a=n.map(e=>fv(e,4));return mv(e.ZERO,i,a)}function _v(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return H_(t),t}return J_(e,{isLE:n})}function vv(e,t,n={},r){if(e!==`weierstrass`&&e!==`edwards`)throw Error(`expected curve type "weierstrass" or "edwards"`);if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);g_(n);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(d_(n)&&n!==Y_))throw Error(`CURVE.${e} must be positive bigint`)}let i=_v(t.p,n.Fp,r),a=_v(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}function yv(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var bv=BigInt(0),xv=BigInt(1),Sv=BigInt(2),Cv=BigInt(4),wv=BigInt(8);function Tv(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function Ev(e,t={}){g_(t,{},{},`extraOpts`);let n=t,r=vv(`edwards`,e,n,n.FpFnLE),{Fp:i,Fn:a}=r,o=r.CURVE,{h:s}=o;if(W_(i,o.a)!==1)throw Error(`edwards: CURVE.a must be a square in Fp for complete addition formulas`);if(W_(i,o.d)!==-1)throw Error(`edwards: CURVE.d must be a non-square in Fp for complete addition formulas`);g_(n,{},{uvRatio:`function`,randomBytes:`function`});let c=n.randomBytes===void 0?Qg:n.randomBytes,l=Sv<<BigInt(i.BYTES*8)-xv;function u(e){if(!i.isOdd)throw Error(`Field does not have .isOdd()`);return i.isOdd(e)}let d=n.uvRatio===void 0?(e,t)=>{try{return{isValid:!0,value:i.sqrt(i.div(e,t))}}catch{return{isValid:!1,value:bv}}}:n.uvRatio;if(!Tv(i,o,o.Gx,o.Gy))throw Error(`bad curve params: generator point`);let f=i.eql(o.a,i.neg(i.ONE))?e=>i.neg(e):i.eql(o.a,i.ONE)?e=>e:e=>i.mul(o.a,e);function p(e,t,n=!1){let r=n?xv:bv;return p_(`coordinate `+e,t,r,l),t}function m(e){if(!(e instanceof h))throw Error(`EdwardsPoint expected`)}class h{static BASE=new h(o.Gx,o.Gy,i.ONE,i.mul(o.Gx,o.Gy));static ZERO=new h(i.ZERO,i.ONE,i.ONE,i.ZERO);static Fp=i;static Fn=a;X;Y;Z;T;constructor(e,t,n,r){this.X=p(`x`,e),this.Y=p(`y`,t),this.Z=p(`z`,n,!0),this.T=p(`t`,r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof h)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return p(`x`,t),p(`y`,n),new h(t,n,i.ONE,i.mul(t,n))}static fromBytes(e,t=!1){let n=i.BYTES,{a:r,d:a}=o;e=u_(Wg(e,n,`point`)),n_(t,`zip215`);let s=u_(e),c=e[n-1];s[n-1]=c&-129;let f=s_(s);p_(`point.y`,f,bv,t?l:i.ORDER);let p=i.sqr(f),m=i.sub(p,i.ONE),g=i.sub(i.mulN(a,p),r),{isValid:_,value:v}=d(m,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=u(v),b=!!(c&128);if(!t&&i.is0(v)&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=i.neg(v)),h.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return h.fromBytes(Xg(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=6,t=!0){return _.setWindowSize(this,e),t||this.multiply(Sv),this}assertValidity(){let e=this,{a:t,d:n}=o;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:a,Z:s,T:c}=e,l=i.sqr(r),u=i.sqr(a),d=i.sqr(s),f=i.sqr(d),p=i.mul(l,t),m=i.mul(i.add(p,u),d),h=i.add(f,i.mul(n,i.mul(l,u)));if(!i.eql(m,h))throw Error(`bad point: equation left != right (1)`);let g=i.mul(r,a),_=i.mul(s,c);if(!i.eql(g,_))throw Error(`bad point: equation left != right (2)`)}equals(e){m(e);let{X:t,Y:n,Z:r}=this,{X:a,Y:o,Z:s}=e,c=i.mul(t,s),l=i.mul(a,r),u=i.mul(n,s),d=i.mul(o,r);return i.eql(c,l)&&i.eql(u,d)}is0(){return this.equals(h.ZERO)}negate(){return new h(i.neg(this.X),this.Y,this.Z,i.neg(this.T))}double(){let{X:e,Y:t,Z:n}=this,r=i.sqr(e),a=i.sqr(t),o=i.mul(i.sqr(n),Sv),s=f(r),c=i.addN(e,t),l=i.sub(i.subN(i.sqr(c),r),a),u=i.addN(s,a),d=i.subN(u,o),p=i.subN(s,a),m=i.mul(l,d),g=i.mul(u,p),_=i.mul(l,p),v=i.mul(d,u);return new h(m,g,v,_)}add(e){m(e);let{d:t}=o,{X:n,Y:r,Z:a,T:s}=this,{X:c,Y:l,Z:u,T:d}=e,p=i.mul(n,c),g=i.mul(r,l),_=i.mul(i.mulN(s,t),d),v=i.mul(a,u),y=i.sub(i.subN(i.mulN(i.addN(n,r),i.addN(c,l)),p),g),b=i.subN(v,_),x=i.addN(v,_),S=i.sub(g,f(p)),C=i.mul(y,b),w=i.mul(x,S),T=i.mul(y,S),E=i.mul(b,x);return new h(C,w,E,T)}subtract(e){return m(e),this.add(e.negate())}multiply(e){if(!a.isValidNot0(e))throw RangeError(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=_.mulSecret(this,e,s,g);return g([t,n])[0]}multiplyUnsafe(e){if(!a.isValid(e))throw RangeError(`invalid scalar: expected 0 <= sc < curve.n`);return e===bv?h.ZERO:this.is0()||e===xv?this:_.mulUnsafe(this,e,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return _.mulUnsafe(this,o.n).is0()}toAffine(e){let t=this,n=e;if(n!=null&&typeof n!=`bigint`)throw TypeError(`"invertedZ" expected bigint, got type=`+typeof n);let{X:r,Y:a,Z:o}=t,s=t.is0();n??=s?i.create(wv):i.inv(o);let c=i.mul(r,n),l=i.mul(a,n),u=i.mul(o,n);if(s)return{x:i.ZERO,y:i.ONE};if(!i.eql(u,i.ONE))throw Error(`invZ was invalid`);return{x:c,y:l}}clearCofactor(){return s===xv?this:s===Sv?this.double():s===Cv?this.double().double():s===wv?this.double().double().double():this.multiplyUnsafe(s)}toBytes(){let{x:e,y:t}=this.toAffine(),n=i.toBytes(t);return n[n.length-1]|=u(e)?128:0,n}toHex(){return Jg(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let g=e=>rv(h,e),_=new hv(h,c);return _.bits>=6&&h.BASE.precompute(6),Object.freeze(h.prototype),Object.freeze(h),h}function Dv(e,t,n={}){if(nv(e),typeof t!=`function`)throw Error(`"hash" function param is required`);let r=t,i=n;g_(i,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,zip215:`boolean`,mapToCurve:`function`,toMontgomery:`function`,toMontgomerySecret:`function`});let{prehash:a}=i,{BASE:o,Fp:s,Fn:c}=e,l=r.outputLen,u=2*s.BYTES;if(l!==void 0&&(i_(l,`hash.outputLen`),l!==u))throw Error(`hash.outputLen must be ${u}, got ${l}`);let d=i.randomBytes===void 0?Qg:i.randomBytes,f=i.toMontgomery,p=i.toMontgomerySecret,m=i.adjustScalarBytes===void 0?e=>e:i.adjustScalarBytes,h=i.domain===void 0?(e,t,n)=>{if(n_(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e}:i.domain;function g(e){return c.create(s_(e))}function _(e){let t=T.secretKey;Wg(e,T.secretKey,`secretKey`);let n=Wg(r(e),2*t,`hashedSecretKey`),i=m(n.slice(0,t));return{head:i,prefix:n.slice(t,2*t),scalar:g(i)}}function v(e){let{head:t,prefix:n,scalar:r}=_(e),i=o.multiply(r);return{head:t,prefix:n,scalar:r,point:i,pointBytes:i.toBytes()}}function y(e){return v(e).pointBytes}function b(e=Uint8Array.of(),...t){let n=Yg(...t);return g(r(h(n,Wg(e,void 0,`context`),!!a)))}function x(e,t,n={}){g_(n,{},{},`options`),e=u_(Wg(e,void 0,`message`)),a&&(e=a(e));let{prefix:r,scalar:i,pointBytes:s}=v(t),l=b(n.context,r,e),u=o.multiply(l).toBytes(),d=b(n.context,u,s,e),f=c.create(l+d*i);if(!c.isValid(f))throw Error(`sign failed: invalid s`);return Wg(Yg(u,c.toBytes(f)),T.signature,`result`)}let S={zip215:i.zip215};function C(t,n,r,i=S){g_(i);let{context:s}=i,c=i.zip215===void 0?!!S.zip215:i.zip215,l=T.signature;t=Wg(t,l,`signature`),n=Wg(n,void 0,`message`),r=Wg(r,T.publicKey,`publicKey`),c!==void 0&&n_(c,`zip215`),a&&(n=a(n));let u=l/2,d=t.subarray(0,u),f=s_(t.subarray(u,l)),p,m,h;try{p=e.fromBytes(r,c),m=e.fromBytes(d,c),h=o.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let g=b(s,d,r,n);return m.add(p.multiplyUnsafe(g)).subtract(h).clearCofactor().is0()}let w=s.BYTES,T={secretKey:w,publicKey:w,signature:2*w,seed:w};function E(e){return e=e===void 0?d(T.seed):e,Wg(e,T.seed,`seed`)}function D(e){return Zg(e)&&e.length===T.secretKey}function O(t,n){try{return!!e.fromBytes(t,n===void 0?S.zip215:n)}catch{return!1}}let k={getExtendedPublicKey:v,randomSecretKey:E,isValidSecretKey:D,isValidPublicKey:O,toMontgomery(t){if(f===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return f(e.fromBytes(t))},toMontgomerySecret(e){if(p===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return p(e)}};return Object.freeze(T),Object.freeze(k),Object.freeze({keygen:yv(E,y),getPublicKey:y,sign:x,verify:C,utils:k,Point:e,lengths:T})}var Ov=BigInt(0),kv=BigInt(1),Av=BigInt(2);function jv(e,t){return e+t-(t>>kv<<kv)}function Mv(e){let t=BigInt(6)*e;return(n,r,i)=>{let a=r+i,o=((t+i-r)*n+r)%e;return{x_2:o,x_3:a-o}}}function Nv(e){return g_(e,{P:`bigint`,type:`string`,adjustScalarBytes:`function`,powPminus2:`function`},{randomBytes:`function`,scalarMultBase:`function`}),Object.freeze({...e})}function Pv(e){let t=Nv(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:a,randomBytes:o}=t,s=t.scalarMultBase,c=r===`x25519`;if(!c&&r!==`x448`)throw Error(`invalid type`);let l=o===void 0?Qg:o,u=c?255:448,d=Mv(n),f=c?32:56,p=BigInt(c?9:5),m=BigInt(c?121665:39081),h=c?Av**BigInt(254):Av**BigInt(447),g=h+(c?BigInt(8)*(Av**BigInt(251)-kv):BigInt(4)*(Av**BigInt(445)-kv))+kv,_=e=>k_(e,n),v=y(p);function y(e){return l_(_(e),f)}function b(e){let t=u_(Wg(e,f,`uCoordinate`));return c&&(t[31]&=127),_(s_(t))}function x(e){return s_(i(u_(Wg(e,f,`scalar`))))}let S=new Set(c?[Ov,kv,n-kv,BigInt(`325606250916557431795983626356110631294008115727848805560023387167927233504`),BigInt(`39382357235489614581723060781553021112529911719440698176882885853963445705823`)]:[Ov,kv,n-kv]);function C(e,t){let n=b(t);if(S.has(n))throw Error(`invalid private or public key received`);let r=D(n,x(e));if(r===Ov)throw Error(`invalid private or public key received`);return y(r)}function w(e){if(s===void 0)return C(e,v);let t=x(e);p_(`scalar`,t,h,g);let n=_(s(t));if(n===Ov)throw Error(`invalid private or public key received`);return y(n)}let T=w,E=C;function D(e,t){p_(`u`,e,Ov,n),p_(`scalar`,t,h,g);let r=t,i=e,o=kv,s=Ov,c=e,l=kv,f=r^r>>kv;for(let e=BigInt(u-1);e>=Ov;e--){let t=jv(n,f>>e);({x_2:o,x_3:c}=d(t,o,c)),{x_2:s,x_3:l}=d(t,s,l);let r=o+s,a=_(r*r),u=o-s,p=_(u*u),h=a-p,g=c+l,v=c-l,y=_(v*r),b=_(g*u),x=y+b,S=y-b;c=_(x*x),l=_(i*_(S*S)),o=_(a*p),s=_(h*(a+_(m*h)))}let p=jv(n,r);({x_2:o,x_3:c}=d(p,o,c)),{x_2:s,x_3:l}=d(p,s,l);let v=a(s);return _(o*v)}let O={secretKey:f,publicKey:f,seed:f},k=e=>(e=e===void 0?l(f):e,Wg(e,O.seed,`seed`),e),A={randomSecretKey:k};return Object.freeze(O),Object.freeze(A),Object.freeze({keygen:yv(k,T),getSharedSecret:E,getPublicKey:T,scalarMult:C,scalarMultBase:w,utils:A,GuBytes:v.slice(),lengths:O})}var Fv=BigInt(0),Iv=BigInt(1),Lv=BigInt(2),Rv=BigInt(3),zv=BigInt(5),Bv=BigInt(8),Vv=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),Hv={p:Vv,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:Bv,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function Uv(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=Vv,o=e*e%a*e%a,s=j_(j_(o,Lv,a)*o%a,Iv,a)*e%a,c=j_(s,zv,a)*s%a,l=j_(c,t,a)*c%a,u=j_(l,n,a)*l%a,d=j_(u,r,a)*u%a;return{pow_p_5_8:j_(j_(j_(j_(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,Lv,a)*e%a,b2:o}}function Wv(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Gv=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function Kv(e,t){let n=Vv,r=k_(t*t*t,n),i=Uv(e*k_(r*r*t,n)).pow_p_5_8,a=k_(e*r*i,n),o=k_(t*a*a,n),s=a,c=k_(a*Gv,n),l=o===e,u=o===k_(-e,n),d=o===k_(-e*Gv,n);return l&&(a=s),(u||d)&&(a=c),B_(a,n)&&(a=k_(-a,n)),{isValid:l||u,value:a}}var qv=Ev(Hv,{uvRatio:Kv}),Jv=qv.Fp;function Yv(e){let{y:t}=e;return Jv.toBytes(Jv.div(Iv+t,Iv-t))}function Xv(e){let t=qv.Fp.BYTES;return md(e,t),Wv(Xd(e.subarray(0,t))).subarray(0,t)}function Zv(e){return Dv(qv,Xd,Object.assign({adjustScalarBytes:Wv,toMontgomery:Yv,toMontgomerySecret:Xv,zip215:!0},e))}var Qv=Zv({}),$v=(()=>{let e=Vv,t=t=>{let{pow_p_5_8:n,b2:r}=Uv(t);return k_(j_(n,Rv,e)*r,e)};return Pv({P:e,type:`x25519`,powPminus2:t,adjustScalarBytes:Wv,scalarMultBase:n=>{let r=k_(n,qv.Fn.ORDER);if(r===Fv)return Fv;let i=qv.BASE.multiply(r);return k_((i.Z+i.Y)*t(k_(i.Z-i.Y,e)),e)}})})(),ey=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hd(e),md(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),bd(r)}update(e){return vd(this),this.iHash.update(e),this}digestInto(e){vd(this),yd(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ty=(()=>{let e=((e,t,n)=>new ey(e,t).update(n).digest());return e.create=(e,t)=>new ey(e,t),e})(),ny=Uint8Array.of(0),ry=Uint8Array.of();function iy(e,t,n,r=32,i){hd(e),pd(r,`length`),md(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=ry:md(n,void 0,`info`),!o)return i&&bd(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=ty.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){ny[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(ny).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(ny[0]=o,o>1&&c.update(u),c.update(n).update(ny).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&bd(u),bd(ny),r===s.length)return s;let f=s.slice(0,r);return bd(s),f}var ay=(e,t,n,r,i)=>{hd(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=ty.create(e,n).update(t);return iy(e,a.digest(),r,i,a)},oy={public:[],friends:[]},sy=/^[A-Za-z0-9_-]{22}$/,cy=new TextEncoder,ly=e=>{if(typeof e!=`string`||!e.isWellFormed())return null;let t=e.normalize(`NFC`).trim();return t!==``&&hf(t,{max:500,multiline:!0})===null?t:null},uy=e=>Y(Yd(cy.encode(e)).slice(0,16)),dy=({id:e,name:t,text:n,at:r})=>({id:e,name:t,text:n,at:r}),fy=e=>{if(typeof e!=`object`||!e)return null;let{id:t,name:n,text:r,at:i}=e;return typeof t!=`string`||!sy.test(t)||typeof n!=`string`||!sf(n)||typeof r!=`string`||ly(r)!==r||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,text:r,at:i}},py=(...e)=>{let t=new Map;for(let n of e.flat())t.has(n.id)||t.set(n.id,n);return[...t.values()].sort((e,t)=>t.at-e.at||(e.id<t.id?-1:+(e.id>t.id))).slice(0,20)},my=e=>py(Array.isArray(e)?e.map(fy).filter(e=>e!==null):[]),hy=e=>e.comments??oy,gy=(e,t)=>({public:py(hy(e).public,hy(t).public),friends:py(hy(e).friends,hy(t).friends)}),_y=(e,t)=>{let n=hy(e);return[...n.public,...n.friends].some(e=>e.id===t.id)?e:{...e,comments:{...n,public:py([t],n.public)}}},vy=(e,t)=>{let n=hy(e);return{...e,comments:{public:n.public.filter(e=>!t.includes(e.id)),friends:n.friends.filter(e=>!t.includes(e.id))}}},yy=(e,t)=>{let n=hy(e);return t===`off`?{...e,comments:oy}:t===`friends`?{...e,comments:{public:[],friends:py(n.friends,n.public)}}:e},by=e=>{if(typeof e!=`object`||!e)return null;let{title:t,link:n,image:r}=e;return!Ah(t,150)||!jh(n)||r!==void 0&&!jh(r)?null:r===void 0?{title:t,link:n}:{title:t,link:n,image:r}},xy=e=>{let t=[];for(let n of Array.isArray(e)?e:[]){let e=by(n);e!==null&&!t.some(t=>t.link===e.link)&&t.length<8&&t.push(e)}return t},Sy=e=>xy(e.profile.favourites?.value),Cy=async(e,t,n)=>{let r=by(t);if(r===null)return{ok:!1,reason:`invalid`};let i=!1,a=await Z(e,e=>{let t=Sy(e),a=t.filter(e=>e.link!==r.link);return n?a.length<t.length?{}:(i=t.length>=8,i?{}:{favourites:[...t,r]}):a.length===t.length?{}:{favourites:a}});return i?{ok:!1,reason:`full`}:a},wy=`fkn/social/v1/sign`,Ty=`fkn/social/v1/dh`,Ey=`fkn/social/v1/hello`,Dy=`fkn/social/v1/offer`,Oy=`fkn/social/v1/accept`,ky=`fkn/social/v1/handshake`,Ay=`fkn/social/v1/pair`,jy=`fkn/social/v1/name`,My=`fkn/social/v2/name`,Ny=`fkn/social/v1/name-room`,Py=`fkn/social/v1/request`,Fy=`fkn/social/v1/request-seal`,Iy=`fkn/social/v1/friends`,Ly=`fkn/social/v1/friend-slot`,Ry=`fkn/social/v1/page`,zy=`fkn/social/v1/chat-direct`,By=`fkn/social/v1/chat-self`,Vy=`fkn/social/v1/chat-sign`,Hy=`fkn/social/v1/chat-group-seal`,Uy=`fkn/social/v1/chat-group-msg`,Wy=`fkn/social/v1/chat-group-pair`,Gy=/^[A-Za-z0-9_-]{43}$/,Ky=e=>{if(typeof e!=`string`||e[43]!==`.`||!Gy.test(e.slice(0,43)))return null;let t=e.slice(44);return t.length>=1&&t.length<=300&&!t.includes(`\0`)?e:null},qy=e=>e.slice(44),Jy=(e,t=Hu,n=Wu)=>{let r=`${n}/`;if(t!==n&&e.startsWith(r)){let n=e.slice(r.length);if(n.length>0)return[e,`${t}/${n}`]}return[e]},Yy=(e,t,n=Hu,r=Wu)=>e===t||Jy(e,n,r).includes(t)||Jy(t,n,r).includes(e),Xy={blue:{label:`Blue`,light:{accent:`#2f5bd3`,text:`#ffffff`},dark:{accent:`#7c9cff`,text:`#0d1430`}},purple:{label:`Purple`,light:{accent:`#7442c8`,text:`#ffffff`},dark:{accent:`#b99cff`,text:`#1f1236`}},pink:{label:`Pink`,light:{accent:`#b8327a`,text:`#ffffff`},dark:{accent:`#ff8ac4`,text:`#3a0f26`}},red:{label:`Red`,light:{accent:`#c0352b`,text:`#ffffff`},dark:{accent:`#ff8f84`,text:`#3d0f0b`}},orange:{label:`Orange`,light:{accent:`#b04e0f`,text:`#ffffff`},dark:{accent:`#ffa163`,text:`#3a1a05`}},green:{label:`Green`,light:{accent:`#2a7a3b`,text:`#ffffff`},dark:{accent:`#6fd38a`,text:`#0b2a13`}},teal:{label:`Teal`,light:{accent:`#0f7671`,text:`#ffffff`},dark:{accent:`#5fd0c8`,text:`#062a28`}},grey:{label:`Grey`,light:{accent:`#5c5a55`,text:`#ffffff`},dark:{accent:`#bdb9b0`,text:`#1d1c1a`}}},Zy=Object.keys(Xy),Qy={steel:{label:`Steel`,light:!1,bg:`#13161a`,sheet:`#181c21`,panel:`#20252c`,head:`#2b333e`,border:`#38414e`,text:`#f0f2f5`,muted:`#adb5c0`,accent:`#8cb4d8`,accentText:`#0f1720`,pill:`#283647`,skyTop:`#262d37`,skyBot:`#13161a`},midnight:{label:`Midnight`,light:!1,bg:`#11161d`,sheet:`#151c26`,panel:`#1c2431`,head:`#243245`,border:`#34465e`,text:`#eef2f7`,muted:`#a4b2c4`,accent:`#7ea8de`,accentText:`#0c1422`,pill:`#23354c`,skyTop:`#1b283a`,skyBot:`#11161d`},forest:{label:`Forest`,light:!1,bg:`#111714`,sheet:`#151e19`,panel:`#1c2721`,head:`#23372c`,border:`#334d3f`,text:`#edf4ef`,muted:`#a5bdaf`,accent:`#76d690`,accentText:`#0a2412`,pill:`#213a2c`,skyTop:`#1c3126`,skyBot:`#111714`},crimson:{label:`Crimson`,light:!1,bg:`#181214`,sheet:`#20171a`,panel:`#281d21`,head:`#3c242c`,border:`#54353f`,text:`#f7eef0`,muted:`#c4a8b0`,accent:`#ee95a3`,accentText:`#290b12`,pill:`#41252e`,skyTop:`#351d24`,skyBot:`#181214`},slate:{label:`Slate`,light:!1,bg:`#141416`,sheet:`#1b1c1f`,panel:`#222428`,head:`#2d3036`,border:`#3d4149`,text:`#f1f2f4`,muted:`#b2b6be`,accent:`#c4c8d0`,accentText:`#141518`,pill:`#30333b`,skyTop:`#26282e`,skyBot:`#141416`},daylight:{label:`Daylight`,light:!0,bg:`#eceef2`,sheet:`#ffffff`,panel:`#f5f6f9`,head:`#e3e7ef`,border:`#cfd5e0`,text:`#14161a`,muted:`#505662`,accent:`#2752c4`,accentText:`#ffffff`,pill:`#dce5f5`,skyTop:`#d7dfec`,skyBot:`#eceef2`}},$y=Object.keys(Qy),eb=`steel`,tb={light:{error:`#b3261e`,warnBg:`#fff4dc`,warnLine:`#e9c46a`},dark:{error:`#ff8a80`,warnBg:`#352b16`,warnLine:`#8a6d1f`}},nb={about:`About`,activity:`Activity`,favourites:`Favourites`,comments:`Comments`},rb=Object.keys(nb),ib={accent:`blue`,theme:eb,sections:[{id:`about`},{id:`activity`,level:`off`},{id:`favourites`,level:`off`},{id:`comments`,level:`off`}]},ab={accent:`blue`,sections:[`about`]},ob=16,sb=e=>typeof e==`string`&&rb.includes(e),cb=e=>typeof e==`string`&&Object.hasOwn(Xy,e)?e:`blue`,lb=e=>typeof e==`string`&&Object.hasOwn(Qy,e)?e:eb,ub=new Set([`public`,`friends`,`off`]),db=(e,t)=>{if(e===`about`)return{id:e};let n=t?.level;return{id:e,level:typeof n==`string`&&ub.has(n)?n:`off`}},fb=e=>{let t=e.profile.page?.value;if(typeof t!=`object`||!t)return ib;let{accent:n,theme:r,sections:i}=t,a=new Map;for(let e of Array.isArray(i)?i:[]){let t=e?.id;sb(t)&&!a.has(t)&&a.set(t,db(t,e))}for(let e of rb)a.has(e)||a.set(e,db(e));return{accent:cb(n),theme:lb(r),sections:[...a.values()]}},pb=(e,t)=>{let n=e.sections.find(e=>e.id===t);return n!==void 0&&n.id!==`about`?n.level:`off`},mb=(e,t)=>pb(fb(e),t),hb=(e,t,n)=>({...e,sections:e.sections.map(e=>e.id===t?{id:t,level:n}:e)}),gb=(e,t,n)=>{let r=e.sections.findIndex(e=>e.id===t),i=r+n;if(r<0||i<0||i>=e.sections.length)return e;let a=[...e.sections];return[a[r],a[i]]=[a[i],a[r]],{...e,sections:a}},_b=(e,t)=>{if(e.profile.page===void 0)return null;let{accent:n,theme:r,sections:i}=fb(e);return{accent:n,...r===`steel`?{}:{theme:r},sections:i.filter(e=>e.id===`about`?t:e.level===`public`).map(({id:e})=>e)}},vb=(e,t)=>fb(e).sections.filter(e=>e.id===`about`?t:e.level!==`off`).map(({id:e})=>e),yb=e=>{if(typeof e!=`object`||!e)return ab;let{accent:t,theme:n,sections:r}=e;if(!Array.isArray(r)||r.length>ob||!r.every(e=>typeof e==`string`))return ab;let i=lb(n);return{accent:cb(t),...i===`steel`?{}:{theme:i},sections:[...new Set(r)].filter(sb)}},bb=(e,t)=>JSON.stringify(e)===JSON.stringify(t),xb=(e,t,n)=>Z(e,()=>bb(t,n)?{}:{page:t}),Sb=new TextEncoder,Cb=new TextDecoder,wb=Uint8Array.of(0),Tb=Uint8Array.of(1),Eb=(...e)=>{let t=e.map(e=>typeof e==`string`?Sb.encode(e):e),n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),r=0;for(let e of t)n.set(e,r),r+=e.length;return n},Db=(e,...t)=>ty(Yd,e,Eb(...t)),Ob=e=>Math.max(8,2**Math.ceil(Math.log2(Math.max(1,e)))),kb=e=>ay(Yd,e.dhSeed,void 0,Sb.encode(Iy),32),Ab=(e,t,n)=>Db(e,`k`,t,wb,n),jb=(e,t,n)=>{try{return ay(Yd,$v.getSharedSecret(e,t),Sb.encode(n),Sb.encode(Ly),32)}catch{return null}},Mb=e=>e.map(Y).sort().join(`\0`),Nb=(e,t,n,r)=>{let i=kb(e),a=Sb.encode(Mb(n)),o=Db(i,`e`,[...r].sort().join(`\0`),Tb,a).slice(0,16),s=n.map(n=>jb(e.dhSeed,n,t)).filter(e=>e!==null);return{e:o,key:Ab(i,t,o),secret:i,members:a,slots:s}},Pb=e=>({displayName:e.displayName,bio:e.bio,links:e.links,...e.avatar==null?{}:{avatar:{url:e.avatar.url,key:e.avatar.key}},...e.background==null?{}:{background:{url:e.background.url,key:e.background.key}}}),Fb=e=>JSON.stringify({profile:e.profile===null?null:Pb(e.profile),sections:e.sections,feed:e.feed.map(Ih),...e.favourites===void 0||e.favourites.length===0?{}:{favourites:e.favourites.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...e.comments===void 0||e.comments.length===0?{}:{comments:e.comments.map(dy)},...e.panels===void 0||e.panels.length===0?{}:{panels:e.panels.map(xm)},...e.panelOrder===void 0||e.panelOrder.length===0?{}:{panelOrder:e.panelOrder},...e.chatRoom==null?{}:{chatRoom:e.chatRoom}}),Ib=(e,t,n,r)=>{let i=Sb.encode(Fb(n)),a=Db(e.key,`z`,r,wb,i,wb,e.members).slice(0,16),o=Hg(e.key,Db(e.key,`c`,a).slice(0,24),Eb(t.roomId,wb,t.owner)).encrypt(i),s=e.slots.map(t=>({i:Y(Db(t,`i`,a).slice(0,16)),w:Y(Hg(t,Db(t,`w`,a).slice(0,24)).encrypt(e.key))}));for(let t=s.length;t<Ob(e.slots.length);t++){let n=ay(Yd,e.secret,a,Eb(`p`,String(t)),64);s.push({i:Y(n.slice(0,16)),w:Y(n.slice(16))})}return{e:Y(e.e),z:Y(a),c:Y(o),s:s.sort((e,t)=>e.i<t.i?-1:+(e.i>t.i))}},Lb=(e,t)=>{let n=`A`.repeat(22);return{e:n,z:n,c:`A`.repeat(Math.ceil((Sb.encode(Fb(t)).length+16)*4/3)),s:Array.from({length:Ob(e.slots.length)},()=>({i:n,w:`A`.repeat(64)}))}},Rb=/^[A-Za-z0-9_-]{22}$/,zb=/^[A-Za-z0-9_-]{64}$/,Bb=e=>{if(typeof e!=`object`||!e)return null;let{e:t,z:n,c:r,s:i}=e;if(typeof t!=`string`||!Rb.test(t)||typeof n!=`string`||!Rb.test(n)||typeof r!=`string`||r===``||X(r)===null||!Array.isArray(i)||i.length>4096)return null;let a=[];for(let e of i){let{i:t,w:n}=e??{};if(typeof t!=`string`||!Rb.test(t)||typeof n!=`string`||!zb.test(n))return null;a.push({i:t,w:n})}return{e:t,z:n,c:r,s:a}},Vb=e=>{let t;try{t=JSON.parse(Cb.decode(e))}catch{return null}if(typeof t!=`object`||!t)return null;let{profile:n,sections:r,feed:i,favourites:a,comments:o,panels:s,panelOrder:c,chatRoom:l}=t,u=typeof n==`object`&&n?n:null,d=u===null?null:Ef({displayName:u.displayName,bio:u.bio,links:u.links,version:0}),f=u?.avatar===void 0?null:yf(u.avatar)??null,p=u?.background===void 0?null:yf(u.background)??null,m=Array.isArray(r)?[...new Set(r)].filter(e=>typeof e==`string`&&Object.hasOwn(nb,e)):[],h=Cm(s),g=wm(c),_=Ky(l);return{profile:d===null?null:{displayName:d.displayName,bio:d.bio,links:d.links,...f===null?{}:{avatar:f},...p===null?{}:{background:p}},sections:m,feed:Bh(i),favourites:xy(a),comments:my(o),...h.length>0?{panels:h}:{},...g.length>0?{panelOrder:g}:{},..._===null?{}:{chatRoom:_}}},Hb=(e,t,n)=>{let r=X(n.z);try{return Vb(Hg(e,Db(e,`c`,r).slice(0,24),Eb(t.roomId,wb,t.owner)).decrypt(X(n.c)))}catch{return null}},Ub=(e,t,n)=>Hb(Ab(kb(e),t.roomId,X(n.e)),t,n),Wb=(e,t,n,r)=>{let i=jb(e.dhSeed,t,n.roomId);if(i===null)return null;let a=X(r.z),o=Y(Db(i,`i`,a).slice(0,16)),s=r.s.find(e=>e.i===o);if(s===void 0)return null;try{return Hb(Hg(i,Db(i,`w`,a).slice(0,24)).decrypt(X(s.w)),n,r)}catch{return null}},Gb=new TextEncoder,Kb={version:0,profile:null,inbox:null},qb=e=>Y(Yd(Gb.encode(`${Ny}\u0000${e}`))),Jb=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);if(n.length!==32)throw Error(`social: a public key is 32 bytes`);let r=Gb.encode(`${jy}\u0000${e}\u0000${t}\u0000`),i=new Uint8Array(r.length+32);return i.set(r),i.set(n,r.length),i},Yb=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return Gb.encode(`${My}\u0000${e}\u0000${t}\u0000${n}`)},Xb=(e,t,n,r={})=>{let{profile:i,inbox:a,displayName:o,pageRoom:s,page:c,favourites:l,panels:u}=t,{feed:d,comments:f,friends:p}=r;return JSON.stringify({k:Y(n.signKey),n:e,version:t.version,profile:i===null?null:{displayName:i.displayName,bio:i.bio,links:i.links,avatar:i.avatar,background:i.background},...a==null?{}:{inbox:{invite:a,dhKey:Y(n.dhKey)}},...o?{displayName:o}:{},...s==null?{}:{pageRoom:s},...c==null?{}:{page:{accent:c.accent,...c.theme===void 0?{}:{theme:c.theme},sections:c.sections}},...d===void 0||d.length===0?{}:{feed:d.map(Ih)},...l===void 0||l.length===0?{}:{favourites:l.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...f===void 0||f.length===0?{}:{comments:f.map(dy)},...u===void 0||u.length===0?{}:{panels:u.map(xm)},...p===void 0?{}:{friends:{e:p.e,z:p.z,c:p.c,s:p.s.map(({i:e,w:t})=>({i:e,w:t}))}}})},Zb=(e,t)=>({t:`social.name`,v:2,b:e,s:t}),Qb=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},$b=(e,t,n)=>{try{return Qv.verify(e,t(),n,{zip215:!1})}catch{return!1}},ex=e=>{if(e==null)return null;if(typeof e!=`object`)return;let{invite:t,dhKey:n}=e,r=Ky(t),i=typeof n==`string`?X(n):null;return r!==null&&i?.length===32?{invite:r,dhKey:i}:void 0},tx=(e,t)=>{if(e===null)return null;if(typeof e!=`object`)return;let{displayName:n,bio:r,links:i,avatar:a,background:o}=e,s=Ef({displayName:n,bio:r,links:i,version:t}),[c,l]=[yf(a),yf(o)];if(s!==null&&c!==void 0&&l!==void 0)return{displayName:s.displayName,bio:s.bio,links:s.links,avatar:c,background:l}},nx=(e,t,n)=>{let{n:r,k:i,s:a}=e;if(r!==n||typeof i!=`string`||typeof a!=`string`)return null;let o=X(i),s=X(a);return o?.length!==32||s?.length!==64?null:$b(s,()=>Jb(t,n,o),o)?{signKey:o,version:null,profile:null,inbox:null,page:ab,feed:[],favourites:[],comments:[],friends:null}:null},rx=(e,t,n,r)=>{let i=Qb(e);if(i===null||i.t!==`social.name`||!sf(r))return null;if(i.v===1)return nx(i,t,r);let{v:a,b:o,s}=i;if(a!==2||typeof o!=`string`||typeof s!=`string`||Gb.encode(o).length>131072)return null;let c=Qb(o);if(c===null||typeof c.k!=`string`||c.n!==r)return null;let l=X(c.k),u=X(s);if(l?.length!==32||u?.length!==64||!$b(u,()=>Yb(t,n,o),l))return null;let{version:d}=c;if(typeof d!=`number`||!Number.isSafeInteger(d)||d<0)return null;let f=tx(c.profile,d),p=ex(c.inbox);if(f===void 0||p===void 0)return null;let m=c.pageRoom,h=m==null?void 0:Ky(m);if(h===null)return null;let g=c.displayName,_;if(g!==void 0){if(typeof g!=`string`||g.trim().length===0||hf(g,{max:32,multiline:!1})!==null)return null;_=g}let v=Cm(c.panels);return{signKey:l,version:d,profile:f,inbox:p,..._===void 0?{}:{displayName:_},...h===void 0?{}:{pageRoom:h},page:yb(c.page),feed:Bh(c.feed),favourites:xy(c.favourites),comments:my(c.comments),...v.length>0?{panels:v}:{},friends:Bb(c.friends)}},ix=new TextEncoder,ax=(e,t,n)=>{if(e.includes(`\0`)||t.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return ix.encode(`${Ry}\u0000${e}\u0000${t}\u0000${n}`)},ox=(e,t,n={})=>{let{profile:r,page:i,favourites:a,panels:o}=e,{feed:s,comments:c,friends:l}=n;return JSON.stringify({k:Y(t.signKey),version:e.version,profile:r===null?null:{displayName:r.displayName,bio:r.bio,links:r.links,avatar:r.avatar,background:r.background},...i==null?{}:{page:{accent:i.accent,...i.theme===void 0?{}:{theme:i.theme},sections:i.sections}},...s===void 0||s.length===0?{}:{feed:s.map(Ih)},...a===void 0||a.length===0?{}:{favourites:a.map(({title:e,link:t,image:n})=>n===void 0?{title:e,link:t}:{title:e,link:t,image:n})},...c===void 0||c.length===0?{}:{comments:c.map(dy)},...o===void 0||o.length===0?{}:{panels:o.map(xm)},...l===void 0?{}:{friends:{e:l.e,z:l.z,c:l.c,s:l.s.map(({i:e,w:t})=>({i:e,w:t}))}}})},sx=(e,t)=>({t:`social.page`,v:1,b:e,s:t}),cx=(e,t,n)=>{let r=Qb(e);if(r===null||r.t!==`social.page`)return null;let{v:i,b:a,s:o}=r;if(i!==1||typeof a!=`string`||typeof o!=`string`||ix.encode(a).length>131072)return null;let s=Qb(a);if(s===null||typeof s.k!=`string`)return null;let c=X(s.k),l=X(o);if(c?.length!==32||l?.length!==64||!$b(l,()=>ax(t,n,a),c))return null;let{version:u}=s;if(typeof u!=`number`||!Number.isSafeInteger(u)||u<0)return null;let d=tx(s.profile,u);if(d===void 0)return null;let f=Cm(s.panels);return{signKey:c,version:u,profile:d,page:s.page===void 0?ab:yb(s.page),feed:Bh(s.feed),favourites:xy(s.favourites),comments:my(s.comments),...f.length>0?{panels:f}:{},friends:Bb(s.friends)}},lx=e=>new TextEncoder().encode(e),ux=()=>crypto.getRandomValues(new Uint8Array(32)),dx=e=>{if(e.length!==32)throw Error(`social: a seed is 32 bytes`);let t=ay(Yd,e,void 0,lx(wy),32),n=ay(Yd,e,void 0,lx(Ty),32);return{signSeed:t,signKey:Qv.getPublicKey(t),dhSeed:n,dhKey:$v.getPublicKey(n)}},fx=1e4,px=(e,t,n=fx,r=!1)=>e()?Promise.resolve():new Promise((i,a)=>{let o,s=()=>{t(()=>{}),clearTimeout(c),o!==void 0&&clearTimeout(o),i()},c=setTimeout(()=>{t(()=>{}),o!==void 0&&clearTimeout(o),a(Error(`social: the room did not answer in time`))},n);t(()=>{if(e()){if(!r){s();return}o===void 0&&(o=setTimeout(s,0))}})}),mx=async(e,t,n)=>{let r={},i=()=>{},a=await e.on(n=>{n.type===`message`&&n.message.from===e.self.id&&n.message.text===t&&(r.seq??=n.message.seq,i())});try{await e.send(t,n),await px(()=>r.seq!==void 0,e=>{i=e})}finally{a()}let o=r.seq,s=(t,n)=>e.delete(t,n).catch(()=>{});o>1&&await s(1,o-1),await s(o+1,2**53-1)},hx=async e=>{let t=new Map,n=()=>{},r=await e.on(e=>{e.type===`message`&&(t.set(e.message.seq,{seq:e.message.seq,from:e.message.from,text:e.message.text,type:e.message.envelope?.type??null}),n())});try{let r=null,[i,a]=await Promise.all([e.usage(),e.backlog(0,2).catch(e=>(r=e,null))]);if(i?.messages!==1)return null;if(a===null)throw r??Error(`social: backlog failed`);if(a.last===0||a.more)return null;await px(()=>t.has(a.last),e=>{n=e},fx,!0)}finally{r()}let i=[...t.values()];return i.length===1?i[0]:null},gx=async e=>(await hx(e))?.text??null,_x=e=>({type:`object`,properties:{type:{type:`string`,const:e}},required:[`type`],additionalProperties:!1}),vx={type:`page`},yx={type:`record`},bx={type:`request`},xx={type:`chat`},Sx={version:2,types:{page:{envelope:_x(`page`),send:`owner`,maxBytes:262144}}},Cx={version:1,types:{request:{envelope:_x(`request`),send:`accounts`,maxBytes:65536,perAccount:{messages:16,bytes:131072}}},maxStoredBytes:4e6},wx={version:1,types:{page:{envelope:_x(`page`),send:`owner`,maxBytes:262144}}},Tx={version:1,types:{chat:{envelope:_x(`chat`),send:`accounts`,maxBytes:65536}},maxStoredBytes:5e7},Ex=(e,t)=>e.schema()===null?void 0:t,Dx=e=>{let t=e.schema()?.types;if(t!==void 0)return Object.hasOwn(t,vx.type)?vx:Object.hasOwn(t,yx.type)?yx:void 0},Ox=e=>{let t=e.schema()?.types;return t!==void 0&&Object.hasOwn(t,vx.type)?vx:void 0},kx=async(e,t)=>{(e.schema()?.version??0)<t.version&&await e.setSchema(t).catch(()=>{})},Ax=new TextEncoder,jx=e=>Ax.encode(e).length,Mx=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Nx={profile:null,sections:[],members:[],left:[]},Px=`A`.repeat(86),Fx=(e,t,n,r)=>{if(n===null||!e.claimed||e.owner!==e.self.id)return null;let i=Jy(e.id);for(let a of i){let i=r(n.text,a,e.owner);if(i!==null&&Mx(i.signKey,t.signKey))return{proof:i,owner:e.owner,roomId:a,currentOwner:!0}}if(n.from===e.owner)return null;for(let e of i){let i=r(n.text,e,n.from);if(i!==null&&Mx(i.signKey,t.signKey))return{proof:i,owner:n.from,roomId:e,currentOwner:!1}}return null},Ix=(e,t,n,r=e.owner,i=e.id)=>{let a=n.friends===null?null:Ub(t,{roomId:i,owner:r},n.friends);return{public:n.feed,friends:a?.feed??[],comments:{public:n.comments,friends:a?.comments??[]}}},Lx=(e,t,n,r,i,a,o)=>{let s=n.friends??null,c=s===null?null:Nb(t,e.id,s.members,s.left),l=n.commentsLevel===`public`||n.commentsLevel===`friends`,u=r.comments??oy,[d,f,p,m]=[r.public.slice(0,50),r.friends.slice(0,50),!1,!0],[h,g]=[u.public.slice(0,20),u.friends.slice(0,20)];for(;;){let t=s!==null&&c!==null&&m&&(s.profile!==null||f.length>0||s.favourites!==void 0||(s.panels?.length??0)>0||g.length>0||l||s.chatRoom!==void 0)?p?{profile:null,sections:[],feed:[],comments:[],...s.chatRoom===void 0?{}:{chatRoom:s.chatRoom}}:{profile:s.profile,sections:s.sections,feed:f,favourites:s.favourites,comments:g,...s.panels&&s.panels.length>0?{panels:s.panels}:{},...s.panelOrder&&s.panelOrder.length>0?{panelOrder:s.panelOrder}:{},...s.chatRoom===void 0?{}:{chatRoom:s.chatRoom}}:null,r=i(n,{feed:d,comments:h,friends:c===null||t===null?void 0:Lb(c,t)}),u=a(r,Px);if(jx(r)<=131072&&jx(u)<=196568||d.length+f.length+h.length+g.length===0&&t===null){let r=c===null||t===null?void 0:Ib(c,{roomId:e.id,owner:e.self.id},t,i(n,{feed:d,comments:h})),s=i(n,{feed:d,comments:h,friends:r});return a(s,o(s))}f.length>0?f=f.slice(0,-1):g.length>0?g=g.slice(0,-1):!p&&t!==null&&s?.chatRoom!==void 0?p=!0:t===null?d.length>0?d=d.slice(0,-1):h=h.slice(0,-1):m=!1}},Rx=async(e,t,n,r,i)=>{for(let a=0;a<2;a++){let a=await hx(e),o=Fx(e,t,a,r.read);if(o!==null&&o.currentOwner&&(o.proof.version??-1)>n.version)return`newer`;let s=r.prepare?r.prepare(o,n):n,c=r.emptyFeeds?.(s)||o===null?Dh:Ix(e,t,o.proof,o.owner,o.roomId),l=i?.(c)??c,u=n.activity===void 0?l:qh(l,n.activity),d=n.commentsLevel===void 0?u:yy(u,n.commentsLevel),f=s.friends==null&&(d.friends.length>0||(d.comments?.friends.length??0)>0)?{...s,friends:Nx}:s,p=r.fit(f,d);if(a?.text===p)return`written`;let m=r.envelope();if(a!==null&&m===vx&&a.type===vx.type&&a.from===e.self.id?await e.edit(a.seq,p,m):await mx(e,p,m),(await hx(e))?.text===p)return`written`}return`failed`},zx=`Your name and public page on FKN Social. Unclaiming it takes your page down and frees the name.`,Bx=e=>e?.code,Vx=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`]),Hx=(e,t)=>e.open(t,{key:qb(t),defaults:{send:!1,receive:!0}}),Ux=async e=>{e.defaults().send&&await e.setDefault(`send`,!1).catch(()=>{}),await kx(e,Sx)},Wx=(e,t)=>{let n=Bx(e);return n===`bad-key`||n===`denied`?`taken`:n===`full`?t===`open`?`busy`:`out-of-claims`:`unavailable`},Gx=(e,t,n,r)=>{for(let i of Jy(t)){let t=rx(e,i,n,r);if(t!==null)return{proof:t,roomId:i}}return null},Kx=(e,t,n)=>{for(let r of Jy(t)){let t=cx(e,r,n);if(t!==null)return{proof:t,roomId:r}}return null},qx=async(e,t)=>{let n=await gx(e);return n===null?null:Gx(n,e.id,e.owner,t)?.proof??null},Jx=async(e,t,n)=>{let r=await qx(e,t);return r!==null&&Mx(r.signKey,n)},Yx=(e,t,n,r,i=`none`)=>Rx(e,t.keys,n,{read:(e,n,r)=>rx(e,n,r,t.name),prepare:(e,n)=>{if(i===`none`||e===null)return n;let r=e.proof.inbox!==null&&Mx(e.proof.inbox.dhKey,t.keys.dhKey)?e.proof.inbox.invite:null;return{...n,inbox:r,...i===`all`&&e.proof.displayName!==void 0?{displayName:e.proof.displayName}:{},...i===`all`&&e.proof.pageRoom!==void 0?{pageRoom:e.proof.pageRoom}:{}}},emptyFeeds:e=>typeof e.pageRoom==`string`,fit:(n,r)=>Lx(e,t.keys,n,r,(e,n)=>Xb(t.name,e,t.keys,n),(e,t)=>JSON.stringify(Zb(e,t??``)),n=>Y(Qv.sign(Yb(e.id,e.self.id,n),t.keys.signSeed))),envelope:()=>Dx(e)},r),Xx=async(e,t,n,r,i)=>{let a;try{a=await Hx(e,n)}catch(e){return{ok:!1,reason:Wx(e,`open`)}}try{try{await a.claim({description:zx})}catch(e){return{ok:!1,reason:Wx(e,`claim`)}}return await Ux(a),await Yx(a,{keys:t,name:n},r??Kb,i,r===void 0?`all`:`none`).catch(()=>`failed`)===`failed`?{ok:!1,reason:`unrecorded`}:{ok:!0}}finally{await a.leave().catch(()=>{})}},Zx=async(e,t)=>{let n;try{n=await Hx(e,t)}catch(e){return Bx(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},Qx=async(e,t,n,r,i)=>{if(!sf(t.name))return`retired`;let a;try{a=await Hx(e,t.name)}catch(e){return Bx(e)===`bad-key`?`taken`:`unknown`}try{if(!a.claimed)return`lost`;if(a.owner!==a.self.id)return`taken`;await Ux(a);let e=await n();if(e===null)return await Jx(a,t.name,t.keys.signKey)?`held`:`unrecorded`;let o=await r(e,async()=>{let e=Fx(a,t.keys,await hx(a),(e,n,r)=>rx(e,n,r,t.name));return e===null?Dh:Ix(a,t.keys,e.proof,e.owner,e.roomId)});if(o===null)return await Jx(a,t.name,t.keys.signKey)?`held`:`unrecorded`;let s=Yx(a,t,o).catch(()=>`failed`);return i?.refreshClaim!==!1&&await a.claim({description:zx}).catch(()=>{}),await s===`failed`?`unrecorded`:`held`}catch{return`unknown`}finally{await a.leave().catch(()=>{})}},$x=async(e,t,n,r)=>{if(!sf(t.name))return`failed`;let i;try{i=await Hx(e,t.name)}catch{return`failed`}try{return!i.claimed||i.owner!==i.self.id?`failed`:await Yx(i,t,n,r,`inbox`)}catch{return`failed`}finally{await i.leave().catch(()=>{})}},eS=async(e,t,n,r,i)=>{let a=!1,o=await $x(e,t,n,e=>(a=Hh(e,r.app,r.at-Eh)>=10,a?e:{...e,[i]:Kh(e[i],r)}));return a?`too-many`:o},tS=async(e,t,n)=>{if(!sf(n))return Dh;let r;try{r=await Hx(e,n)}catch(e){return Vx.has(String(Bx(e)))?Dh:null}try{let e=Fx(r,t,await hx(r),(e,t,r)=>rx(e,t,r,n));return e===null?Dh:Ix(r,t,e.proof,e.owner,e.roomId)}catch{return null}finally{r.leave().catch(()=>{})}},nS=async(e,t)=>{if(!sf(t.name))return{inbox:null,pageRoom:null,chatRoom:null};let n;try{n=await Hx(e,t.name)}catch{return{inbox:null,pageRoom:null,chatRoom:null}}let r=null,i=null,a=null;try{let e=Fx(n,t.keys,await hx(n),(e,n,r)=>rx(e,n,r,t.name));i=e!==null&&e.proof.inbox!==null&&Mx(e.proof.inbox.dhKey,t.keys.dhKey)?e.proof.inbox.invite:null,r=e?.proof.pageRoom??null,e?.proof.friends!=null&&(a=Ub(t.keys,{roomId:e.roomId,owner:e.owner},e.proof.friends)?.chatRoom??null)}catch{return{inbox:null,pageRoom:null,chatRoom:null}}finally{await n.leave().catch(()=>{})}return{inbox:i,pageRoom:r,chatRoom:a}},rS=async(e,t,n)=>{if(e.join===void 0)return null;let r=null;try{r=await e.join(n);let i=await gx(r),a=i===null?null:Kx(i,r.id,r.owner);return a!==null&&Mx(a.proof.signKey,t.keys.signKey)&&a.proof.friends!==null?Ub(t.keys,{roomId:a.roomId,owner:r.owner},a.proof.friends)?.chatRoom??null:null}catch{return null}finally{r!==null&&await r.leave().catch(()=>{})}},iS=async(e,t,n)=>{if(!sf(t))return!1;let r;try{r=await Hx(e,t)}catch(e){return Bx(e)!==`bad-key`&&null}try{return await Jx(r,t,n)}catch{return null}finally{r.leave().catch(()=>{})}},aS=async(e,t)=>{let n;try{n=await Hx(e,t)}catch(e){let t=String(Bx(e));return t===`full`?{view:{kind:`busy`}}:{view:Vx.has(t)?{kind:`none`}:{kind:`unavailable`}}}try{if(!n.claimed)return{view:{kind:`unheld`}};let e=await gx(n),r=e===null?null:Gx(e,n.id,n.owner,t)?.proof??null;if(r===null)return{view:{kind:`none`}};let i={kind:`shown`,signKey:r.signKey,...r.displayName===void 0?{}:{displayName:r.displayName},profile:r.profile,inbox:r.inbox,page:r.page,feed:r.feed,favourites:r.favourites,comments:r.comments,...r.panels===void 0?{}:{panels:r.panels}};return r.pageRoom!==void 0&&e!==null?{view:i,pageRoom:r.pageRoom,coreRecord:{roomId:n.id,owner:n.owner,text:e}}:{view:r.friends===null||e===null?i:{...i,record:{name:t,roomId:n.id,owner:n.owner,text:e}}}}catch{return{view:{kind:`unavailable`}}}finally{n.leave().catch(()=>{})}},oS=async(e,t)=>(await aS(e,t)).view,sS=async(e,t)=>{let n=await aS(e,t);if(n.view.kind!==`shown`||n.pageRoom===void 0)return n.view;if(e.join===void 0)return{kind:`unavailable`};let r;try{r=await e.join(n.pageRoom)}catch(e){let t=String(Bx(e));return t===`full`?{kind:`busy`}:Vx.has(t)?n.view:{kind:`unavailable`}}try{if(!r.claimed)return n.view;let e=await gx(r),i=e===null?null:Kx(e,r.id,r.owner)?.proof??null;if(i===null||!Mx(i.signKey,n.view.signKey))return n.view;let a={...n.view,profile:i.profile,page:i.page,feed:i.feed,favourites:i.favourites,comments:i.comments,...i.panels===void 0?{}:{panels:i.panels}};return i.friends===null||e===null?a:{...a,record:{name:t,roomId:r.id,owner:r.owner,text:e,...n.coreRecord?{core:n.coreRecord}:{}}}}catch{return{kind:`unavailable`}}finally{r.leave().catch(()=>{})}},cS=`FKNS`,lS=e=>{if(e.length!==32)throw Error(`social: a seed is 32 bytes`);return`${cS}-${(Qd(e).match(/.{1,4}/g)??[]).join(`-`)}`},uS=e=>{let t=ef(e),n=t.length===56&&t.startsWith(`FKNS`)?t.slice(4):t;if(n.length!==52||!$d(n))return null;let r=tf(n);return r!==null&&r.length===32?r:null},dS=new TextEncoder,fS=new TextDecoder,pS=e=>dS.encode(e),mS=Uint8Array.of(0),hS=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},gS=(e,t,n)=>ay(Yd,$v.getSharedSecret(e,t),pS(n),pS(ky),32),_S=(e,t,n,r,i)=>{if(n.length!==32)throw Error(`social: a pairing nonce is 32 bytes`);let[a,o]=[r,i].sort(),s=hS([pS(Ay),mS,pS(a),mS,pS(o)]);return ay(Yd,$v.getSharedSecret(e,t),n,s,32)},vS=(e,t,n,r,i,a)=>hS([pS(e),mS,pS(t),mS,pS(n),mS,pS(r),mS,pS(i),mS,Yd(a)]),yS=(e,t)=>{let n=crypto.getRandomValues(new Uint8Array(24));return hS([n,Hg(e,n).encrypt(t)])},bS=(e,t)=>{if(t.length<=24)return null;try{return Hg(e,t.slice(0,24)).decrypt(t.slice(24))}catch{return null}},xS={"social.offer":Dy,"social.accept":Oy},SS=(e,t,n,r)=>{let i=yS(gS(r.dhSeed,r.theirDhKey,n.roomId),pS(JSON.stringify(t)));return{t:e,v:1,to:n.toMemberId,i:n.id,b:Y(i),s:Y(Qv.sign(vS(xS[e],n.roomId,n.fromMemberId,n.toMemberId,n.id,i),r.signSeed))}},CS=(e,t,n)=>SS(`social.offer`,{n:Y(e.nonce),p:e.profile,x:e.inbox,...e.chatRoom==null?{}:{m:e.chatRoom}},t,n),wS=(e,t,n)=>SS(`social.accept`,{o:e.offerId,p:e.profile,x:e.inbox,...e.chatRoom==null?{}:{m:e.chatRoom}},t,n),TS=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return(t.t===`social.offer`||t.t===`social.accept`)&&t.v===1&&typeof t.to==`string`&&typeof t.i==`string`&&typeof t.b==`string`&&typeof t.s==`string`},ES=(e,t,n,r)=>{if(!TS(t)||t.t!==e)return{ok:!1,reason:`malformed`};if(t.to!==n.selfMemberId)return{ok:!1,reason:`not-for-me`};let i=X(t.b),a=X(t.s);if(!i||!a||a.length!==64)return{ok:!1,reason:`malformed`};let o=vS(xS[e],n.roomId,n.fromMemberId,n.selfMemberId,t.i,i);try{if(!Qv.verify(a,o,r.theirSignKey,{zip215:!1}))return{ok:!1,reason:`bad-signature`}}catch{return{ok:!1,reason:`bad-signature`}}let s=bS(gS(r.dhSeed,r.theirDhKey,n.roomId),i);if(!s)return{ok:!1,reason:`unsealed`};if(s.length>16384)return{ok:!1,reason:`malformed`};try{let e=JSON.parse(fS.decode(s));return typeof e!=`object`||!e?{ok:!1,reason:`malformed`}:{ok:!0,id:t.i,body:e}}catch{return{ok:!1,reason:`malformed`}}},DS=e=>e==null?null:Ky(e)??void 0,OS=(e,t,n)=>{let r=ES(`social.offer`,e,t,n);if(!r.ok)return r;let i=typeof r.body.n==`string`?X(r.body.n):null,a=Ef(r.body.p),o=DS(r.body.x),s=DS(r.body.m);return i?.length!==32||a===null||o===void 0||s===void 0?{ok:!1,reason:`malformed`}:{ok:!0,id:r.id,body:{nonce:i,profile:a,inbox:o,...s===null?{}:{chatRoom:s}}}},kS=(e,t,n)=>{let r=ES(`social.accept`,e,t,n);if(!r.ok)return r;let i=Ef(r.body.p),a=DS(r.body.x),o=DS(r.body.m);return typeof r.body.o!=`string`||i===null||a===void 0||o===void 0?{ok:!1,reason:`malformed`}:{ok:!0,body:{offerId:r.body.o,profile:i,inbox:a,...o===null?{}:{chatRoom:o}}}},AS=(e,t)=>`${e}/${t}`,jS=/^[A-Za-z0-9_-]{8,64}$/,MS=new Set([`general`,`panels`,`layout`,`visibility`]),NS=200,PS=e=>{if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||e.includes(`\0`))return null;let t=e===`/`?`/`:e.replace(/\/+$/,``);if(t===`/`)return{tab:`overview`};let n=t.slice(1).split(`/`);if(n.some(e=>e===``))return null;let[r,i,a]=n;if(n.length===1)switch(r){case`overview`:return{tab:`overview`};case`customize`:return{tab:`customize`,customizeTab:`general`};case`friends`:return{tab:`friends`};case`messages`:return{tab:`messages`};case`inbox`:return{tab:`inbox`};case`apps`:return{tab:`apps`};case`account`:return{tab:`account`};default:return null}if(n.length===2){if(r===`customize`&&i!==void 0&&MS.has(i))return{tab:`customize`,customizeTab:i};if(r===`friends`&&i!==void 0){let e=of(i);return e.ok?{tab:`friends`,friendName:e.name}:null}if(r===`messages`&&i!==void 0){let e=of(i);return e.ok?{tab:`messages`,peerName:e.name}:null}return null}return n.length===3&&r===`messages`&&i===`group`&&a!==void 0&&jS.test(a)?{tab:`messages`,groupId:a}:null},FS=e=>{switch(e.tab){case`overview`:return`/overview`;case`customize`:return`/customize/${e.customizeTab}`;case`friends`:return e.friendName?`/friends/${e.friendName}`:`/friends`;case`messages`:return e.groupId?`/messages/group/${e.groupId}`:e.peerName?`/messages/${e.peerName}`:`/messages`;case`inbox`:return`/inbox`;case`apps`:return`/apps`;case`account`:return`/account`}},IS=e=>typeof e==`string`&&e.length>0&&e.length<=NS&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&PS(e)!==null,LS=new TextEncoder,RS=new TextDecoder,zS=e=>LS.encode(e),BS=Uint8Array.of(0),VS=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},HS=(e,t)=>{let n=typeof e==`string`?X(e):null;return n===null?null:t===void 0||n.length===t?n:null},US=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},WS=4e3,GS=/^[A-Za-z0-9_-]{16,64}$/,KS=/^[A-Za-z0-9_-]{22}$/,qS=e=>{let t=e.replace(/\r\n?/g,`
11
+ `).normalize(`NFC`);return t.trim().length===0?null:hf(t,{max:4e3,multiline:!0})===null?t:null},JS=e=>{let t=e.normalize(`NFC`).trim();return t.length===0?null:hf(t,{max:80,multiline:!1})===null?t:null},YS=(e,t)=>{let n=HS(t.signKey,32),r=HS(t.dhKey,32),i=HS(t.pairNonce,32);if(n===null||r===null||i===null)return null;try{return _S(e.dhSeed,r,i,cf(e.signKey),cf(n))}catch{return null}},XS=e=>Y(ty(Yd,e,zS(`${zy}\u0000id`)).slice(0,16)),ZS=(e,t)=>ay(Yd,e,zS(t),zS(zy),32),QS=(e,t)=>ay(Yd,e,zS(t),zS(By),32),$S=(e,t)=>ay(Yd,e,zS(t),zS(Hy),32),eC=(e,t,n,r,i)=>{let a=$v.getSharedSecret(e,t);if(a.every(e=>e===0))throw Error(`social: invalid peer agreement key`);let[o,s]=n<r?[n,r]:[r,n];return ay(Yd,a,zS(`${i}\u0000${o}\u0000${s}`),zS(Wy),32)},tC=(e,t,n)=>ay(Yd,e,zS(`${t}\u0000${n}`),zS(Uy),32),nC=(e,t)=>Y(ty(Yd,e,zS(`gk-tag\u0000${t}`)).slice(0,16)),rC=()=>Y(crypto.getRandomValues(new Uint8Array(16))),iC=(e,t,n,r,i)=>{if(e.includes(`\0`)||t.includes(`\0`)||i.includes(`\0`))throw Error(`social: signed chat field may not contain NUL`);return VS([zS(e),BS,zS(t),BS,zS(n),BS,zS(String(r)),BS,zS(i)])},aC=(e,t,n,r,i,a)=>{if(e.includes(`\0`)||t.includes(`\0`)||i.includes(`\0`))throw Error(`social: signed chat field may not contain NUL`);return zS(`${Vy}\u0000${e}\u0000${t}\u0000${n}\u0000${r}\u0000${i}\u0000${a}`)},oC=e=>{let t=e.ep??0,n=JSON.stringify(e.body),r=Y(Qv.sign(aC(e.roomId,e.ch,e.kind,t,e.id,n),e.signSeed)),i=zS(JSON.stringify({b:n,s:r})),a=crypto.getRandomValues(new Uint8Array(24)),o=Hg(e.key,a,iC(e.roomId,e.ch,e.kind,t,e.id)).encrypt(i),s=new Uint8Array(24+o.length);s.set(a),s.set(o,24);let c={t:`social.chat`,v:1,k:e.kind,ch:e.ch,...e.ep===void 0?{}:{ep:e.ep},...e.p===void 0?{}:{p:e.p},i:e.id,b:Y(s)};return JSON.stringify(c)},sC=(e,t,n)=>{let r=X(e.b);if(r===null||r.length<=24)return null;let i=e.ep??0,a;try{a=Hg(n,r.slice(0,24),iC(t,e.ch,e.k,i,e.i)).decrypt(r.slice(24))}catch{return null}let o=US(RS.decode(a));if(o===null||typeof o.b!=`string`||typeof o.s!=`string`)return null;let s=HS(o.s,64),c=US(o.b),l=HS(c?.from,32);if(s===null||c===null||l===null)return null;try{if(!Qv.verify(s,aC(t,e.ch,e.k,i,e.i,o.b),l,{zip215:!1}))return null}catch{return null}return{senderSignKey:l,senderFingerprint:cf(l),body:c}},cC=(e,t,n)=>{for(let r of Jy(t)){let t=sC(e,r,n);if(t!==null)return t}return null},lC=(e,t,n,r,i,a,o=rC())=>{let s=qS(i);if(s===null||!GS.test(o))return null;let c=YS(t,r);if(c===null)return null;let l=XS(c);return oC({roomId:e,kind:`dm`,ch:l,id:o,key:ZS(c,l),signSeed:t.signSeed,body:{from:Y(t.signKey),name:n,body:s,at:a}})},uC=e=>{let t=e.id??rC();if(!GS.test(t)||!jS.test(e.groupId))throw Error(`social: invalid group control frame id`);return oC({roomId:e.roomId,kind:`gk`,ch:e.groupId,ep:e.epoch,p:nC(e.sealKey,e.groupId),id:t,key:e.sealKey,signSeed:e.myKeys.signSeed,body:{from:Y(e.myKeys.signKey),action:e.action,groupId:e.groupId,epoch:e.epoch,title:e.title,members:e.members.map(e=>({signKey:e.signKey,dhKey:e.dhKey,name:e.name,...Ky(e.chatRoom)?{chatRoom:Ky(e.chatRoom)}:{}})),key:e.groupKey===null?``:Y(e.groupKey),at:e.at}})},dC=e=>{let t=qS(e.body),n=e.id??rC();return t===null||!GS.test(n)||!jS.test(e.groupId)?null:oC({roomId:e.roomId,kind:`gm`,ch:e.groupId,ep:e.epoch,id:n,key:tC(e.groupKey,e.groupId,e.epoch),signSeed:e.myKeys.signSeed,body:{from:Y(e.myKeys.signKey),name:e.myName,body:t,at:e.at}})},fC=e=>{let t=US(e);return t===null||t.t!==`social.chat`||t.v!==1||t.k!==`dm`&&t.k!==`gk`&&t.k!==`gm`||typeof t.ch!=`string`||t.ch.length===0||t.ch.length>64||typeof t.i!=`string`||!GS.test(t.i)||typeof t.b!=`string`||t.b.length===0?null:t.k===`dm`?t.ep!==void 0||t.p!==void 0?null:{t:`social.chat`,v:1,k:`dm`,ch:t.ch,i:t.i,b:t.b}:!jS.test(t.ch)||typeof t.ep!=`number`||!Number.isSafeInteger(t.ep)||t.ep<1?null:t.k===`gk`?typeof t.p!=`string`||!KS.test(t.p)?null:{t:`social.chat`,v:1,k:`gk`,ch:t.ch,ep:t.ep,p:t.p,i:t.i,b:t.b}:{t:`social.chat`,v:1,k:`gm`,ch:t.ch,ep:t.ep,i:t.i,b:t.b}},pC=(e,t=!1)=>{if(!Array.isArray(e)||!t&&e.length===0||e.length>32)return null;let n=new Set,r=[];for(let t of e){if(typeof t!=`object`||!t)return null;let{signKey:e,dhKey:i,name:a,chatRoom:o}=t;if(typeof e!=`string`||typeof i!=`string`||typeof a!=`string`||!sf(a))return null;let s=HS(e,32),c=HS(i,32);if(s===null||c===null)return null;let l=o==null?null:Ky(o);if(o!=null&&l===null)return null;let u=cf(s);if(n.has(u))return null;n.add(u),r.push({signKey:e,dhKey:i,name:a,...l===null?{}:{chatRoom:l},fingerprint:u})}return r},mC=(e,t)=>{let n=new Map,r=new Map;for(let i of t){if(i.state!==`active`)continue;let t=HS(i.signKey,32),a=YS(e,i);if(t===null||a===null)continue;let o=XS(a),s={fingerprint:i.fingerprint,name:i.name,signKey:t,secret:a,dmChannel:o,dmKey:ZS(a,o)};n.set(i.fingerprint,s),r.set(o,s)}return{friendsByFp:n,dmByChannel:r}},hC=(e,t,n)=>{let{friendsByFp:r,dmByChannel:i}=mC(e,n);return{myKeys:e,myFingerprint:cf(e.signKey),myName:t,friendsByFp:r,dmByChannel:i,dmMessages:new Map,groups:new Map,pendingDm:new Map,pendingGk:new Map,pendingGm:new Map}},gC=(e,t,n)=>{if(!e.has(t)&&e.size>=64){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let r=e.get(t)??[];r.some(e=>e.seq===n.seq&&e.frame.i===n.frame.i)||(r.push(n),r.length>64&&r.shift(),e.set(t,r))},_C=e=>{for(;e.size>500;){let t=null,n=1/0;for(let[r,i]of e)i.seq<n&&(n=i.seq,t=r);if(t===null)break;e.delete(t)}},vC=e=>{if(typeof e!=`string`)return null;let t=qS(e);return t===e?t:null},yC=(e,t,n)=>{if(t===e.myFingerprint)return e.myName;let r=e.friendsByFp.get(t);return r===void 0?n?.find(e=>e.fingerprint===t)?.name??t.slice(0,8):r.name},bC=e=>e.reduce((e,t)=>t.controlId<e.controlId?t:e).key,xC=(e,t)=>{for(;e.size>64;){let n=e.keys().next().value;if(n===void 0||n===t)break;e.delete(n)}},SC=(e,t)=>{let n=new Map(e.members.map(e=>[e.fingerprint,e])),r=[];for(let e of t){let t=n.get(e.fingerprint);if(t!==void 0){if(e.signKey!==t.signKey||e.dhKey!==t.dhKey)return null;r.push(t)}else r.push(e)}return r},CC=(e,t,n,r)=>{let i=e.dmByChannel.get(n.ch);if(i===void 0)return`defer`;let a=cC(n,r,i.dmKey);if(a===null)return`drop`;let{senderFingerprint:o,body:s}=a;if(o!==e.myFingerprint&&o!==i.fingerprint)return`drop`;let c=vC(s.body);if(c===null||typeof s.name!=`string`||!sf(s.name)||typeof s.at!=`number`||!Number.isSafeInteger(s.at)||s.at<0)return`drop`;let l=e.dmMessages.get(i.fingerprint);l===void 0&&(l=new Map,e.dmMessages.set(i.fingerprint,l));let u=l.get(n.i);return u===void 0?(l.set(n.i,{id:n.i,seq:t,conversationId:i.fingerprint,senderFingerprint:o,senderName:o===e.myFingerprint?e.myName:i.name,body:c,at:s.at,self:o===e.myFingerprint}),_C(l),`applied`):t<u.seq?(l.set(n.i,{...u,seq:t}),`applied`):`drop`},wC=(e,t)=>{let{friendsByFp:n,dmByChannel:r}=mC(e.myKeys,t);e.friendsByFp=n,e.dmByChannel=r;let i=!1;for(let[t,n]of e.pendingDm)if(e.dmByChannel.has(t)){e.pendingDm.delete(t);for(let t of[...n].sort((e,t)=>e.seq-t.seq))CC(e,t.seq,t.frame,t.roomId)===`applied`&&(i=!0)}return i},TC=(e,t,n,r)=>{let i=n.ch,a=n.ep??0;if(a<1||a>1e6)return`drop`;let o=n.p??``,s=null,c=null,l=null,u=QS(e.myKeys.dhSeed,i);if(nC(u,i)===o&&(s=u,c=`self`,l=e.myFingerprint),s===null)for(let t of e.friendsByFp.values()){let e=$S(t.secret,i);if(nC(e,i)===o){s=e,c=`friend`,l=t.fingerprint;break}}let d=e.groups.get(i);if(s===null&&d!==void 0)for(let t of d.members){if(t.fingerprint===e.myFingerprint)continue;let n=HS(t.dhKey,32);if(n!==null)try{let r=eC(e.myKeys.dhSeed,n,e.myFingerprint,t.fingerprint,i);if(nC(r,i)===o){s=r,c=`member`,l=t.fingerprint;break}}catch{continue}}if(s===null||c===null||l===null)return d===void 0?`defer`:`drop`;let f=cC(n,r,s);if(f===null)return`drop`;let{senderFingerprint:p,body:m}=f;if(p!==l)return`drop`;let h=m.action;if(h!==`create`&&h!==`add`&&h!==`leave`&&h!==`rekey`||m.groupId!==i||m.epoch!==a||typeof m.at!=`number`||!Number.isSafeInteger(m.at)||m.at<0)return`drop`;let g=typeof m.title==`string`?JS(m.title):null,_=pC(m.members,h===`leave`);if(g===null||g!==m.title||_===null)return`drop`;let v=new Set(_.map(e=>e.fingerprint)),y=v.has(e.myFingerprint),b=v.has(p);if(d===void 0){if(h===`rekey`)return`defer`;if(h===`create`){if(a!==1||!b||!y||_.length<2)return`drop`;let t=HS(m.key,32);if(t===null)return`drop`;let r=new Map;return r.set(1,[{key:t,members:v,controlId:n.i}]),e.groups.set(i,{id:i,title:g,epoch:1,members:_,active:!0,key:t,epochKeys:r,messagesById:new Map,createdAt:m.at}),`applied`}if(h===`add`){if(c!==`friend`&&c!==`self`||a<2||!b||!y||_.length<2)return`drop`;let t=HS(m.key,32);if(t===null)return`drop`;let r=new Map;return r.set(a,[{key:t,members:v,controlId:n.i}]),e.groups.set(i,{id:i,title:g,epoch:a,members:_,active:!0,key:t,epochKeys:r,messagesById:new Map,createdAt:m.at}),`applied`}return p!==e.myFingerprint||y||m.key!==``?`drop`:(e.groups.set(i,{id:i,title:g,epoch:a,members:_,active:!1,key:null,epochKeys:new Map,messagesById:new Map,createdAt:m.at}),`applied`)}if(!d.active){if(h!==`add`||c!==`friend`&&c!==`self`||a<=d.epoch||!b||!y||_.length<2||g!==d.title)return`drop`;let e=SC(d,_),t=HS(m.key,32);return e===null||t===null?`drop`:(d.epoch=a,d.members=e,d.active=!0,d.key=t,d.epochKeys.set(a,[{key:t,members:v,controlId:n.i}]),xC(d.epochKeys,a),`applied`)}let x=new Set(d.members.map(e=>e.fingerprint));if(!x.has(p)||g!==d.title)return`drop`;let S=SC(d,_);if(S===null||a<d.epoch)return`drop`;if(a>d.epoch+1)return a<=d.epoch+16?`defer`:`drop`;if(a===d.epoch){if(h!==`rekey`||!b||!y||_.length!==d.members.length||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let e=HS(m.key,32);if(e===null)return`drop`;let t=d.epochKeys.get(a)??[];if(t.some(e=>e.controlId===n.i)||t.length>=4)return`drop`;let r=[...t,{key:e,members:v,controlId:n.i}];return d.epochKeys.set(a,r),d.key=bC(r),`applied`}if(h===`add`){if(!b||!y||_.length!==d.members.length+1||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let e=HS(m.key,32);return e===null?`drop`:(d.epoch=a,d.members=S,d.active=!0,d.key=e,d.epochKeys.set(a,[{key:e,members:v,controlId:n.i}]),xC(d.epochKeys,a),`applied`)}if(h===`leave`)return b||m.key!==``||_.length!==d.members.length-1||!S.every(e=>x.has(e.fingerprint))?`drop`:(d.epoch=a,d.members=S,d.active=y,d.key=null,`applied`);if(h!==`rekey`||!b||!y||_.length!==d.members.length||!d.members.every(e=>v.has(e.fingerprint)))return`drop`;let C=HS(m.key,32);return C===null?`drop`:(d.epoch=a,d.members=S,d.active=!0,d.key=C,d.epochKeys.set(a,[{key:C,members:v,controlId:n.i}]),xC(d.epochKeys,a),`applied`)},EC=(e,t,n,r)=>{let i=e.groups.get(n.ch),a=n.ep??0,o=i?.epochKeys.get(a);if(i===void 0||o===void 0||o.length===0)return`defer`;for(let s of o){let o=cC(n,r,tC(s.key,i.id,a));if(o===null)continue;let{senderFingerprint:c,body:l}=o;if(c!==e.myFingerprint&&!s.members.has(c))continue;let u=vC(l.body);if(u===null||typeof l.name!=`string`||!sf(l.name)||typeof l.at!=`number`||!Number.isSafeInteger(l.at)||l.at<0)return`drop`;let d=i.messagesById.get(n.i);return d===void 0?(i.messagesById.set(n.i,{id:n.i,seq:t,conversationId:i.id,senderFingerprint:c,senderName:yC(e,c,i.members),body:u,at:l.at,self:c===e.myFingerprint}),_C(i.messagesById),`applied`):t<d.seq?(i.messagesById.set(n.i,{...d,seq:t}),`applied`):`drop`}return`drop`},DC=(e,t)=>{let n=!1;for(let r=!0;r;){r=!1;let i=e.pendingGk.get(t);if(i!==void 0&&i.length>0){let a=[],o=[...i].sort((e,t)=>(e.frame.ep??0)-(t.frame.ep??0)||e.seq-t.seq);for(let t of o){let i=TC(e,t.seq,t.frame,t.roomId);i===`applied`?(n=!0,r=!0):i===`defer`&&a.push(t)}a.length===0?e.pendingGk.delete(t):e.pendingGk.set(t,a)}}let r=e.pendingGm.get(t);if(r!==void 0&&r.length>0){let i=[];for(let t of[...r].sort((e,t)=>e.seq-t.seq)){let r=EC(e,t.seq,t.frame,t.roomId);r===`applied`?n=!0:r===`defer`&&i.push(t)}i.length===0?e.pendingGm.delete(t):e.pendingGm.set(t,i)}return n},OC=(e,t,n,r)=>{let i=fC(n);if(i===null)return!1;if(i.k===`dm`){let n=CC(e,t,i,r);return n===`applied`||(n===`defer`&&gC(e.pendingDm,i.ch,{seq:t,roomId:r,frame:i}),!1)}if(i.k===`gk`){let n=TC(e,t,i,r);return n===`applied`?(DC(e,i.ch),!0):(n===`defer`&&gC(e.pendingGk,i.ch,{seq:t,roomId:r,frame:i}),!1)}let a=EC(e,t,i,r);return a===`applied`||(a===`defer`&&gC(e.pendingGm,i.ch,{seq:t,roomId:r,frame:i}),!1)},kC=(e,t,n)=>{let r=!1;for(let i of e.dmMessages.values())for(let[e,a]of i)a.seq>=t&&a.seq<=n&&(i.delete(e),r=!0);for(let i of e.groups.values())for(let[e,a]of i.messagesById)a.seq>=t&&a.seq<=n&&(i.messagesById.delete(e),r=!0);return r},AC=e=>e===void 0||e.size===0?[]:[...e.values()].sort((e,t)=>e.seq-t.seq||e.at-t.at||(e.id<t.id?-1:+(e.id>t.id))),jC=e=>{let t={};for(let[n,r]of e.dmMessages){let i=AC(r).map(t=>({...t,senderName:t.self?e.myName:e.friendsByFp.get(t.senderFingerprint)?.name??t.senderName}));i.length>0&&(t[n]=i)}return{directMessages:t,groups:[...e.groups.values()].map(t=>{let n=t.members.map(n=>({...n,name:yC(e,n.fingerprint,t.members)})),r=AC(t.messagesById).map(t=>({...t,senderName:yC(e,t.senderFingerprint,n)})),i=r.at(-1)?.seq??0;return{id:t.id,title:t.title,epoch:t.epoch,members:n,active:t.active,messages:r,lastSeq:i}}).sort((t,n)=>{let r=t.messages.at(-1)?.at??e.groups.get(t.id)?.createdAt??0;return(n.messages.at(-1)?.at??e.groups.get(n.id)?.createdAt??0)-r||t.id.localeCompare(n.id)})}},MC=`Your encrypted direct and group messages on FKN Social. Unclaiming it deletes stored messages here.`,NC={send:!0,receive:!1,maxMessageBytes:65536},PC=5e3,FC=e=>e?.code,IC=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`,`invalid`]),LC=e=>{let t=e.profile.chatRoom;return t===void 0?void 0:Ky(t.value)},RC=async(e,t)=>{if(t!==void 0){let n=await Z(e,e=>LC(e)===t?{chatRoom:null}:{});if(!n.ok)return n}let n;try{n=await e.rooms.create({defaults:NC,schema:Tx})}catch(e){return{ok:!1,reason:FC(e)===`full`?`busy`:`unavailable`}}try{try{await n.claim({description:MC})}catch(t){if(FC(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>LC(e)===void 0?{chatRoom:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}let t=await Z(e,e=>typeof LC(e)==`string`?{}:{chatRoom:n.invite});return(!t.ok||LC(t.roster)!==n.invite)&&await n.release().catch(()=>{}),t}finally{await n.leave().catch(()=>{})}},zC=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return FC(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},BC=[2e3,5e3,1e4,3e4],VC=(e,t,n,r,i,a)=>{let o=a?.backoffMs??BC,s=a?.sleep??(e=>new Promise(t=>setTimeout(t,e))),c=!1,l=null,u=()=>{},d=r(),f=0,p=hC(t,n,Hf(d)),m=Promise.resolve(),h=e=>{let t=m.then(e,e);return m=t.catch(()=>{}),t},g=async()=>{u(),u=()=>{};let e=l;l=null,e!==null&&await e.leave().catch(()=>{})},_=async t=>{let n=await Z(e,e=>LC(e)===t?{chatRoom:null}:{});n.ok&&(d=n.roster,i.onRoster(n.roster))},v=()=>{i.onUpdate(jC(p))},y=async(t,n)=>{let r;try{r=await e.rooms.join(t)}catch(e){return c?{status:`unavailable`}:FC(e)===`bad-key`?(await _(t),i.onStatus(`none`),{status:`none`,roster:d}):(i.onStatus(`unavailable`),{status:`unavailable`})}if(c)return await r.leave().catch(()=>{}),{status:`unavailable`};l=r;try{if(!r.claimed)return await g(),await _(t),i.onStatus(`none`),{status:`none`,roster:d};if(r.owner!==r.self.id)return await g(),i.onStatus(`taken`),{status:`taken`};if(await kx(r,Tx),c)return await g(),{status:`unavailable`};if(r.mailbox===null)return await g(),i.onStatus(`not-kept`),{status:`not-kept`};let e=!0,a=new Map,o=()=>{};u=await r.on(n=>{if(!(c||l!==r)){if(n.type===`message`)e?(a.set(n.message.seq,n.message.text),o()):(n.message.seq>f&&(f=n.message.seq),h(async()=>{!c&&OC(p,n.message.seq,n.message.text,r.id)&&v()}));else if(n.type===`deleted`){if(e)for(let e of a.keys())e>=n.from&&e<=n.to&&a.delete(e);h(async()=>{!c&&kC(p,n.from,n.to)&&v()})}else n.type===`claim`&&h(async()=>{c||l!==r||(n.claimed?n.owner===r.self.id?n.mailbox||i.onStatus(`not-kept`):(await g(),i.onStatus(`taken`)):(await g(),await _(t),i.onStatus(`none`)))})}});let s=n;for(;!c;){let e=await r.backlog(s);e.last>s&&await px(()=>c||a.has(e.last),e=>{o=e},PC,!0).catch(()=>{});let t=[...a].filter(([t])=>t<=e.last).sort(([e],[t])=>e-t);for(let[e]of t)a.delete(e);if(t.length>0&&await h(async()=>{for(let[e,n]of t)OC(p,e,n,r.id)}),e.last>f&&(f=e.last),!e.more||e.last<=s)break;s=e.last}e=!1,o=()=>{};let m=[...a].sort(([e],[t])=>e-t);for(let[e]of m)e>f&&(f=e);return await h(async()=>{for(let[e,t]of m)OC(p,e,t,r.id)}),c||l!==r?{status:`unavailable`}:(i.onStatus(`ready`),v(),r.closed?.then(e=>{c||l!==r||e.reason===`left`||(u(),u=()=>{},l=null,b(t))}),{status:`ready`,roster:d})}catch{return await g(),i.onStatus(`unavailable`),{status:`unavailable`}}},b=async e=>{for(let t=0;!c;t+=1)if(await s(o[Math.min(t,o.length-1)]??2e3),c||(await y(e,f)).status!==`unavailable`)return};return{ready:(async()=>{d=r();let t=LC(d);if(t===void 0){let n=await RC(e);if(c)return{status:`unavailable`};if(n.roster!==void 0&&(d=n.roster,i.onRoster(n.roster)),!n.ok){let e=n.reason===`out-of-claims`?`out-of-claims`:`unavailable`;return i.onStatus(e),{status:e,roster:n.roster}}t=LC(n.roster)}if(t==null)return i.onStatus(`none`),{status:`none`};let n=await y(t,0);return!c&&n.status===`unavailable`&&b(t),n})(),refreshRoster:e=>{d=e,wC(p,Hf(e)),v()},groupState:e=>p.groups.get(e)??null,leave:async()=>{c=!0,await g()}}},HC=async(e,t,n)=>{let r;try{r=await e.join(t)}catch(e){let t=String(FC(e));return t===`full`?`busy`:IC.has(t)?`closed`:`unavailable`}try{if(r.mailbox===null)return`closed`;let e=n(r.id);return e===null?`unavailable`:(await r.send(e,Ex(r,xx)),`sent`)}catch(e){let t=String(FC(e));return t===`storage`||t===`quota`||t===`full`?`full`:t===`rate-limited`?`busy`:t===`denied`||t===`blocked`?`closed`:`unavailable`}finally{await r.leave().catch(()=>{})}},UC=async e=>{let t=await cp(e);if(!t.ok)return t;let n=LC(t.roster);if(typeof n==`string`)return{ok:!0,invite:n,roster:t.roster};if(n===null)return{ok:!1,reason:`no-room`};let r=await RC(e);if(!r.ok)return{ok:!1,reason:r.reason===`out-of-claims`?`out-of-claims`:`unavailable`};let i=LC(r.roster);return typeof i==`string`?{ok:!0,invite:i,roster:r.roster}:{ok:!1,reason:`no-room`}},WC=async(e,t,n,r)=>{let i=X(n.signKey);if(i===null)return{outcome:`closed`};let a=cf(i),o=Ky(n.chatRoom),s;if(o===null&&(o=await vT(e.rooms,t,n),o!==null)){let t=await gp(e,a,o);t.ok&&(s=t.roster)}if(o===null)return{outcome:`closed`};let c=await HC(e.rooms,o,r);if(c===`closed`){let i=await vT(e.rooms,t,n);if(i!==null&&i!==o){let t=await gp(e,a,i);return t.ok&&(s=t.roster),c=await HC(e.rooms,i,r),{outcome:c,roster:s,resolvedInvite:i}}}return{outcome:c,roster:s,resolvedInvite:o}},GC=async(e,t,n,r,i=Date.now())=>{let a=qS(r);if(a===null)return{ok:!1,reason:`invalid`};let o=await UC(e);if(!o.ok)return o;let s=rC(),c=await WC(e,t.keys,n,e=>lC(e,t.keys,t.name,n,a,i,s));return c.outcome===`closed`?{ok:!1,reason:`no-peer-room`}:c.outcome!==`sent`||await HC(e.rooms,o.invite,e=>lC(e,t.keys,t.name,n,a,i,s))!==`sent`?{ok:!1,reason:`unavailable`}:{ok:!0,roster:c.roster??o.roster}},KC=async(e,t,n,r)=>{let i=X(n.signKey);if(i===null)return null;let a=cf(i),o=r.friends[a]?.value;if(o?.state===`active`){let n=Ky(o.chatRoom)??await vT(e.rooms,t,o);if(n!==null)return n}let s=Ky(n.chatRoom);return s===null?vT(e.rooms,t,n):s},qC=async(e,t,n,r,i)=>{let a=[];for(let o of n){let n=X(o.signKey);if(n===null)return null;let s=cf(n);if(s===i)continue;let c=await KC(e,t,o,r);if(c===null)return null;a.push({member:o,fp:s,invite:c})}return a},JC=async(e,t,n,r,i=Date.now())=>{let a=JS(n);if(a===null||r.length===0)return{ok:!1,reason:`invalid`};let o=await UC(e);if(!o.ok)return o;let s=`grp_${rC()}`,c=crypto.getRandomValues(new Uint8Array(32)),l=[...new Map(r.map(e=>[e.fingerprint,e])).values()].filter(e=>e.fingerprint!==cf(t.keys.signKey));if(l.length===0||l.length+1>32)return{ok:!1,reason:`invalid`};let u=[],d=o.roster;for(let n of l){let r=await KC(e,t.keys,n,d),i=YS(t.keys,n);if(r===null||i===null)return{ok:!1,reason:`no-peer-room`};if(Ky(n.chatRoom)===null){let t=await gp(e,n.fingerprint,r);t.ok&&(d=t.roster)}u.push({friend:n,invite:r,secret:i})}let f=[{signKey:Y(t.keys.signKey),dhKey:Y(t.keys.dhKey),name:t.name,chatRoom:o.invite},...u.map(({friend:e,invite:t})=>({signKey:e.signKey,dhKey:e.dhKey,name:e.name,chatRoom:t}))],p=rC();for(let n of u){let r=$S(n.secret,s),o=await HC(e.rooms,n.invite,e=>uC({roomId:e,myKeys:t.keys,sealKey:r,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p}));if(o===`closed`){let l=await vT(e.rooms,t.keys,n.friend);l!==null&&l!==n.invite&&(o=await HC(e.rooms,l,e=>uC({roomId:e,myKeys:t.keys,sealKey:r,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p})))}if(o!==`sent`)return{ok:!1,reason:o===`closed`?`no-peer-room`:`unavailable`}}let m=QS(t.keys.dhSeed,s);return await HC(e.rooms,o.invite,e=>uC({roomId:e,myKeys:t.keys,sealKey:m,groupId:s,action:`create`,epoch:1,title:a,members:f,groupKey:c,at:i,id:p}))===`sent`?{ok:!0,roster:d,groupId:s}:{ok:!1,reason:`unavailable`}},YC=async e=>{let t=cf(e.me.keys.signKey),n=e.resolvedTargets??await qC(e.services,e.me.keys,e.members,e.roster,t);if(n===null)return{ok:!1,reason:`no-peer-room`};let r=rC(),i=new Map(Hf(e.roster).map(e=>[e.fingerprint,e])),a=n.length===0,o=null;for(let{member:s,fp:c,invite:l}of n){let n=i.get(c),u=n?YS(e.me.keys,n):null,d;if(u!==null)d=$S(u,e.group.id);else{let n=X(s.dhKey);if(n===null)return{ok:!1,reason:`unavailable`};d=eC(e.me.keys.dhSeed,n,t,c,e.group.id)}let f=l,p=await HC(e.services.rooms,f,t=>uC({roomId:t,myKeys:e.me.keys,sealKey:d,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.nextKey,at:e.at,id:r}));if(p===`closed`){let t=await vT(e.services.rooms,e.me.keys,s);t!==null&&t!==f&&(f=t,p=await HC(e.services.rooms,f,t=>uC({roomId:t,myKeys:e.me.keys,sealKey:d,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.nextKey,at:e.at,id:r})))}p===`sent`?a=!0:o===null&&(o=p===`closed`?`no-peer-room`:`unavailable`)}if(a){let t=QS(e.me.keys.dhSeed,e.group.id);await HC(e.services.rooms,e.ownInvite,n=>uC({roomId:n,myKeys:e.me.keys,sealKey:t,groupId:e.group.id,action:e.action,epoch:e.nextEpoch,title:e.group.title,members:e.members,groupKey:e.action===`leave`?null:e.nextKey,at:e.at,id:r}))!==`sent`&&o===null&&(o=`unavailable`)}return o===null?{ok:!0}:{ok:!1,reason:o}},XC=async(e,t,n,r,i=Date.now())=>{let a=qS(r);if(a===null)return{ok:!1,reason:`invalid`};if(!n.active)return{ok:!1,reason:`not-active`};let o=await UC(e);if(!o.ok)return o;let s=cf(t.keys.signKey),c=await qC(e,t.keys,n.members,o.roster,s);if(c===null)return{ok:!1,reason:`no-peer-room`};let l=n.epoch,u=n.key;if(u===null){let r=crypto.getRandomValues(new Uint8Array(32)),a=n.epoch+1,s=n.members.map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}})),d=await YC({services:e,me:t,ownInvite:o.invite,group:n,nextKey:r,nextEpoch:a,action:`rekey`,members:s,roster:o.roster,resolvedTargets:c,at:i});if(!d.ok)return d;l=a,u=r}let d=rC(),f=c.length===0,p=null;for(let{member:r,invite:o}of c){let s=o,c=await HC(e.rooms,s,e=>dC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d}));if(c===`closed`){let o=await vT(e.rooms,t.keys,r);o!==null&&o!==s&&(s=o,c=await HC(e.rooms,s,e=>dC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d})))}c===`sent`?f=!0:p===null&&(p=c===`closed`?`no-peer-room`:`unavailable`)}return f&&await HC(e.rooms,o.invite,e=>dC({roomId:e,myKeys:t.keys,myName:t.name,groupKey:u,groupId:n.id,epoch:l,body:a,at:i,id:d}))!==`sent`&&p===null&&(p=`unavailable`),p===null?{ok:!0,roster:o.roster}:{ok:!1,reason:p}},ZC=async(e,t,n,r,i=Date.now())=>{if(!n.active)return{ok:!1,reason:`not-active`};if(n.members.some(e=>e.fingerprint===r.fingerprint)||n.members.length>=32)return{ok:!1,reason:`invalid`};let a=await UC(e);if(!a.ok)return a;let o=await KC(e,t.keys,r,a.roster);if(o===null)return{ok:!1,reason:`no-peer-room`};let s=crypto.getRandomValues(new Uint8Array(32)),c=[...n.members.map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}})),{signKey:r.signKey,dhKey:r.dhKey,name:r.name,chatRoom:o}],l=await YC({services:e,me:t,ownInvite:a.invite,group:n,nextKey:s,nextEpoch:n.epoch+1,action:`add`,members:c,roster:a.roster,at:i});return l.ok?{ok:!0,roster:a.roster}:l},QC=async(e,t,n,r=Date.now())=>{if(!n.active)return{ok:!1,reason:`not-active`};let i=await UC(e);if(!i.ok)return i;let a=cf(t.keys.signKey),o=n.members.filter(e=>e.fingerprint!==a).map(({signKey:e,dhKey:t,name:n,chatRoom:r})=>({signKey:e,dhKey:t,name:n,...r?{chatRoom:r}:{}}));if(o.length===0){let a=QS(t.keys.dhSeed,n.id);return await HC(e.rooms,i.invite,e=>uC({roomId:e,myKeys:t.keys,sealKey:a,groupId:n.id,action:`leave`,epoch:n.epoch+1,title:n.title,members:[],groupKey:null,at:r}))===`sent`?{ok:!0,roster:i.roster}:{ok:!1,reason:`unavailable`}}let s=await YC({services:e,me:t,ownInvite:i.invite,group:n,nextKey:null,nextEpoch:n.epoch+1,action:`leave`,members:o,roster:i.roster,at:r});return s.ok?{ok:!0,roster:i.roster}:s},$C=new TextEncoder,ew=new TextDecoder,tw=2e3,nw=(e,t)=>{if(e.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);return $C.encode(`${Py}\u0000${e}\u0000${t}`)},rw=(e,t)=>ay(Yd,e,$C.encode(t),$C.encode(Fy),32),iw=(e,t,n,r)=>{let i=JSON.stringify({k:Y(r.signKey),d:Y(r.dhKey),...n}),a=Y(Qv.sign(nw(e,i),r.signSeed)),o=$v.utils.randomSecretKey(),s=crypto.getRandomValues(new Uint8Array(24)),c=Hg(rw($v.getSharedSecret(o,t),e),s).encrypt($C.encode(JSON.stringify({b:i,s:a}))),l=new Uint8Array(24+c.length);return l.set(s),l.set(c,24),JSON.stringify({t:`social.request`,v:1,e:Y($v.getPublicKey(o)),b:Y(l)})},aw=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}},ow=(e,t)=>{let n=typeof e==`string`?X(e):null;return n?.length===t?n:null},sw=(e,t,n,r)=>{let i=ow(n,32),a=typeof r==`string`?X(r):null;if(i===null||a===null||a.length<=24)return null;try{return Hg(rw($v.getSharedSecret(e.dhSeed,i),t),a.slice(0,24)).decrypt(a.slice(24))}catch{return null}},cw=(e,t)=>{if(e.kind===`party`){let n=typeof e.url==`string`?gf(e.url,tw):null;return n!==null&&n===e.url?{...t,kind:`party`,url:n}:null}if(e.kind===`comment`)return ly(e.text)===e.text?{...t,kind:`comment`,text:e.text}:null;if(e.kind!==`friend`&&e.kind!==`accept`)return null;let n=Ef(e.p),r=Ky(e.x),i=e.m===void 0||e.m===null?null:Ky(e.m),a=ow(e.r,32)===null?null:e.r;return n===null||a===null||e.m!==void 0&&e.m!==null&&i===null?null:e.kind===`friend`?r===null?null:{...t,kind:`friend`,p:n,x:r,r:a,...i===null?{}:{m:i}}:r===null&&e.x!==null&&e.x!==void 0?null:{...t,kind:`accept`,p:n,x:r,r:a,...i===null?{}:{m:i}}},lw=(e,t,n)=>{let r=aw(e);if(r===null||r.t!==`social.request`||r.v!==1)return null;let i=sw(n,t,r.e,r.b),a=i===null?null:aw(ew.decode(i));if(a===null||typeof a.b!=`string`||$C.encode(a.b).length>16384)return null;let o=ow(a.s,64),s=aw(a.b),c=ow(s?.k,32);if(s===null||o===null||c===null)return null;try{if(!Qv.verify(o,nw(t,a.b),c,{zip215:!1}))return null}catch{return null}let{name:l,to:u}=s;if(u!==Y(n.signKey)||typeof l!=`string`||!sf(l))return null;let d=ow(s.d,32);if(d===null)return null;let f=cw(s,{k:s.k,d:s.d,name:l,to:u});return f===null?null:{body:f,signKey:c,dhKey:d}},uw=`Your inbox on FKN Social. Unclaiming it deletes the requests waiting there.`,dw={send:!0,receive:!1,maxMessageBytes:65536},fw=5e3,pw=e=>e?.code,mw=e=>X(e),hw=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),gw=e=>{let t=e.profile.inbox;return t===void 0?void 0:Ky(t.value)},_w=async(e,t)=>{if(t!==void 0){let n=await Z(e,e=>gw(e)===t?{inbox:null}:{});if(!n.ok)return n}let n;try{n=await e.rooms.create({defaults:dw,schema:Cx})}catch(e){return{ok:!1,reason:pw(e)===`full`?`busy`:`unavailable`}}try{try{await n.claim({description:uw})}catch(t){if(pw(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>gw(e)===void 0?{inbox:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}let t=await Z(e,e=>typeof gw(e)==`string`?{}:{inbox:n.invite});return(!t.ok||gw(t.roster)!==n.invite)&&await n.release().catch(()=>{}),t}finally{await n.leave().catch(()=>{})}},vw=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return pw(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},yw=(e,t)=>e.friends[cf(t)]?.value.state===`active`,bw=(e,t,n)=>{for(let r of Jy(t)){let t=lw(e,r,n);if(t!==null)return t}return null},xw=[2e3,5e3,1e4,3e4],Sw=(e,t,n,r,i)=>{let a=i?.backoffMs??xw,o=i?.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=null,l=()=>{},u=null,d=n(),f=[],p=new Set,m=new Set,h=0,g=Promise.resolve(),_=e=>{let t=g.then(()=>s?void 0:e(),()=>s?void 0:e());return g=t.catch(()=>{}),t},v=(e,t=e)=>{let n=f.length;return f=f.filter(n=>n.seq<e||n.seq>t),f.length!==n},y=async t=>{let n=c;if(n!==null&&!s)try{n.claimed&&n.owner===n.self.id&&await n.delete(t)}catch{}else u!==null&&await Tw(e.rooms,u,t);!s&&v(t)&&r.onWaiting([...f])},b=async()=>{let e=c,t=l;c=null,l=()=>{},t(),e!==null&&await e.leave().catch(()=>{})},x=async t=>{let n=await Z(e,e=>gw(e)===t?{inbox:null}:{});if(n.ok)return d=n.roster,r.onRoster(n.roster),n.roster},S=async(i,a,o,c)=>{if(s||p.has(i))return;p.add(i),i>h&&(h=i),d=n();let l=bw(a,o.id,t);if(l===null||hw(l.signKey,t.signKey)){await y(i);return}let{body:u,signKey:g,dhKey:_}=l,v={signKey:g,dhKey:_,name:u.name,fingerprint:cf(g),confirmed:null};if(u.kind===`accept`){let t=await Sp(e,{signKey:g,dhKey:_,name:u.name,profile:u.p,pairNonce:mw(u.r),linkedVia:`request`,inbox:u.x,chatRoom:u.m},Date.now());if(!t.outcome.ok){p.delete(i),m.add(i);return}if(m.delete(i),d=t.outcome.roster,r.onRoster(t.outcome.roster),t.applied){let e=t.outcome.roster.friends[v.fingerprint]?.value.name??u.name;r.onAccepted([e])}await y(i)}else if(u.kind===`friend`){let e=f.find(e=>e.kind===`friend`&&e.sender.fingerprint===v.fingerprint);if(e!==void 0){if(e.seq>i){y(i);return}f=f.filter(t=>t!==e),y(e.seq)}f=[...f,{kind:`friend`,inbox:o.invite,seq:i,sender:v,request:u,friend:yw(d,g)}],c&&r.onWaiting([...f])}else if(u.kind===`comment`){let e=d.friends[v.fingerprint]?.value;e?.state===`active`&&mb(d,`comments`)!==`off`?(f.some(e=>e.seq===i)||(f=[...f,{kind:`comment`,inbox:o.invite,seq:i,sender:{...v,name:e.name},text:u.text,id:uy(a)}]),c&&r.onWaiting([...f])):y(i)}else yw(d,g)?(f.some(e=>e.seq===i)||(f=[...f,{kind:`party`,inbox:o.invite,seq:i,sender:v,url:u.url}]),c&&r.onWaiting([...f])):y(i)},C=async(t,n,i)=>{let a;try{a=await e.rooms.join(t)}catch(e){if(s)return{status:`unavailable`,inboxTaken:!1};if(pw(e)===`bad-key`){let e=await x(t);return r.onStatus(`none`),{status:`none`,roster:e,inboxTaken:!1}}return r.onStatus(`unavailable`),{status:`unavailable`,inboxTaken:!1}}if(s)return await a.leave().catch(()=>{}),{status:`unavailable`,inboxTaken:!1};c=a;try{if(!a.claimed){await b();let e=await x(t);return r.onStatus(`none`),{status:`none`,roster:e,inboxTaken:!1}}if(a.owner!==a.self.id)return await b(),r.onStatus(`taken`),{status:`taken`,inboxTaken:!0};if(await kx(a,Cx),s)return await b(),{status:`unavailable`,inboxTaken:!1};if(a.mailbox===null)return await b(),r.onStatus(`not-kept`),{status:`not-kept`,inboxTaken:!1};let e=!0,o=new Map,u=[],p=()=>{};l=await a.on(n=>{if(!(s||c!==a)){if(n.type===`message`)e?(o.set(n.message.seq,n.message.text),p()):_(()=>S(n.message.seq,n.message.text,a,!0));else if(n.type===`deleted`){if(e){for(let e of o.keys())e>=n.from&&e<=n.to&&o.delete(e);_(async()=>{!s&&v(n.from,n.to)&&r.onWaiting([...f])})}else _(async()=>{!s&&v(n.from,n.to)&&r.onWaiting([...f])})}else n.type===`claim`&&_(async()=>{s||c!==a||(n.claimed?n.owner===a.self.id?n.mailbox||r.onStatus(`not-kept`):(await b(),r.onStatus(`taken`)):(await b(),await x(t),r.onStatus(`none`)))})}});try{let e=n;for(;!s&&o.size<100;){let t=await a.backlog(e,100-o.size);if(t.last>e&&await px(()=>s||o.has(t.last),e=>{p=e},fw,!0).catch(()=>{u.push(t.last)}),!t.more||t.last<=e)break;e=t.last}}catch{}e=!1,p=()=>{};let m=[...o].sort(([e],[t])=>e-t).slice(0,100);for(let e of u)y(e);return await _(async()=>{for(let[e,t]of m)await S(e,t,a,!1)}),s||c!==a?{status:`unavailable`,inboxTaken:!1}:(r.onStatus(`ready`),(i||m.length>0)&&r.onWaiting([...f]),a.closed?.then(e=>{s||c!==a||e.reason===`left`||(l(),l=()=>{},c=null,w(t))}),{status:`ready`,roster:d,inboxTaken:!1})}catch{return await b(),r.onStatus(`unavailable`),{status:`unavailable`,inboxTaken:!1}}},w=async e=>{for(let t=0;!s;t+=1){let n=a[Math.min(t,a.length-1)]??2e3;if(await o(n),s)return;let r=m.size>0?Math.min(h,Math.min(...m)-1):h,i=await C(e,r,!1);if(i.status===`ready`||i.status===`none`||i.status===`taken`||i.status===`not-kept`)return}};return{ready:(async()=>{d=n();let t=gw(d);if(t===void 0){let n=await _w(e);if(s)return{status:`unavailable`,inboxTaken:!1};if(n.roster!==void 0&&(d=n.roster,r.onRoster(n.roster)),!n.ok){let e=n.reason===`out-of-claims`?`out-of-claims`:`unavailable`;return r.onStatus(e),{status:e,roster:n.roster,inboxTaken:!1}}t=gw(n.roster)}if(t==null)return r.onStatus(`none`),{status:`none`,inboxTaken:!1};u=t;let i=await C(t,0,!0);return!s&&i.status===`unavailable`&&w(t),i})(),delete:y,leave:async()=>{s=!0,await b()}}},Cw=new Set([`bad-key`,`not-found`,`denied`,`blocked`,`closed`,`invalid`]),ww=async(e,t,n,r,i)=>{let a;try{a=await e.join(t)}catch(e){let t=String(pw(e));return t===`full`?`busy`:Cw.has(t)?`closed`:`unavailable`}try{return a.mailbox===null?`closed`:(await a.send(iw(a.id,n,r,i),Ex(a,bx)),`sent`)}catch(e){let t=String(pw(e));return t===`storage`||t===`quota`||t===`full`?`full`:t===`rate-limited`?`busy`:t===`denied`||t===`blocked`?`closed`:`unavailable`}finally{await a.leave().catch(()=>{})}},Tw=async(e,t,n)=>{let r;try{r=await e.join(t)}catch{return}try{r.claimed&&r.owner===r.self.id&&await r.delete(n).catch(()=>{})}finally{await r.leave().catch(()=>{})}},Ew=async(e,t,n)=>{if(hw(n.signKey,t.keys.signKey))return{ok:!1,reason:`self`};if(t.inbox===null)return{ok:!1,reason:`no-inbox`};if(n.inbox===null)return{ok:!1,reason:`closed`};let{invite:r,dhKey:i}=n.inbox,a=await xp(e,{signKey:n.signKey,dhKey:i,name:n.name,inbox:r},Date.now());if(!a.ok)return a;let o=await ww(e.rooms,r,i,{to:Y(n.signKey),name:t.name,kind:`friend`,p:t.profile,x:t.inbox,r:a.nonce,...t.chatRoom==null?{}:{m:t.chatRoom}},t.keys);return o===`sent`?{ok:!0}:{ok:!1,reason:o}},Dw=async(e,t,n,r,i=(t,n)=>Tw(e.rooms,t,n))=>{if(!r)return await i(n.inbox,n.seq),{ok:!0};let{sender:a,request:o}=n,s=await yp(e,{signKey:a.signKey,dhKey:a.dhKey,name:a.name,profile:o.p,pairNonce:mw(o.r),linkedVia:`request`,inbox:o.x,chatRoom:o.m},Date.now());return s.ok?await ww(e.rooms,o.x,a.dhKey,{to:o.k,name:t.name,kind:`accept`,p:t.profile,x:t.inbox,r:o.r,...t.chatRoom==null?{}:{m:t.chatRoom}},t.keys)===`sent`?(await i(n.inbox,n.seq),{ok:!0,roster:s.roster}):{ok:!1,reason:`unsent`,roster:s.roster}:s},Ow=async(e,t,n,r)=>{let i=Ky(n.inbox);if(i===null)return{ok:!1,reason:`no-inbox`};let a=gf(r,tw);if(a===null)return{ok:!1,reason:`link`};let o=await ww(e.rooms,i,mw(n.dhKey),{to:n.signKey,name:t.name,kind:`party`,url:a},t.keys);return o===`sent`?{ok:!0}:{ok:!1,reason:o}},kw=(e,t,n=(t,n)=>Tw(e.rooms,t,n))=>n(t.inbox,t.seq),Aw=async(e,t,n,r)=>{let i=ly(r);if(i===null)return{ok:!1,reason:`invalid`};let a=await cp(e);if(!a.ok)return a;let o=await oS(e.rooms,n);if(o.kind===`busy`||o.kind===`unavailable`)return{ok:!1,reason:o.kind};if(o.kind!==`shown`||!yw(a.roster,o.signKey))return{ok:!1,reason:`not-friend`};if(o.inbox===null)return{ok:!1,reason:`closed`};let s=await ww(e.rooms,o.inbox.invite,o.inbox.dhKey,{to:Y(o.signKey),name:t.name,kind:`comment`,text:i},t.keys);return s===`sent`?{ok:!0}:{ok:!1,reason:s}},jw=`Your profile page on FKN Social. Unclaiming it deletes stored activity and comments and moves your profile back to your name room.`,Mw={send:!1,receive:!0},Nw=e=>e?.code,Pw=e=>{let t=e.profile.pageRoom;return t===void 0?void 0:Ky(t.value)},Fw=e=>{let t=e.profile.visibility?.value;return t!==void 0&&`invite`in t&&typeof t.invite==`string`},Iw=(e,t)=>{if(Fw(e))return!1;if(bf(e).level===`public`)return!0;let n=wf(e);return n.displayName!==``||n.bio!==``||n.links.length>0||(e.profile.avatar?.value??null)!==null||(e.profile.background?.value??null)!==null||e.profile.page!==void 0||Dm(e).length>0||Sy(e).length>0||t!==void 0&&(t.public.length>0||t.friends.length>0||(t.comments?.public.length??0)>0||(t.comments?.friends.length??0)>0)},Lw=async e=>{e.defaults().send&&await e.setDefault(`send`,!1).catch(()=>{}),await kx(e,wx)},Rw=(e,t,n,r)=>Rx(e,t,n,{read:cx,fit:(n,r)=>Lx(e,t,n,r,(e,n)=>ox(e,t,n),(e,t)=>JSON.stringify(sx(e,t??``)),n=>Y(Qv.sign(ax(e.id,e.self.id,n),t.signSeed))),envelope:()=>Ox(e)},r),zw=e=>t=>({public:Vh(t.public,e.public),friends:Vh(t.friends,e.friends),comments:gy(t,e)}),Bw=async(e,t,n,r,i)=>{if(i!==void 0&&!(await Z(e,e=>Pw(e)===i?{pageRoom:null}:{})).ok)return{ok:!1,reason:`unavailable`};let a;try{a=await e.rooms.create({defaults:Mw,schema:wx})}catch{return{ok:!1,reason:`unavailable`}}try{try{await a.claim({description:jw})}catch(t){if(Nw(t)!==`full`)return{ok:!1,reason:`unavailable`};let n=await Z(e,e=>Pw(e)===void 0?{pageRoom:null}:{});return{ok:!1,reason:`out-of-claims`,roster:n.ok?n.roster:void 0}}if(await Lw(a),await Rw(a,t,n,r).catch(()=>`failed`)===`failed`)return await a.release().catch(()=>{}),{ok:!1,reason:`unavailable`};let i=await Z(e,e=>typeof Pw(e)==`string`?{}:{pageRoom:a.invite});if(i.ok&&Pw(i.roster)===a.invite)return{ok:!0,invite:a.invite,roster:i.roster};if(await a.release().catch(()=>{}),!i.ok)return{ok:!1,reason:`unavailable`};let o=Pw(i.roster);if(typeof o==`string`){let a=await Vw(e,t,o,n,r);return a.status===`ready`?{ok:!0,invite:o,roster:i.roster}:{ok:!1,reason:`unavailable`,roster:a.roster??i.roster}}return{ok:!1,reason:`unavailable`}}finally{await a.leave().catch(()=>{})}},Vw=async(e,t,n,r,i,a)=>{let o=async()=>{let t=await Z(e,e=>Pw(e)===n?{pageRoom:null}:{});return{status:`inline`,roster:t.ok?t.roster:void 0}},s;try{s=await e.rooms.join(n)}catch(e){return Nw(e)===`bad-key`?await o():{status:`unavailable`}}try{if(!s.claimed)return await o();if(s.owner!==s.self.id)return{status:`taken`};if(await Lw(s),s.mailbox===null)return{status:`not-kept`};let e=Rw(s,t,r,i).catch(()=>`failed`);return a?.refreshClaim!==!1&&await s.claim({description:jw}).catch(()=>{}),{status:await e===`failed`?`unavailable`:`ready`}}catch{return{status:`unavailable`}}finally{await s.leave().catch(()=>{})}},Hw=async(e,t,n,r,i)=>{let a;try{a=await e.join(t)}catch{return`failed`}try{return!a.claimed||a.owner!==a.self.id||a.mailbox===null?`failed`:await Rw(a,n,r,i)}catch{return`failed`}finally{await a.leave().catch(()=>{})}},Uw=async(e,t,n,r,i,a)=>{let o=!1,s=await Hw(e,t,n,r,e=>(o=Hh(e,i.app,i.at-Eh)>=10,o?e:{...e,[a]:Kh(e[a],i)}));return o?`too-many`:s},Ww=async(e,t)=>{let n;try{n=await e.join(t)}catch(e){return Nw(e)===`bad-key`}try{return!n.claimed||n.owner!==n.self.id||await n.release(),!0}catch{return!1}finally{await n.leave().catch(()=>{})}},Gw=async(e,t,n)=>{let r;try{r=await e.join(n)}catch{return}try{if(!r.claimed||r.owner!==r.self.id||r.mailbox===null)return;let e=Fx(r,t,await hx(r),cx);if(e===null||e.currentOwner)return;await Lw(r),await Rw(r,t,{version:0,profile:null})}catch{}finally{await r.leave().catch(()=>{})}},Kw=`v1/identity.json`,qw=1024,Jw=3e3,Yw=({seed:e,name:t})=>{let n=JSON.stringify({v:1,seed:Y(e),name:t,pad:``});return n.replace(`"pad":""`,`"pad":"${` `.repeat(qw-n.length)}"`)},Xw=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{v:n,seed:r,name:i}=t;if(n!==1)return`newer`;if(typeof r!=`string`||i!==null&&typeof i!=`string`)return null;let a=X(r);return a?.length===32?{seed:a,name:i}:null},Zw=async e=>{let t;try{t=await e.read(Kw)}catch(e){return{ok:!1,refusal:Mf(e)}}if(t===null)return{ok:!0,identity:null};let n=Xw(t);return n===`newer`?{ok:!1,refusal:`newer`}:n?{ok:!0,identity:n}:{ok:!1,refusal:`reset`}},Qw=async(e,t)=>{try{return await e.write(Kw,Yw(t)),null}catch(e){return Mf(e)}},$w=async(e,t)=>{let n=await Zw(e);if(!n.ok||n.identity!==null)return n;let r=await Qw(e,{seed:ux(),name:null});return r===null?(await t(Jw),Zw(e)):{ok:!1,refusal:r}},eT=(e,t)=>{let n=e=>t()?e():Promise.reject(Error(`social: the FKN account changed`)),{cloud:r,storage:i}=e;return{...e,cloud:{list:()=>n(()=>r.list()),read:e=>n(()=>r.read(e)),write:(e,t)=>n(()=>r.write(e,t)),remove:e=>n(()=>r.remove(e))},storage:{put:e=>n(()=>i.put(e)),get:(e,t)=>n(()=>i.get(e,t)),delete:e=>n(()=>i.delete(e)),list:()=>n(()=>i.list())}}},tT=e=>({kind:e}),nT=async({account:e,cloud:t},n)=>{let r=e.encryption().catch(()=>null),i=await e.availability().catch(()=>`unknown`);if(i===`unknown`)return{kind:`unreachable`};if(i===`disconnected`)return{kind:`signed-out`};let a=await r;if(a===null)return{kind:`unreachable`};if(!a.enrolled)return{kind:`no-keys`};if(!a.unlocked)return{kind:`locked`};n?.();let o=await Zw(t);return o.ok?o.identity===null?{kind:`no-identity`}:{kind:`ready`,identity:o.identity}:tT(o.refusal)},rT=async(e,t,n)=>{let r=of(t);if(!r.ok)return r;let i=await $w(e.cloud,e.sleep);if(!i.ok)return{ok:!1,reason:i.refusal};let a=i.identity;if(a===null)return{ok:!1,reason:`unreachable`};if(a.name===r.name)return{ok:!0};let o=dx(a.seed),s=typeof n?.pageRoom==`string`,c=a.name===null||s?void 0:await tS(e.rooms,o,a.name);if(c===null)return{ok:!1,reason:`unavailable`};let l=await Xx(e.rooms,o,r.name,n,c===void 0?void 0:e=>({public:Vh(e.public,c.public),friends:Vh(e.friends,c.friends),comments:gy(e,c)}));if(!l.ok&&l.reason!==`unrecorded`)return l;if(l.ok&&n===void 0){let t=await nS(e.rooms,{keys:o,name:r.name});t.pageRoom!==null&&await Gw(e.rooms,o,t.pageRoom)}if(!l.ok&&a.name!==null)return await Zx(e.rooms,r.name)?{ok:!1,reason:`unavailable`}:{ok:!1,reason:`unavailable`,kept:r.name};let u=await Qw(e.cloud,{...a,name:r.name});return u===null?a.name===null||await Zx(e.rooms,a.name)?{ok:!0}:{ok:!0,kept:a.name}:{ok:!1,reason:u}},iT=async(e,t)=>await Zx(e.rooms,t)?{ok:!0}:{ok:!1,reason:`unavailable`},aT=async(e,t,n)=>t.name===null?{ok:!1,reason:`empty`}:Xx(e.rooms,dx(t.seed),t.name,n),oT=async(e,t)=>{let n=uS(t);if(n===null)return{ok:!1,reason:`bad-recovery-key`};let r=await Qw(e.cloud,{seed:n,name:null});return r===null?{ok:!0}:{ok:!1,reason:r}},sT=async e=>{let t=await Qw(e.cloud,{seed:ux(),name:null});return t===null?{ok:!0}:{ok:!1,reason:t}},cT=async({cloud:e,rooms:t,storage:n})=>{let r=await cp({cloud:e});if(r.ok)return{ok:!0};if(r.reason!==`reset`)return{ok:!1,reason:r.reason};let i=await Zw(e);if(i.ok&&i.identity?.name!=null){let n={keys:dx(i.identity.seed),name:i.identity.name},r=await nS(t,n);if(r.inbox!==null||r.pageRoom!==null||r.chatRoom!==null){let i=await cp({cloud:e});if(i.ok)return{ok:!0};if(i.reason!==`reset`)return{ok:!1,reason:i.reason};let a=r.chatRoom??(r.pageRoom===null?null:await rS(t,n,r.pageRoom));r.inbox!==null&&await vw(t,r.inbox),r.pageRoom!==null&&await Ww(t,r.pageRoom),a!==null&&await zC(t,a)}}let a=await n.list().then(({objects:e})=>e,()=>[]);for(let{url:e}of a)await n.delete(e).catch(()=>{});try{let t=(await e.list()).map(({path:e})=>e).filter(e=>e!==Kw);for(let n of t)await e.remove(n);return{ok:!0}}catch(e){return{ok:!1,reason:Mf(e)}}},lT={ok:!1,reason:`none`},uT=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),dT=e=>{if(typeof e!=`object`||!e)return!1;let{roomId:t,owner:n,text:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`},fT=e=>dT(e)&&typeof e.name==`string`&&(e.core===void 0||dT(e.core)),pT=e=>e===null?lT:{ok:!0,...e},mT=e=>{for(let t of Jy(e.roomId)){let n=rx(e.text,t,e.owner,e.name);if(n!==null)return{proof:n,roomId:t}}if(e.core===void 0)return null;let t=null;for(let n of Jy(e.core.roomId))if(t=rx(e.core.text,n,e.core.owner,e.name),t!==null)break;if(t?.pageRoom===void 0||!Yy(qy(t.pageRoom),e.roomId))return null;for(let n of Jy(e.roomId)){let r=cx(e.text,n,e.owner);if(r!==null&&uT(r.signKey,t.signKey))return{proof:r,roomId:n}}return null},hT=async(e,t,n,r)=>{let i=mT(n);if(i?.proof.friends==null)return lT;let a=await t();if(a.kind!==`ready`)return lT;let o=dx(a.identity.seed),s={roomId:i.roomId,owner:n.owner};if(uT(i.proof.signKey,o.signKey))return pT(Ub(o,s,i.proof.friends));let c=await(r?r():cp(e)),l=c.ok?c.roster.friends[cf(i.proof.signKey)]?.value:void 0,u=l?.state===`active`?X(l.dhKey):null;return u?.length===32?pT(Wb(o,u,s,i.proof.friends)):lT},gT=(e,t,n,r)=>{if(r===void 0)return;let i=X(n),a=i?.length===32?mT(r):null;if(a?.proof.friends!=null&&uT(a.proof.signKey,t))return Wb(e,i,{roomId:a.roomId,owner:r.owner},a.proof.friends)?.chatRoom??void 0},_T=async(e,t,n)=>{let r=X(n.signKey);if(r?.length!==32)return null;let i=await sS(e,n.name).catch(()=>null);if(i?.kind!==`shown`||!uT(i.signKey,r))return null;if(i.profile!==null){let e=gT(t,r,n.dhKey,i.record);return{displayName:i.profile.displayName,bio:i.profile.bio,links:i.profile.links,avatar:i.profile.avatar,...e===void 0?{}:{chatRoom:e}}}if(i.record!==void 0){let e=X(n.dhKey),a=e?.length===32?mT(i.record):null;if(a?.proof.friends!=null&&uT(a.proof.signKey,r)){let n=Wb(t,e,{roomId:a.roomId,owner:i.record.owner},a.proof.friends);if(n?.profile!=null)return{displayName:n.profile.displayName,bio:n.profile.bio,links:n.profile.links,avatar:yf(n.profile.avatar??null)??null,...n.chatRoom===void 0?{}:{chatRoom:n.chatRoom}};if(n?.chatRoom!==void 0)return{displayName:``,bio:``,links:[],avatar:null,chatRoom:n.chatRoom}}}return null},vT=async(e,t,n)=>{let r=X(n.signKey);if(r?.length!==32)return null;let i=await sS(e,n.name).catch(()=>null);return i?.kind!==`shown`||!uT(i.signKey,r)?null:gT(t,r,n.dhKey,i.record)??null},yT=e=>{let t=null,n=null,r=()=>{if(n!==null)return n;let t=cp(e).then(e=>(!e.ok&&n===t&&(n=null),e));return n=t,t},i=()=>t??=nT(e,()=>{r()});return{own:async()=>{let e=await i();return e.kind===`ready`?dx(e.identity.seed).signKey:null},friends:t=>hT(e,i,t,r)}},bT=e=>e?.code,xT=e=>[e.profile.avatar?.value??null,e.profile.background?.value??null],ST=e=>{let t=e.profile.visibility?.value;return t!==void 0&&`invite`in t&&typeof t.invite==`string`?t.invite:null},CT=e=>{let t=bf(e).level,n=ST(e)===null,{displayName:r,bio:i,links:a}=wf(e),[o,s]=xT(e),c=n?Am(e):[],l=n?km(e):[],u=LC(e);return{profile:t===`friends`&&n?{displayName:r,bio:i,links:a,...o===null?{}:{avatar:o},...s===null?{}:{background:s}}:null,sections:vb(e,t!==`me`&&n),...mb(e,`favourites`)===`friends`?{favourites:Sy(e)}:{},...c.length>0?{panels:c}:{},...c.length>0&&l.length>0?{panelOrder:jm(e)}:{},...typeof u==`string`?{chatRoom:u}:{},members:Hf(e).map(e=>X(e.dhKey)).filter(e=>e?.length===32),left:Object.entries(e.friends).filter(([,e])=>e.value.state!==`active`).map(([e])=>e).sort()}},wT=e=>{let t=wf(e),n=Math.max(0,...Bf(e).map(({lamport:e})=>e)),r=ST(e)===null,i=bf(e).level===`public`&&r,a=_b(e,i),o=mb(e,`activity`),s=CT(e),c=mb(e,`favourites`)===`public`?Sy(e):void 0,l=r?km(e):[],u=mb(e,`comments`);if(!i)return{version:n,profile:null,page:a,activity:o,favourites:c,commentsLevel:u,...l.length>0?{panels:l}:{},friends:s};let[d,f]=xT(e);return{version:n,profile:{displayName:t.displayName,bio:t.bio,links:t.links,avatar:d,background:f},page:a,activity:o,favourites:c,commentsLevel:u,...l.length>0?{panels:l}:{},friends:s}},TT=(e,t=!1)=>({...wT(e),inbox:t?null:gw(e)??null}),ET=(e,t,n=!1)=>{let r=Math.max(0,...Bf(e).map(({lamport:e})=>e)),i=n?null:gw(e)??null,a=ST(e)===null,o=bf(e).level===`public`&&a,s=t!==null&&o?wf(e).displayName:``;return{version:r,profile:null,inbox:i,...s===``?{}:{displayName:s},...t===null?{}:{pageRoom:t}}},DT=e=>JSON.stringify({inbox:e.inbox??null,displayName:e.displayName??null,pageRoom:e.pageRoom??null}),OT=(e,t=!1)=>{let n=Pw(e);return typeof n==`string`?ET(e,n,t):TT(e,t)},kT=async(e,t,n,r)=>{let i=r?.skipNameIfUnchanged!==!0;if(r?.skipNameIfUnchanged===!0&&r.lastNameStatus===`held`&&n!==null&&!(`then`in n)){let{roster:i,inboxTaken:a}=n,o=Pw(i);if(typeof o==`string`){let n=DT(ET(i,o,a));if(n===r.lastCoreKey){let r=await Vw(e,t.keys,o,wT(i),void 0,{refreshClaim:!1});if(r.status!==`inline`)return{status:`held`,pageStatus:r.status,...r.roster?{roster:r.roster}:{},coreKey:n};let s=r.roster??i;return{status:await Qx(e.rooms,t,()=>Promise.resolve(TT(s,a)),async e=>e,{refreshClaim:!1}),pageStatus:`inline`,...r.roster?{roster:r.roster}:{},coreKey:null}}}}let a=`unused`,o,s=null,c=n!==null&&!(`then`in n)?n:null,l=c?Pw(c.roster):void 0,u=typeof l==`string`?Vw(e,t.keys,l,wT(c.roster),void 0,{refreshClaim:i}):null,d=await Qx(e.rooms,t,()=>Promise.resolve(n),async({roster:n,inboxTaken:r},c)=>{let l=Pw(n);if(typeof l==`string`){u??=Vw(e,t.keys,l,wT(n),void 0,{refreshClaim:i});let c=await u;if(o=c.roster,c.status===`inline`)return a=`inline`,s=null,TT(c.roster??n,r);if(a=c.status,c.status===`unavailable`)return s=null,null;let d=ET(n,l,r);return s=DT(d),d}if(l===void 0){let i=await c();if(!Iw(n,i))return a=`unused`,s=null,TT(n,r);let l=await Bw(e,t.keys,wT(n),zw(i));if(o=l.roster,l.ok){a=`ready`;let e=ET(l.roster,l.invite,r);return s=DT(e),e}return a=l.reason===`out-of-claims`?`out-of-claims`:`unavailable`,s=null,TT(l.roster??n,r)}return a=`inline`,s=null,TT(n,r)},{refreshClaim:i}),f=await Promise.resolve(n);if(f!==null&&u===null&&typeof Pw(f.roster)==`string`&&(u=Vw(e,t.keys,Pw(f.roster),wT(f.roster),void 0,{refreshClaim:i})),u!==null){let e=await u;a=e.status,e.roster!==void 0&&(o=e.roster)}return{status:d,pageStatus:a,...o?{roster:o}:{},coreKey:d===`held`?s:null}},AT=async(e,t,n)=>{for(let r=0;r<2;r++){let r=await cp(e);if(!r.ok)return`failed`;let i=Pw(r.roster);if(typeof i==`string`&&e.rooms.join!==void 0){let a=await Hw(e.rooms,i,t.keys,wT(r.roster),n);if(a!==`newer`)return a}else{let i=await $x(e.rooms,t,TT(r.roster),n);if(i!==`newer`)return i}}return`failed`},jT=async(e,t,n,r)=>{let i={id:n.id,name:n.sender.name,text:n.text,at:Date.now()};return await AT(e,t,e=>_y(e,i))===`written`&&(await kw(e,n,r),!0)},MT=async(e,t,n=!1)=>{let r=await Z(e,e=>bf(e).level===`public`?{}:{visibility:{level:`public`}});if(!r.ok)return r;let i=await kT(e,t,{roster:r.roster,inboxTaken:n});return{ok:!0,roster:i.roster??r.roster,status:i.status,pageStatus:i.pageStatus}},NT=async(e,t,n=!1)=>{let r;try{r=await e.join(t)}catch(e){return bT(e)===`bad-key`}try{return r.claimed?r.owner===r.self.id?(await r.release(),!0):!n:!0}catch{return!1}finally{await r.leave().catch(()=>{})}},PT=async(e,t,n,r,i=!1)=>{let a=ST(n);if(a!==null&&!await NT(e.rooms,a))return{ok:!1,reason:`unavailable`};let o=bf(n).level,s=o===`public`,c=o===`friends`&&r===`me`,l=[],u=await Z(e,e=>{if(s){let t=xT(e);return l=t.some(e=>e!==null)?t:xT(n),bf(e).level===r&&t.every(e=>e===null)?{}:{visibility:{level:r},avatar:null,background:null}}if(bf(e).level===`public`)return{};if(c){let t=xT(e);if(t.some(e=>e!==null))return l=t,{visibility:{level:r},avatar:null,background:null}}return{visibility:{level:r}}});if(!u.ok)return u;let d=await kT(e,t,{roster:u.roster,inboxTaken:i});return typeof Pw(u.roster)==`string`&&d.pageStatus!==`ready`&&d.pageStatus!==`inline`?{ok:!1,reason:`unavailable`,pageStatus:d.pageStatus}:(await qp(e.storage,l),{ok:!0,roster:d.roster??u.roster,status:d.status,pageStatus:d.pageStatus})},FT=async(e,t)=>{let n=ST(t);if(n===null)return{ok:!0,roster:t};if(!await NT(e.rooms,n,!0))return{ok:!1,reason:`unavailable`};let r=[],i=await Z(e,e=>ST(e)===n?(r=xT(e),{visibility:{level:`friends`},avatar:null,background:null}):{});return i.ok&&await qp(e.storage,r),i},IT=e=>Array.isArray(e)?Th.filter(t=>e.includes(t)):[],LT=(e,t)=>{let n=e.apps[t]?.value;if(typeof n!=`object`||!n)return null;let{kinds:r,level:i,state:a,presence:o,publishingAsked:s,connectedAt:c}=n;return{kinds:IT(r),level:i===`public`?`public`:`friends`,state:a===`asked`||a===`allowed`?a:`stopped`,...o===`allowed`||o===`blocked`?{presence:o}:{},...typeof s==`boolean`?{publishingAsked:s}:{},...typeof c==`number`&&Number.isSafeInteger(c)&&c>=0?{connectedAt:c}:{}}},RT=e=>e?.state===`allowed`?{state:`allowed`,kinds:e.kinds}:e?.state===`asked`?{state:`asked`}:{state:`off`},zT=e=>e.reason===`locked`?`locked`:`unavailable`,BT=async e=>{let t=await nT(e);if(t.kind===`locked`)return`locked`;if(t.kind===`no-identity`)return`no-name`;if(t.kind!==`ready`)return`unavailable`;let{seed:n,name:r}=t.identity;if(r===null)return`no-name`;let i=await cp(e);return i.ok?{me:{keys:dx(n),name:r},roster:i.roster}:zT(i)},VT=(e,t)=>e.length===t.length&&e.every(e=>t.includes(e)),HT=(e,t)=>{let n=async(n,r)=>{let i=await BT(e);if(typeof i==`string`)return{state:i};let a=LT(i.roster,n);if(r(a)===null)return RT(a);let o=await fp(e,n,e=>{let t=r(LT(e,n));return t===null?null:{grant:t}});return o.ok&&t?.onRosterChange?.(),o.ok?RT(LT(o.roster,n)):{state:zT(o)}},r=Promise.resolve(),i=e=>{let t=r.then(e,e);return r=t.catch(()=>{}),t};return{publishing:async t=>{let n=await BT(e);return typeof n==`string`?{state:n}:RT(LT(n.roster,t))},allow:(e,t)=>{let r=IT(t?.kinds);return n(e,e=>r.length===0||e?.state===`allowed`||e?.state===`asked`&&VT(e.kinds,r)?null:{kinds:r,level:e?.level??`friends`,state:`asked`,...e?.presence===void 0?{}:{presence:e.presence},...e?.connectedAt===void 0?{}:{connectedAt:e.connectedAt}})},stop:e=>n(e,e=>e===null||e.state===`stopped`?null:{...e,state:`stopped`}),publish:(t,n)=>i(async()=>{for(let r=0;r<2;r++){let r=await BT(e);if(typeof r==`string`)return{ok:!1,reason:r};let i=LT(r.roster,t),a=mb(r.roster,`activity`);if(i?.state!==`allowed`||a===`off`)return{ok:!1,reason:`not-allowed`};let o=zh(n,t,Date.now());if(o===null)return{ok:!1,reason:`invalid`};if(!i.kinds.includes(o.kind))return{ok:!1,reason:`not-allowed`};let s=Pw(r.roster),c=typeof s==`string`?await Uw(e.rooms,s,r.me.keys,wT(r.roster),o,i.level):await eS(e.rooms,r.me,TT(r.roster),o,i.level);if(c===`written`)return{ok:!0,id:o.id};if(c!==`newer`)return{ok:!1,reason:c===`too-many`?`too-many`:`unavailable`}}return{ok:!1,reason:`unavailable`}})}},UT=async(e,t,n)=>{let r=!1;return{outcome:await fp(e,t,e=>LT(e,t)===null?(r=!0,{grant:{kinds:[],level:`friends`,state:`stopped`,presence:`allowed`,publishingAsked:!1,connectedAt:n}}):(r=!1,null)),wrote:r}},WT=(e,t,n)=>fp(e,t,e=>{let r=LT(e,t);if(r===null)return null;let i={...r,...n},a=i.state===`allowed`&&r.state!==`allowed`&&mb(e,`activity`)===`off`?hb(fb(e),`activity`,i.level):void 0;return a===void 0&&JSON.stringify(i)===JSON.stringify(r)?null:{grant:i,page:a}}),GT=new TextEncoder,KT=e=>GT.encode(e),qT=0,JT=e=>{let t=[e.roomId,e.memberId,String(e.at),e.name,e.displayName,e.avatarUrl];for(let e of t)if(e.includes(`\0`))throw Error(`social: a signed field may not contain a NUL`);if(e.signKey.length!==32||e.dhKey.length!==32)throw Error(`social: a public key is 32 bytes`);let n=[KT(Ey),Uint8Array.of(qT),KT(e.roomId),Uint8Array.of(qT),KT(e.memberId),Uint8Array.of(qT),KT(String(e.at)),Uint8Array.of(qT),e.signKey,Uint8Array.of(qT),e.dhKey,Uint8Array.of(qT),KT(e.name.normalize(`NFC`)),Uint8Array.of(qT),KT(e.displayName.normalize(`NFC`)),Uint8Array.of(qT),KT(e.avatarUrl)],r=n.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i},YT=(e,t)=>({t:`social.hello`,v:1,k:Y(e.signKey),d:Y(e.dhKey),h:e.name,n:e.displayName,i:e.avatarUrl===``?null:e.avatarUrl,a:e.at,s:Y(Qv.sign(JT(e),t))}),XT=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.t===`social.hello`&&typeof t.k==`string`&&typeof t.d==`string`&&typeof t.h==`string`&&typeof t.n==`string`&&(t.i===null||typeof t.i==`string`)&&typeof t.a==`number`&&typeof t.s==`string`},ZT=(e,t,n)=>{if(!XT(e))return{ok:!1,reason:`malformed`};if(e.v!==1)return{ok:!1,reason:`unsupported-version`};let r=X(e.k),i=X(e.d),a=X(e.s);if(!r||!i||!a)return{ok:!1,reason:`malformed`};if(r.length!==32||i.length!==32)return{ok:!1,reason:`bad-key`};if(a.length!==64||!Number.isSafeInteger(e.a))return{ok:!1,reason:`malformed`};let o={roomId:t,memberId:n,at:e.a,signKey:r,dhKey:i,name:e.h,displayName:e.n,avatarUrl:e.i??``},s;try{s=JT(o)}catch{return{ok:!1,reason:`malformed`}}try{if(!Qv.verify(a,s,r,{zip215:!1}))return{ok:!1,reason:`bad-signature`}}catch{return{ok:!1,reason:`bad-signature`}}return{ok:!0,hello:o}},QT=(e,t)=>({roomId:e,selfMemberId:t,participants:new Map,keyByMember:new Map}),$T=(e,t)=>({memberId:e,status:`silent`,identity:null,nickname:null,refusal:null,self:e===t}),eE=(e,t)=>{e.participants.has(t)||e.participants.set(t,$T(t,e.selfMemberId))},tE=(e,t)=>{e.participants.delete(t),e.keyByMember.delete(t)},nE=(e,t,n)=>{e.participants.set(t,{...$T(t,e.selfMemberId),status:`unverified`,refusal:n})},rE=(e,t,n)=>({fingerprint:cf(t),handle:uf(e.h,t),name:e.h,displayName:e.n,avatar:e.i,signKey:e.k,dhKey:e.d,shortFingerprint:df(t)}),iE=e=>X(e),aE=(e,t,n,r,i)=>{if(typeof n!=`object`||!n)return!1;let a=n;if(a.t!==`social.hello`)return!1;if(eE(e,t),typeof a.h!=`string`||!sf(a.h)||typeof a.n!=`string`||hf(a.n,{max:32,multiline:!1})!==null)return nE(e,t,`bad-name`),!0;if(typeof a.a!=`number`||Math.abs(a.a-r)>6e5)return nE(e,t,`stale`),!0;let o=ZT(n,e.roomId,t);if(!o.ok)return nE(e,t,o.reason),!0;let s=n,c=rE(s,iE(s.k),iE(s.d));for(let[n,r]of e.keyByMember)if(n!==t&&r===s.k)return nE(e,n,`duplicate-key`),nE(e,t,`duplicate-key`),e.keyByMember.set(t,s.k),!0;e.keyByMember.set(t,s.k);let l=i.friendByFingerprint(c.fingerprint),u=l===null?i.friendNamed(c.name)?`rekeyed`:`verified`:`friend`;return e.participants.set(t,{memberId:t,status:u,identity:c,nickname:l?.nickname??null,refusal:null,self:t===e.selfMemberId}),!0},oE=e=>[...e.participants.values()].sort((e,t)=>e.memberId.localeCompare(t.memberId)),sE=/^[A-Za-z0-9_-]+$/,cE=43,lE=(e,t)=>`${e}/i#${t.key}.${t.nonce}.${t.roomId}`,uE=e=>{if(e[cE]!==`.`||e[87]!==`.`)return null;let t=e.slice(0,cE),n=e.slice(44,87),r=e.slice(88);return r.length===0||!sE.test(t)||!sE.test(n)?null:{roomId:r,key:t,nonce:n}},dE=9e5,fE=1e4,pE={t:`social.whois`,v:1},mE=e=>({state:e,listeners:new Set}),hE=(e,t)=>{e.state=t;for(let n of e.listeners)n(t)},gE=e=>t=>(e.listeners.add(t),()=>{e.listeners.delete(t)}),_E=()=>Y(crypto.getRandomValues(new Uint8Array(16))),vE=e=>{try{let t=JSON.parse(e);return typeof t==`object`&&t?t:null}catch{return null}},yE=(e,t)=>JSON.stringify(YT({roomId:e.id,memberId:e.self.id,at:Date.now(),signKey:t.keys.signKey,dhKey:t.keys.dhKey,name:t.name,displayName:``,avatarUrl:``},t.keys.signSeed)),bE=(e,t,n,r,i,a,o)=>{let s=QT(t.id,t.self.id);aE(s,r,i,a,{friendByFingerprint:()=>null,friendNamed:()=>!1});let c=s.participants.get(r)?.identity;if(!c)return null;let l={memberId:r,fingerprint:c.fingerprint,name:c.name,displayName:c.displayName,signKey:X(c.signKey),dhKey:X(c.dhKey),confirmed:null,friend:n(c.fingerprint)};return iS(e.rooms,l.name,l.signKey).then(e=>o({...l,confirmed:e})),l},xE=async(e,t,n)=>{if(e.writerId===null)return{ok:!1,reason:`no-writer`};let r;try{r=await e.rooms.create({members:2})}catch{return{ok:!1,reason:`unavailable`}}let i=crypto.getRandomValues(new Uint8Array(32)),a=r.invite.indexOf(`.`),o=lE(Vu,{key:r.invite.slice(0,a),nonce:Y(i),roomId:r.invite.slice(a+1)}),s=Date.now()+dE,c=mE({kind:`waiting`}),l=new Map,u=null,d=null,f=!1,p=()=>{},m=()=>`peer`in c.state?c.state.peer:null,h=()=>c.state.kind===`friends`,g=async e=>{h()||hE(c,e),!f&&(f=!0,clearTimeout(x),p(),await r.leave().catch(()=>{}))},_=async()=>{let t=m();if(d===null||t===null)return;let n=await yp(e,d,Date.now());n.ok?await g({kind:`friends`,peer:t}):hE(c,{kind:`unsaved`,peer:t,reason:n.reason})},v=(t,i,a)=>{let o=m();if(o!==null&&o.memberId===t)return;let s=bE(e,r,n,t,i,a,e=>{m()?.memberId===e.memberId&&c.state.kind===`joined`&&hE(c,{kind:`joined`,peer:e})});s!==null&&(c.state.kind===`waiting`||c.state.kind===`left`)&&hE(c,{kind:`joined`,peer:s})},y=async(e,n)=>{let a=m();if(c.state.kind!==`offered`||a===null||a.memberId!==e)return;let o=kS(n,{roomId:r.id,fromMemberId:e,selfMemberId:r.self.id},{dhSeed:t.keys.dhSeed,theirSignKey:a.signKey,theirDhKey:a.dhKey});o.ok&&l.get(o.body.offerId)===e&&(d={signKey:a.signKey,dhKey:a.dhKey,name:a.name,profile:o.body.profile,pairNonce:i,linkedVia:`invite`,inbox:o.body.inbox,chatRoom:o.body.chatRoom},await _())},b=e=>{if(e.type===`left`&&d===null&&e.id===m()?.memberId&&(c.state.kind===`joined`||c.state.kind===`offered`)){hE(c,{kind:`left`});return}if(e.type!==`message`||e.message.from===r.self.id)return;let{from:n,text:i,at:a}=e.message,o=vE(i);o?.t===`social.whois`?(r.send(yE(r,t)).catch(()=>{}),c.state.kind===`offered`&&m()?.memberId===n&&u!==null&&r.send(u).catch(()=>{})):o?.t===`social.hello`?v(n,o,a):o?.t===`social.accept`&&y(n,o)},x=setTimeout(()=>void g({kind:`closed`}),dE);return p=await r.on(b),r.closed.then(()=>void g({kind:`closed`})),{ok:!0,invite:{link:o,expiresAt:s,state:()=>c.state,on:gE(c),add:async()=>{let e=m();if(c.state.kind!==`joined`||e===null)return!1;let n=_E(),a=JSON.stringify(CS({nonce:i,profile:t.profile,inbox:t.inbox,chatRoom:t.chatRoom},{roomId:r.id,fromMemberId:r.self.id,toMemberId:e.memberId,id:n},{signSeed:t.keys.signSeed,dhSeed:t.keys.dhSeed,theirDhKey:e.dhKey}));try{await r.send(a)}catch{return!1}return l.set(n,e.memberId),u=a,hE(c,{kind:`offered`,peer:e}),!0},saveAgain:_,close:()=>g({kind:`closed`})}}},SE=new Set([`bad-key`,`invalid`,`not-found`,`denied`,`blocked`,`closed`]),CE=(e,t,n,r)=>{let i=mE({kind:`joining`}),a=X(n.nonce),o=null,s=()=>{},c,l=null,u=null,d=!1,f=()=>`host`in i.state?i.state.host:null,p=()=>[`friends`,`closed`,`in-use`,`unavailable`].includes(i.state.kind),m=async e=>{p()||hE(i,e),!d&&(d=!0,clearTimeout(c),s(),await o?.leave().catch(()=>{}))},h=(n,o,s,u)=>{if(o!==n.owner)return;let d=vE(s);if(d?.t===`social.hello`&&f()===null){let a=bE(e,n,r,o,d,u,e=>{let t=i.state;`host`in t&&t.host?.memberId===e.memberId&&hE(i,{...t,host:e})});if(a===null)return;clearTimeout(c),hE(i,{kind:`waiting`,host:a}),n.send(yE(n,t)).catch(()=>{})}else if(d?.t===`social.offer`){let e=f();if(e===null||i.state.kind!==`waiting`&&i.state.kind!==`offered`)return;let r=OS(d,{roomId:n.id,fromMemberId:o,selfMemberId:n.self.id},{dhSeed:t.keys.dhSeed,theirSignKey:e.signKey,theirDhKey:e.dhKey});if(!r.ok||a===null||!wE(r.body.nonce,a))return;l={id:r.id,nonce:r.body.nonce,profile:r.body.profile,inbox:r.body.inbox,chatRoom:r.body.chatRoom},hE(i,{kind:`offered`,host:e,profile:r.body.profile})}},g=async e=>{if(o!==null&&u!==null){try{await o.send(u)}catch{hE(i,{kind:`unsent`,host:e});return}await m({kind:`friends`,host:e})}};return(async()=>{let t;try{t=await e.rooms.join(`${n.key}.${n.roomId}`)}catch(e){let t=e?.code;hE(i,t===`full`?{kind:`in-use`}:SE.has(String(t))?{kind:`closed`}:{kind:`unavailable`});return}if(o=t,t.owner===t.self.id)return void m({kind:`closed`});if(d)return void t.leave().catch(()=>{});s=await t.on(e=>{e.type===`left`&&e.id===t.owner&&m({kind:`closed`}),e.type===`message`&&h(t,e.message.from,e.message.text,e.message.at)}),t.closed.then(()=>void m({kind:`closed`})),hE(i,{kind:`waiting`,host:null}),c=setTimeout(()=>{f()===null&&m({kind:`closed`})},fE),await t.send(JSON.stringify(pE)).catch(()=>{})})(),{state:()=>i.state,on:gE(i),accept:async()=>{let n=i.state;if(n.kind!==`offered`&&n.kind!==`failed`||l===null||o===null)return;let r=n.host;hE(i,{kind:`accepting`,host:r,profile:l.profile});let a=await yp(e,{signKey:r.signKey,dhKey:r.dhKey,name:r.name,profile:l.profile,pairNonce:l.nonce,linkedVia:`invite`,inbox:l.inbox,chatRoom:l.chatRoom},Date.now());if(!a.ok){hE(i,{kind:`failed`,host:r,profile:l.profile,reason:a.reason});return}u=JSON.stringify(wS({offerId:l.id,profile:t.profile,inbox:t.inbox,chatRoom:t.chatRoom},{roomId:o.id,fromMemberId:o.self.id,toMemberId:r.memberId,id:_E()},{signSeed:t.keys.signSeed,dhSeed:t.keys.dhSeed,theirDhKey:r.dhKey})),await g(r)},sendAgain:async()=>{let e=f();i.state.kind===`unsent`&&e!==null&&await g(e)},decline:()=>m({kind:`closed`})}},wE=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),TE={started:`start`,watched:`watch`,completed:`finish`,rated:`rate`},EE=e=>Th.filter(t=>e.includes(t)),DE=(e,t,n)=>{let r=n||Ph(e),i=EE(t).map(e=>TE[e]);return i.length===0?`${r} asks to post to your page.`:`${r} asks to post when you ${i.length===1?i[0]:`${i.slice(0,-1).join(`, `)} or ${i.at(-1)}`} something.`},OE=()=>{let[e,t]=K(!1),[n,r]=K(null);return{busy:e,problem:n,run:async n=>{if(e)return!1;t(!0),r(null);let i=await n();return t(!1),r(i),i===null}}},kE=({asks:e,actions:t,names:n,onAnswered:r})=>{let{busy:i,problem:a,run:o}=OE(),s=J(new Map),c=new Set(e.map(({app:e})=>e));for(let e of s.current.keys())c.has(e)||s.current.delete(e);let l=(e,t)=>{let n=s.current.get(e);if(n!==void 0)return n;let r=EE(t);return s.current.set(e,r),r},u=async(e,n)=>{await o(()=>t.change(e,n))&&r?.()};return e.length===0?null:Q(`div`,{className:`social-stack`,"data-social-asks":!0,children:[e.map(({app:e,grant:t})=>{let r=l(e,t.kinds);return Q(`div`,{className:`social-invite`,"data-social-ask":e,children:[Q(`p`,{children:DE(e,r,n?.[e])}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-social-allow":!0,"aria-disabled":i,onClick:()=>void u(e,{state:`allowed`,kinds:r}),children:`Allow`}),Q(`button`,{type:`button`,"data-social-not-now":!0,"aria-disabled":i,onClick:()=>void u(e,{state:`stopped`}),children:`Not now`})]})]},e)}),Q(uh,{children:a})]})},AE=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`}],jE=[{presence:`allowed`,label:`Share`},{presence:`blocked`,label:`Block`}],ME=({app:e,grant:t,actions:n,displayName:r})=>{let{busy:i,problem:a,run:o}=OE(),[s,c]=K(!1),l=J(null),u=Ph(e),d=r||u,f=t.presence??`allowed`,p=t=>void o(()=>n.change(e,t)),m=e=>Th.filter(n=>n===e?!t.kinds.includes(n):t.kinds.includes(n)),h=()=>{c(!1),l.current?.focus()},g=async()=>{await o(()=>n.remove(e))&&h()};return Q(`li`,{className:`social-section`,"data-social-app":e,"data-social-app-state":t.state,"data-social-app-presence":f,children:[Q(`span`,{className:`social-choice-label`,children:d}),d!==u&&Q(`span`,{className:`social-muted`,children:u}),t.publishingAsked!==!1&&Q(G,{children:[Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`What it posts`}),Q(`div`,{className:`social-checks`,role:`group`,"aria-label":`What it posts`,children:Th.map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`checkbox`,value:e,checked:t.kinds.includes(e),"aria-disabled":i,onChange:()=>p({kinds:m(e)})}),Q(`span`,{className:`social-choice-label`,children:wh[e]})]},e))})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Who sees its posts`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees its posts`,children:AE.map(({level:n,label:r})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`app-level-${e}`,value:n,checked:t.level===n,"aria-disabled":i,onChange:()=>p({level:n})}),Q(`span`,{className:`social-choice-label`,children:r})]},n))})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,"data-social-app-switch":!0,"aria-disabled":i,onClick:()=>p(t.state===`allowed`?{state:`stopped`}:{state:`allowed`,kinds:EE(t.kinds)}),children:t.state===`allowed`?`Stop`:`Allow`}),Q(`button`,{type:`button`,"data-social-app-delete":!0,ref:l,"aria-disabled":i,onClick:()=>{i||c(!0)},children:`Delete everything it posted`})]}),s&&Q(`div`,{className:`social-warn`,"data-social-delete-app":!0,children:[Q(`p`,{children:[`Delete everything `,d,` posted?`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-social-delete-confirm":!0,ref:lh,"aria-disabled":i,onClick:()=>void g(),children:`Delete`}),Q(`button`,{type:`button`,"aria-disabled":i,onClick:()=>{i||h()},children:`Cancel`})]})]})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Room identity`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Room identity`,children:jE.map(({presence:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`app-presence-${e}`,value:t,checked:f===t,"aria-disabled":i,onChange:()=>p({presence:t})}),Q(`span`,{className:`social-choice-label`,children:n})]},t))}),Q(`span`,{className:`social-muted`,children:`Applies the next time this app joins a room.`})]}),Q(uh,{children:a})]})},NE=({apps:e,actions:t,names:n})=>Q(`ul`,{className:`social-list`,"data-social-apps":!0,children:e.map(({app:e,grant:r})=>Q(ME,{app:e,grant:r,actions:t,displayName:n?.[e]},e))}),PE=e=>t=>{t.key===`Enter`&&e()},FE=({name:e,label:t,placeholder:n,value:r,onChange:i,onSubmit:a})=>{let o=of(r);return Q(G,{children:[Q(`input`,{name:e,"aria-label":t,autoComplete:`off`,autoCapitalize:`none`,spellcheck:!1,maxLength:40,placeholder:n,value:r,onChange:e=>i(e.currentTarget.value),onKeyDown:PE(a)}),!o.ok&&o.reason!==`empty`&&Q(`p`,{className:`social-muted`,children:th(o.reason)})]})},IE=({label:e,onPick:t})=>{let[n,r]=K(``),[i,a]=K(!1),[o,s]=K(null),c=of(n),l=async()=>{if(!c.ok||i)return;a(!0),s(null);let e=await t(c.name);a(!1),e.ok||s(e.reason)};return Q(`div`,{children:[Q(FE,{name:`name`,label:`Name`,placeholder:`your name`,value:n,onChange:e=>{r(e),s(null)},onSubmit:()=>void l()}),c.ok&&c.name!==n&&Q(`p`,{className:`social-muted`,children:[`Saved as `,c.name]}),Q(eh,{reason:o}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-submit":!0,className:`social-primary`,"aria-disabled":!c.ok||i,onClick:()=>void l(),children:i?`Claiming...`:e})})]})},LE=({onRestore:e})=>{let[t,n]=K(``),[r,i]=K(!1),[a,o]=K(null),s=async()=>{if(r||t.trim()===``)return;i(!0),o(null);let n=await e(t);i(!1),n.ok||o(n.reason)};return Q(`div`,{children:[Q(`input`,{name:`recovery-key`,"aria-label":`Recovery key`,autoComplete:`off`,spellcheck:!1,placeholder:`FKNS-...`,value:t,onChange:e=>{n(e.currentTarget.value),o(null)},onKeyDown:PE(()=>void s())}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-submit":!0,"aria-disabled":t.trim()===``||r,onClick:()=>void s(),children:r?`Restoring...`:`Restore`})})]})},RE=({identity:e,fresh:t})=>{let[n,r]=K(t),i=lS(e.seed);return Q(G,{children:[Q(`h2`,{children:t?`Save your recovery key`:`Recovery key`}),Q(`p`,{className:`social-muted`,children:`Keep it somewhere private: anyone holding it can act as you.`}),n&&Q(`code`,{className:`social-key`,"data-recovery-key":!0,children:i}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,onClick:()=>r(!n),children:n?`Hide`:`Show recovery key`}),n&&Q(Sh,{text:i})]})]})},zE={lost:`Your account no longer holds this name.`,unrecorded:`Your name's record is missing. Check that Messages kept is on for it under Rooms in your FKN settings, then write it again.`,taken:`Someone else holds this name now.`,retired:`Names like this one are no longer given out.`},BE={lost:`Claim it again`,unrecorded:`Write it again`},VE=({status:e,onClaimAgain:t,onRename:n})=>{let[r,i]=K(!1),[a,o]=K(null),s=zE[e];if(s===void 0)return null;let c=async()=>{if(r)return;i(!0);let e=await t();i(!1),o(e.ok?null:e.reason)},l=BE[e];return Q(`div`,{className:`social-warn`,role:`status`,children:[Q(`p`,{children:s}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:[l!==void 0&&Q(`button`,{type:`button`,className:`social-primary`,"aria-disabled":r,onClick:()=>void c(),children:r?`Claiming...`:l}),Q(`button`,{type:`button`,onClick:n,children:`Pick another name`})]})]})},HE=({name:e,onGiveBack:t})=>{let[n,r]=K(!1),[i,a]=K(null),o=async()=>{if(n)return;r(!0);let e=await t();r(!1),a(e.ok?null:e.reason)};return Q(`div`,{className:`social-warn`,role:`status`,"data-social-kept":e,children:[Q(`p`,{children:[`Your FKN account still holds `,e,`.`]}),Q(eh,{reason:i}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":n,onClick:()=>void o(),children:n?`Giving back...`:`Give it back`})})]})},UE=({identity:e,fresh:t,status:n,actions:r,avatar:i=null,avatarUrl:a,openRename:o=!1,onRenameOpened:s})=>{let[c,l]=K(!1),[u,d]=K(null),f=dx(e.seed);q(()=>{o&&(l(!0),s?.())},[o,s]);let p=async e=>{let t=await r.rename(e);return t.ok&&l(!1),(t.ok||t.kept!==void 0)&&d(t.kept??null),t},m=async e=>{let t=await r.giveBack(e);return t.ok&&d(null),t};return Q(G,{children:[Q(`div`,{className:`social-card`,"data-social-claim":n,children:[Q(vh,{signKey:f.signKey,src:i,url:a,avatarAlt:`${e.name}'s avatar`}),Q(`div`,{children:[Q(`div`,{className:`social-name`,"data-social-name":!0,style:ch(e.name),children:e.name}),Q(`div`,{className:`social-muted`,children:`Your name on FKN Social`})]})]}),Q(VE,{status:n,onClaimAgain:r.claimAgain,onRename:()=>l(!0)}),u!==null&&Q(HE,{name:u,onGiveBack:()=>m(u)}),c?Q(G,{children:[Q(`h2`,{children:`Change your name`}),Q(`p`,{className:`social-muted`,children:[e.name,` is given back.`]}),Q(IE,{label:`Change name`,onPick:p}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>l(!1),children:`Cancel`})})]}):Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>l(!0),children:`Change name`})}),Q(RE,{identity:e,fresh:t})]})},WE=`FKN rooms did not answer. Try again in a moment.`,GE=(e,t)=>({closed:`${t} is not taking friend requests.`,full:`${t}'s inbox is full. Try again later.`,busy:WE,unavailable:WE})[e],KE=(e,t)=>({...nh,self:`This is you.`,"no-inbox":`You need an inbox to send friend requests.`,closed:GE(`closed`,t),full:GE(`full`,t),busy:WE,unavailable:WE})[e],qE={none:`You have no inbox.`,"out-of-claims":`No inbox: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`,taken:`Someone else holds your inbox now.`,"not-kept":`Your inbox keeps no messages. Turn on Messages kept for it under Rooms in your FKN settings.`,unavailable:WE},JE={...nh,"out-of-claims":qE[`out-of-claims`],busy:WE,unavailable:WE},YE=[`none`,`out-of-claims`,`taken`],XE=({onMake:e})=>{let[t,n]=K(!1),[r,i]=K(null),a=async()=>{if(t)return;n(!0);let r=await e();n(!1),i(r.ok?null:JE[r.reason])};return Q(G,{children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-make-inbox":!0,"aria-disabled":t,onClick:()=>void a(),children:t?`Making an inbox...`:`Make an inbox`})}),r!==null&&Q(`p`,{className:`social-error`,role:`alert`,children:r})]})},ZE=({status:e,onMake:t})=>e===`ready`?null:Q(`div`,{className:`social-stack`,"data-social-inbox-line":e,children:[Q(`p`,{className:`social-warn-text`,children:qE[e]}),YE.includes(e)&&Q(XE,{onMake:t})]}),QE=e=>{try{return new URL(e).host}catch{return e}},$E=({signKey:e,name:t,displayName:n=``,storage:r,avatar:i=null})=>Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:e,name:t,storage:r,avatar:i,small:!0}),Q(`div`,{children:[Q(`div`,{className:`social-person-name`,children:n||t}),n!==``&&n!==t&&Q(`div`,{className:`social-muted`,children:t})]})]}),eD=({waiting:e,actions:t,storage:n})=>{let[r,i]=K(!1),[a,o]=K(null),[s,c]=K(!1),{sender:l,request:u}=e,d=async n=>{if(r)return;i(!0);let a=await t.answer(e,n);i(!1),c(!a.ok&&a.reason===`unsent`),o(a.ok||a.reason===`unsent`?null:nh[a.reason])};return Q(`div`,{className:`social-invite`,"data-social-request":l.name,"data-social-confirmed":String(l.confirmed),children:[Q(`p`,{children:[l.name,` sent you a friend request.`]}),Q($E,{signKey:l.signKey,name:l.name,displayName:u.p.displayName,storage:n,avatar:u.p.avatar??null}),l.confirmed===!1&&Q(`p`,{className:`social-warn-text`,children:`Their name room does not confirm this name.`}),e.friend&&Q(`p`,{className:`social-muted`,children:`Already in your list.`}),s&&Q(`p`,{className:`social-error`,role:`alert`,children:[`Your answer did not reach `,l.name,`.`]}),a!==null&&Q(`p`,{className:`social-error`,role:`alert`,children:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-accept-request":!0,"aria-disabled":r,onClick:()=>void d(!0),children:s?`Send again`:`Accept`}),!s&&Q(`button`,{type:`button`,"data-decline-request":!0,"aria-disabled":r,onClick:()=>void d(!1),children:`Decline`})]})]})},tD=({waiting:e,site:t,actions:n,storage:r,avatar:i})=>{let[a,o]=K(!1),s=t(),c=async()=>{s!==null&&await s.open(e.url).catch(()=>o(!0))};return Q(`div`,{className:`social-invite`,"data-social-party":e.sender.name,children:[Q(`p`,{children:[e.sender.name,` invited you to a party at `,QE(e.url),`.`]}),Q($E,{signKey:e.sender.signKey,name:e.sender.name,storage:r,avatar:i??null}),Q(`div`,{className:`social-row`,children:[s!==null&&Q(`button`,{type:`button`,className:`social-primary`,"data-open-party":!0,onClick:()=>void c(),children:`Open`}),Q(Sh,{text:e.url}),Q(`button`,{type:`button`,"data-dismiss-party":!0,onClick:()=>void n.dismiss(e),children:`Dismiss`})]}),a&&Q(`p`,{className:`social-muted`,children:`It did not open. Copy it instead.`})]})},nD=({waiting:e,actions:t,storage:n,avatar:r})=>{let[i,a]=K(!1),[o,s]=K(!1),c=async()=>{if(i)return;a(!0);let n=await t.approve(e);a(!1),s(!n)};return Q(`div`,{className:`social-invite`,"data-social-comment":e.sender.name,children:[Q(`p`,{children:[e.sender.name,` commented on your page.`]}),Q($E,{signKey:e.sender.signKey,name:e.sender.name,storage:n,avatar:r??null}),Q(`p`,{className:`social-bio`,"data-social-comment-text":!0,children:e.text}),o&&Q(`p`,{className:`social-error`,role:`alert`,children:`FKN rooms did not answer, so nothing changed. Try again in a moment.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-approve-comment":!0,"aria-disabled":i,onClick:()=>void c(),children:`Approve`}),Q(`button`,{type:`button`,"data-delete-comment":!0,"aria-disabled":i,onClick:()=>{i||t.dismiss(e)},children:`Delete`})]})]})},rD=({status:e,waiting:t,accepted:n,site:r,actions:i,onMake:a,storage:o,friendAvatars:s})=>Q(`div`,{className:`social-stack`,"data-social-inbox-status":e??`loading`,children:[n.map(e=>Q(`p`,{"data-social-accepted":e,children:[e,` accepted your friend request.`]},e)),t.map(e=>e.kind===`friend`?Q(eD,{waiting:e,actions:i,storage:o},e.seq):e.kind===`comment`?Q(nD,{waiting:e,actions:i,storage:o,avatar:s?.[e.sender.fingerprint]??null},e.seq):Q(tD,{waiting:e,site:r,actions:i,storage:o,avatar:s?.[e.sender.fingerprint]??null},e.seq)),e!==null&&Q(ZE,{status:e,onMake:a})]}),iD=(e,t)=>({unheld:`Nobody holds the name ${t} on FKN Social right now.`,none:`${t}'s page shows nothing right now. Try again in a moment.`,busy:WE,unavailable:WE,malformed:`This link is incomplete. Ask for the link again.`})[e.kind],aD=({onAdd:e})=>{let[t,n]=K(``),r=of(t),i=()=>{r.ok&&(e(r.name),n(``))};return Q(`div`,{"data-social-add-by-name":!0,children:[Q(FE,{name:`friend-name`,label:`Friend's name`,placeholder:`their name`,value:t,onChange:n,onSubmit:i}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-add-by-name":!0,"aria-disabled":!r.ok,onClick:i,children:`Request friend`})})]})},oD=({name:e,own:t,isFriend:n,read:r,send:i,onMake:a,onClose:o,storage:s})=>{let[c,l]=K(e===null?{kind:`malformed`}:null),[u,d]=K(!1),[f,p]=K(null),m=J(null);q(()=>{let e=document.activeElement;return m.current?.focus(),()=>{e instanceof HTMLElement&&e!==document.body&&e.isConnected&&(document.activeElement===document.body||m.current?.contains(document.activeElement))&&e.focus()}},[]),q(()=>{if(e===null)return;let t=!0;return r(e).then(e=>{t&&l(e)}),()=>{t=!1}},[e,r]);let h=e??``,g=c?.kind===`shown`&&e!==null?{name:e,signKey:c.signKey,inbox:c.inbox}:null,_=g===null?null:Jm(g.signKey,t)?{ok:!1,reason:`self`}:g.inbox===null?{ok:!1,reason:`closed`}:null,v=f??_,y=_===null?g:null,b=v===null?c===null?`loading`:c.kind===`shown`?`ready`:c.kind:v.ok?`sent`:v.reason,x=async()=>{y===null||u||(d(!0),p(await i(y)),d(!1))};return Q(`div`,{ref:m,tabIndex:-1,className:`social-invite`,"data-social-send-request":b,children:[Q(`h2`,{children:e===null?`Add a friend`:`Add ${h} as a friend`}),c===null&&Q(`div`,{className:`social-inline-loader`,children:[Q(`span`,{className:`social-loader-track social-loader-track-sm`,"aria-hidden":`true`,children:Q(`span`,{className:`social-loader-bar`})}),Q(`span`,{className:`social-muted`,children:`Loading...`})]}),c!==null&&c.kind!==`shown`&&Q(`p`,{children:iD(c,h)}),c?.kind===`shown`&&Q($E,{signKey:c.signKey,name:h,displayName:c.profile?.displayName??c.displayName,storage:s,avatar:c.profile?.avatar??null}),y!==null&&n(y.signKey)&&Q(`p`,{className:`social-muted`,children:`Already in your list.`}),v?.ok===!0&&Q(`p`,{role:`status`,children:`Sent.`}),v?.ok===!1&&Q(`p`,{className:`social-error`,role:`alert`,children:KE(v.reason,h)}),v?.ok===!1&&v.reason===`no-inbox`&&Q(XE,{onMake:async()=>{let e=await a();return e.ok&&p(null),e}}),Q(`div`,{className:`social-row`,children:[y!==null&&v?.ok!==!0&&Q(`button`,{type:`button`,className:`social-primary`,"data-send-request":!0,"aria-disabled":u,onClick:()=>void x(),children:u?`Sending...`:`Send friend request`}),Q(`button`,{type:`button`,"data-close-request":!0,onClick:o,children:`Close`})]})]})},sD=e=>X(e.signKey)??new Uint8Array(32),cD=(e,t)=>e.nickname??((t==null?e.profile.displayName:t.displayName)||e.name),lD=(e,t)=>t==null?e.profile.avatar??null:t.avatar,uD=({friends:e,onOpen:t,focusRef:n,storage:r,profiles:i})=>e.length===0?Q(`p`,{className:`social-muted`,"data-social-friends":`0`,children:`No friends yet.`}):Q(`ul`,{className:`social-list`,"data-social-friends":e.length,children:e.map(e=>{let a=i?.[e.fingerprint],o=cD(e,a);return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-person`,"data-social-friend":e.name,ref:n?.(e.fingerprint),onClick:()=>t(e.fingerprint),children:[Q(bh,{signKey:sD(e),name:e.name,storage:r,avatar:lD(e,a),small:!0}),Q(`span`,{children:[Q(`span`,{className:`social-person-name`,children:o}),o!==e.name&&Q(`span`,{className:`social-muted`,children:[` `,e.name]})]})]})},e.fingerprint)})}),dD={invite:`Met through an invite link.`,party:`Met in a party.`,request:`Met through a friend request.`},fD=(e,t)=>e.ok?`Sent.`:e.reason===`link`?`A party link starts with https:// and has at most ${tw.toLocaleString(`en`)} characters.`:e.reason===`no-inbox`?`${t} has no inbox.`:e.reason===`closed`?`${t} cannot take party invites right now.`:GE(e.reason,t),pD=({name:e,onInvite:t})=>{let[n,r]=K(``),[i,a]=K(!1),[o,s]=K(null),c=async()=>{if(i||n.trim()===``)return;a(!0);let e=await t(n);a(!1),s(e),e.ok&&r(``)};return Q(`div`,{className:`social-stack`,"data-social-party-invite":!0,children:[Q(`label`,{className:`social-label`,children:[`Party link`,Q(`input`,{name:`party-link`,autoComplete:`off`,inputMode:`url`,value:n,onChange:e=>{r(e.currentTarget.value),s(null)},onKeyDown:e=>{e.key===`Enter`&&c()}})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-send-party":!0,"aria-disabled":i||n.trim()===``,onClick:()=>void c(),children:i?`Sending...`:`Send invite`})}),o!==null&&Q(`p`,{className:o.ok?`social-muted`:`social-error`,role:o.ok?`status`:`alert`,children:fD(o,e)})]})},mD=({friend:e,site:t,onNickname:n,onRemove:r,onBack:i,onInvite:a,onMessage:o,storage:s,live:c})=>{let[l,u]=K(e.nickname??``),[d,f]=K(!1),[p,m]=K(!1),[h,g]=K(null),_=async e=>{if(p)return;m(!0);let t=await e();m(!1),g(t.ok?null:nh[t.reason])},v=l.trim(),y=v===(e.nickname??``),b=cD(e,c),x=c==null?e.profile.displayName:c.displayName,S=c==null?e.profile.bio:c.bio,C=c==null?e.profile.links:c.links;return Q(`div`,{className:`social-stack`,"data-social-friend-view":e.name,children:[Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:sD(e),name:e.name,storage:s,avatar:lD(e,c)}),Q(`div`,{children:[Q(`div`,{className:`social-name`,tabIndex:-1,ref:lh,style:ch(b),children:b}),b!==e.name&&Q(`div`,{className:`social-muted`,children:e.name})]})]}),x!==``&&e.nickname!==null&&Q(`p`,{children:x}),S!==``&&Q(`p`,{className:`social-bio`,"data-social-bio":!0,children:S}),C.map(e=>Q(Ch,{url:e,site:t},e)),Q(`p`,{className:`social-muted`,children:[`Friends since `,new Date(e.linkedAt).toLocaleDateString(`en`,{year:`numeric`,month:`long`,day:`numeric`}),`.`,` `,dD[e.linkedVia]]}),a!==void 0&&Ky(e.inbox)!==null&&Q(G,{children:[Q(`h2`,{children:`Invite to a party`}),Q(pD,{name:e.name,onInvite:a})]}),Q(`label`,{className:`social-label`,children:[`Nickname, only for you`,Q(`input`,{name:`nickname`,autoComplete:`off`,maxLength:64,value:l,onChange:e=>u(e.currentTarget.value)})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":p||y,onClick:()=>{y||_(()=>n(v===``?null:v))},children:`Save nickname`})}),Q(uh,{children:h}),Q(`div`,{className:`social-row`,children:[o!==void 0&&Q(`button`,{type:`button`,className:`social-primary`,"data-social-message-friend":!0,onClick:o,children:`Message`}),Q(`button`,{type:`button`,onClick:i,children:`Back to friends`}),d?Q(`button`,{type:`button`,className:`social-danger`,"aria-disabled":p,onClick:()=>void _(r),children:[`Remove `,e.name]}):Q(`button`,{type:`button`,onClick:()=>f(!0),children:`Remove`})]})]})},hD=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(hD||{}),gD=[0,1],_D=[1,0],vD=[2,3],yD=[3,2],bD={L:gD,M:_D,Q:vD,H:yD},xD=/^\d*$/,SD=/^[A-Z0-9 $%*+./:-]*$/,CD=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,wD=1,TD=40,ED=3,DD=3,OD=40,kD=10,AD=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],jD=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],MD=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<wD||e>TD)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,hD.Timing),this.setFunctionModule(e,6,e%2==0,hD.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,PD(r,e));this.setFunctionModule(8,7,PD(r,6)),this.setFunctionModule(8,8,PD(r,7)),this.setFunctionModule(7,8,PD(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,PD(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,PD(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,PD(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=PD(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,hD.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,hD.Alignment)}setFunctionModule(e,t,n,r=hD.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==YD(t,n))throw RangeError(`Invalid argument`);let r=jD[n[0]][t],i=AD[n[0]][t],a=Math.floor(JD(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=XD(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=ZD(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(JD(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=PD(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=ED:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*OD),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*OD}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=ED:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*OD),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*OD}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=DD)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*kD,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function ND(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function PD(e,t){return!!(e>>>t&1)}var FD=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},ID=[1,10,12,14],LD=[2,9,11,13],RD=[4,8,16,16];function zD(e,t){return e[Math.floor((t+7)/17)+1]}function BD(e){let t=[];for(let n of e)ND(n,8,t);return new FD(RD,e.length,t)}function VD(e){if(!WD(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);ND(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new FD(ID,e.length,t)}function HD(e){if(!GD(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=CD.indexOf(e.charAt(n))*45;r+=CD.indexOf(e.charAt(n+1)),ND(r,11,t)}return n<e.length&&ND(CD.indexOf(e.charAt(n)),6,t),new FD(LD,e.length,t)}function UD(e){return e===``?[]:WD(e)?[VD(e)]:GD(e)?[HD(e)]:[BD(qD(e))]}function WD(e){return xD.test(e)}function GD(e){return SD.test(e)}function KD(e,t){let n=0;for(let r of e){let e=zD(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function qD(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function JD(e){if(e<wD||e>TD)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function YD(e,t){return Math.floor(JD(e)/8)-AD[t[0]][e]*jD[t[0]][e]}function XD(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=QD(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=QD(n,2)}return t}function ZD(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=QD(t,e))}return n}function QD(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function $D(e,t,n=1,r=40,i=-1,a=!0){if(!(wD<=n&&n<=r&&r<=TD)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=YD(o,t)*8,i=KD(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[_D,vD,yD])a&&s<=YD(o,e)*8&&(t=e);let c=[];for(let t of e){ND(t.mode[0],4,c),ND(t.numChars,zD(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=YD(o,t)*8;ND(0,Math.min(4,l-c.length),c),ND(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)ND(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new MD(o,t,u,i)}function eO(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?UD(e):Array.isArray(e)?[BD(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=$D(c,bD[n],i,a,o,r),u=tO({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function tO(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=hD.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var nO=({text:e})=>{let{size:t,data:n}=eO(e,{ecc:`L`,border:2}),r=``;return n.forEach((e,t)=>e.forEach((e,n)=>{e&&(r+=`M${n} ${t}h1v1h-1z`)})),Q(`svg`,{className:`social-qr`,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`QR code of the invite link`,shapeRendering:`crispEdges`,children:[Q(`rect`,{width:t,height:t,fill:`#fff`}),Q(`path`,{d:r,fill:`#000`})]})},rO=(e,t)=>{let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`},iO=()=>{let[e,t]=K(()=>Date.now());return q(()=>{let e=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(e)},[]),e},aO=({peer:e,storage:t,avatar:n=null})=>Q(`div`,{className:`social-stack`,"data-social-peer":e.name,"data-social-confirmed":String(e.confirmed),children:[Q(`div`,{className:`social-card`,children:[Q(bh,{signKey:e.signKey,name:e.name,storage:t,avatar:n,small:!0}),Q(`div`,{children:[Q(`div`,{className:`social-person-name`,children:e.displayName||e.name}),Q(`div`,{className:`social-muted`,children:e.name})]})]}),e.confirmed===!1&&Q(`p`,{className:`social-warn-text`,children:`This name could not be confirmed.`}),e.friend&&Q(`p`,{className:`social-muted`,children:`Already your friend.`})]}),oO=({profile:e,site:t})=>Q(G,{children:[e.bio!==``&&Q(`p`,{className:`social-bio`,children:e.bio}),e.links.map(e=>Q(Ch,{url:e,site:t},e))]}),sO=({link:e,expiresAt:t,state:n,onAdd:r,onClose:i,onSaveAgain:a,onDismiss:o})=>{let s=iO(),[c,l]=K(!1),u=n.kind!==`friends`&&n.kind!==`closed`,d=n.kind===`joined`||n.kind===`offered`||n.kind===`unsaved`;return Q(`div`,{className:`social-invite`,"data-social-host":n.kind,children:[u&&!d&&Q(G,{children:[Q(`code`,{className:`social-key`,"data-invite-link":!0,children:e}),Q(`div`,{className:`social-row`,children:Q(Sh,{text:e,label:`Copy link`})}),Q(nO,{text:e}),Q(`p`,{className:`social-muted`,children:[`This link works while this tab is open, for `,rO(t,s),` more.`]})]}),Q(`div`,{className:`social-stack`,role:`status`,children:[n.kind===`waiting`&&Q(`p`,{children:`Waiting for someone to open the link.`}),n.kind===`left`&&Q(`p`,{children:`They left. The link still works until it ends.`}),n.kind===`joined`&&Q(G,{children:[Q(`p`,{children:`Someone opened your link:`}),Q(aO,{peer:n.peer}),c&&Q(`p`,{className:`social-error`,role:`alert`,children:`The offer did not go out. Try again in a moment.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-add":!0,onClick:()=>void r().then(e=>l(!e)),children:[`Add `,n.peer.name]})})]}),n.kind===`offered`&&Q(G,{children:[Q(aO,{peer:n.peer}),Q(`p`,{children:[`Waiting for `,n.peer.name,` to accept.`]})]}),n.kind===`unsaved`&&Q(G,{children:[Q(aO,{peer:n.peer}),Q(`p`,{className:`social-error`,role:`alert`,children:[n.peer.name,` accepted, but your friend list was not saved. `,nh[n.reason]]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:a,children:`Save again`})})]}),n.kind===`friends`&&Q(`p`,{"data-social-done":!0,children:[`You and `,n.peer.name,` are now friends.`]}),n.kind===`closed`&&Q(`p`,{children:`This invite has ended.`})]}),Q(`div`,{className:`social-row`,children:u?Q(`button`,{type:`button`,"data-close-invite":!0,onClick:i,children:`Close the invite`}):Q(`button`,{type:`button`,onClick:o,children:`Done`})})]})},cO=`This browser keeps no site data for FKN Social. Allow site data, then open the link again.`,lO=({state:e,site:t,onAccept:n,onDecline:r,onSendAgain:i,onDismiss:a,storage:o})=>{let s=e.kind===`friends`||e.kind===`closed`||e.kind===`in-use`||e.kind===`unavailable`,c=e.kind===`accepting`;return Q(`div`,{className:`social-invite`,"data-social-guest":e.kind,children:[Q(`h2`,{children:`An invite to be friends`}),Q(`div`,{className:`social-stack`,role:`status`,children:[e.kind===`joining`&&Q(`p`,{children:`Opening the invite...`}),e.kind===`waiting`&&(e.host===null?Q(`p`,{children:`Waiting for the person who made it to answer...`}):Q(G,{children:[Q(aO,{peer:e.host}),Q(`p`,{children:[`Waiting for `,e.host.name,` to add you.`]})]})),(e.kind===`offered`||e.kind===`accepting`||e.kind===`failed`)&&Q(G,{children:[Q(aO,{peer:{...e.host,displayName:e.profile.displayName},storage:o,avatar:e.profile.avatar??null}),Q(oO,{profile:e.profile,site:t}),e.kind===`failed`&&Q(`p`,{className:`social-error`,role:`alert`,children:e.reason===`no-writer`?cO:nh[e.reason]}),Q(`div`,{className:`social-row`,children:[(e.kind!==`failed`||e.reason!==`no-writer`)&&Q(`button`,{type:`button`,className:`social-primary`,"data-accept":!0,"aria-disabled":c,onClick:()=>{c||n()},children:c?`Accepting...`:e.kind===`failed`?`Try again`:`Accept`}),Q(`button`,{type:`button`,"aria-disabled":c,onClick:()=>{c||r()},children:`Decline`})]})]}),e.kind===`unsent`&&Q(G,{children:[Q(`p`,{className:`social-error`,role:`alert`,children:[e.host.name,` is in your friend list, but your answer did not reach them.`]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:i,children:`Send again`})})]}),e.kind===`friends`&&Q(`p`,{"data-social-done":!0,children:[`You and `,e.host.name,` are now friends.`]}),e.kind===`in-use`&&Q(`p`,{children:`Someone else is already using this invite. Ask for a new link.`}),e.kind===`unavailable`&&Q(`p`,{children:`FKN rooms did not answer. Open the link again in a moment.`}),e.kind===`closed`&&Q(`p`,{children:`This invite is no longer open. Ask for a new link.`})]}),s&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:a,children:`Done`})})]})},uO=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`},{level:`off`,label:`Off`}],dO={activity:`Delete all activity?`,comments:`Delete all comments?`},fO=(e,t)=>Object.keys(dO).filter(n=>pb(e,n)!==`off`&&pb(t,n)===`off`),pO=({layout:e,onPreview:t,onSave:n})=>{let[r,i]=K(e),[a,o]=K(e),[s,c]=K(!1),[l,u]=K(null),[d,f]=K(!1),[p,m]=K(null),h=J(null),g=J(null),_=J(!1),v=e=>{_.current=!0,e?E(!0):m(null)},y=e=>{e!==null&&_.current&&(_.current=!1,e.focus())},b=JSON.stringify(e),[x,S]=K(b);b!==x&&(S(b),b!==JSON.stringify(a)&&(JSON.stringify(r)===JSON.stringify(a)&&i(e),o(e)));let C=e=>{i(e),u(null),f(!1),m(null)},w=(e,t)=>{g.current=`${e}-${t===-1?`up`:`down`}`,C(n=>gb(n,e,t))};gu(()=>{t?.(r)},[r,t]),gu(()=>{if(g.current===null)return;let e=g.current;g.current=null,h.current?.querySelector(`[data-social-move="${e}"]`)?.focus()},[r.sections]);let T=(e,t)=>C(n=>hb(n,e,t)),E=async(e=!1)=>{if(s)return;let t=fO(a,r);if(!e&&t.length>0)return m(t.length>1?`Delete all activity and comments?`:dO[t[0]]);m(null),c(!0);let i=await n(r,a);c(!1),i.ok&&o(r),f(i.ok),u(i.ok?null:nh[i.reason])};return Q(`div`,{className:`social-stack`,"data-social-page-editor":!0,"data-social-theme":r.theme,"data-social-accent":r.accent,children:[Q(`div`,{className:`social-stack`,role:`radiogroup`,"aria-label":`Theme`,children:[Q(`span`,{className:`social-label`,children:`Theme`}),Q(`div`,{className:`social-swatch-row`,children:$y.map(e=>Q(`label`,{className:`social-choice social-tile`,children:[Q(`input`,{type:`radio`,name:`theme`,value:e,checked:r.theme===e,onChange:()=>C(t=>({...t,theme:e}))}),Q(`span`,{className:`social-swatch`,"data-social-theme-swatch":e,style:{background:`linear-gradient(135deg, ${Qy[e].bg} 0% 50%, ${Qy[e].accent} 50% 100%)`},"aria-hidden":`true`}),Q(`span`,{className:`social-choice-label`,children:Qy[e].label})]},e))})]}),Q(`div`,{className:`social-stack`,role:`radiogroup`,"aria-label":`Colour`,children:[Q(`span`,{className:`social-label`,children:`Colour`}),Q(`div`,{className:`social-swatch-row`,children:Zy.map(e=>Q(`label`,{className:`social-choice social-tile`,children:[Q(`input`,{type:`radio`,name:`accent`,value:e,checked:r.accent===e,onChange:()=>C(t=>({...t,accent:e}))}),Q(`span`,{className:`social-swatch`,"data-social-accent":e,"aria-hidden":`true`}),Q(`span`,{className:`social-choice-label`,children:Xy[e].label})]},e))})]}),Q(`span`,{className:`social-label`,children:`Sections`}),Q(`ul`,{className:`social-list`,ref:h,children:r.sections.map((e,t)=>{let n=nb[e.id],i=e=>e===-1?t===0:t===r.sections.length-1;return Q(`li`,{className:`social-section`,"data-social-section":e.id,children:[Q(`div`,{className:`social-section-head`,children:[Q(`span`,{className:`social-choice-label`,children:n}),Q(`div`,{className:`social-section-moves`,children:[[-1,`up`],[1,`down`]].map(([t,r])=>Q(`button`,{type:`button`,"aria-label":`Move ${n} ${r}`,"aria-disabled":i(t),"data-social-move":`${e.id}-${r}`,onClick:()=>{i(t)||w(e.id,t)},children:[Q(t===-1?Km:qm,{}),`Move `,r]},t))})]}),e.id!==`about`&&Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees ${n}`,children:uO.map(({level:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`${e.id}-level`,value:t,checked:e.level===t,onChange:()=>T(e.id,t)}),Q(`span`,{className:`social-choice-label`,children:n})]},t))})]},e.id)})}),Q(uh,{children:l}),p===null?Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-save-layout":!0,ref:y,"aria-disabled":s,onClick:()=>void E(),children:s?`Saving...`:`Save layout`}),d&&Q(`span`,{className:`social-muted`,"data-social-layout-saved":!0,children:`Saved`})]}):Q(`div`,{className:`social-warn`,"data-social-drop-activity":!0,children:[Q(`p`,{children:p}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-social-drop-confirm":!0,onClick:()=>v(!0),children:`Delete`}),Q(`button`,{type:`button`,onClick:()=>v(!1),children:`Cancel`})]})]})]})},mO=(e,t)=>{if(t===``)return;let n=e.at(-1);n?.kind===`text`?e[e.length-1]={kind:`text`,text:n.text+t}:e.push({kind:`text`,text:t})},hO=e=>e===` `||e===` `||e===`
12
+ `||e===`\r`,gO=e=>{if(/\s/.test(e))return null;let t=gf(e);if(t===null)return null;let n=new URL(t);return n.username===``&&n.password===``?t:null},_O=e=>{let t=[],n=[],r=!1,i=0;for(;i<e.length;){if(e[i]==="`"){if(!r){let t=e.indexOf("`",i+1);if(t>i+1){i=t+1;continue}t<0&&(r=!0)}i+=1;continue}if(e[i]===`*`){if(e[i+1]===`*`){let n=i+2;for(;e[n]===`*`;)n+=1;i>0&&!hO(e[i-1])&&t.push(n-2),i=n;continue}i>0&&e[i-1]!==`*`&&!hO(e[i-1])&&n.push(i)}i+=1}return{bold:t,italic:n}},vO=(e,t)=>{let{bold:n,italic:r}=t<2?_O(e):{bold:[],italic:[]},i=0,a=0,o=!1,s=!1,c=[],l=0;for(;l<e.length;){let u=e[l];if(u==="`"){if(!o){let t=e.indexOf("`",l+1);if(t>l+1){c.push({kind:`code`,text:e.slice(l+1,t)}),l=t+1;continue}t<0&&(o=!0)}}else if(u===`[`){let t=l+1;for(;t<e.length;){let n=e[t];if(n===`]`||n===`[`||n===`
13
+ `)break;t+=1}if(e[t]===`]`&&e[t+1]===`(`&&!s){let n=e.indexOf(`)`,t+2);if(n<0)s=!0;else{let r=gO(e.slice(t+2,n));if(r!==null){let i=e.slice(l+1,t).trim()||r;c.push({kind:`link`,label:i,href:r}),l=n+1;continue}}}}else if(t<2&&u===`*`){if(e[l+1]===`*`){if(!hO(e[l+2])){for(;i<n.length&&n[i]<=l+2;)i+=1;if(i<n.length){let r=n[i++];c.push({kind:`strong`,children:vO(e.slice(l+2,r),t+1)}),l=r+2;continue}}}else if(!hO(e[l+1])){for(;a<r.length&&r[a]<=l+1;)a+=1;if(a<r.length){let n=r[a++];c.push({kind:`em`,children:vO(e.slice(l+1,n),t+1)}),l=n+1;continue}}}mO(c,u),l+=1}return c},yO=e=>e.startsWith(`### `)?{level:3,body:e.slice(4)}:e.startsWith(`## `)?{level:2,body:e.slice(3)}:e.startsWith(`# `)?{level:1,body:e.slice(2)}:null,bO=e=>e.startsWith(`- `)||e.startsWith(`* `)?e.slice(2):null,xO=e=>{let t=e.replaceAll(`\r
14
14
  `,`
15
15
  `).split(`
16
- `),n=[],r=null,i=null,a=()=>{if(r===null)return;let e=[];for(let[t,n]of r.entries())t>0&&e.push({kind:`break`}),e.push(...fO(n,0));n.push({kind:`paragraph`,children:e}),r=null},o=()=>{i!==null&&(n.push({kind:`list`,items:i}),i=null)};for(let e of t){if(e.trim()===``){a(),o();continue}let t=pO(e);if(t!==null){a(),o(),n.push({kind:`heading`,level:t.level,children:fO(t.body,0)});continue}let s=mO(e);if(s!==null){a(),i===null&&(i=[]),i.push(fO(s,0));continue}o(),r===null&&(r=[]),r.push(e)}return a(),o(),n},gO=(e,t)=>e.map((e,n)=>{let r=`${t}-${n}`;switch(e.kind){case`text`:return Q(G,{children:e.text},r);case`break`:return Q(`br`,{},r);case`code`:return Q(`code`,{children:e.text},r);case`strong`:return Q(`strong`,{children:gO(e.children,r)},r);case`em`:return Q(`em`,{children:gO(e.children,r)},r);case`link`:return Q(`a`,{className:`social-page-link`,href:e.href,target:`_blank`,rel:`noopener noreferrer nofollow ugc`,children:e.label},r)}}),_O=(e,t)=>{let n=`b-${t}`;switch(e.kind){case`heading`:{let t=gO(e.children,n);return e.level===1?Q(`h3`,{children:t},n):e.level===2?Q(`h4`,{children:t},n):Q(`h5`,{children:t},n)}case`paragraph`:return Q(`p`,{children:gO(e.children,n)},n);case`list`:return Q(`ul`,{children:e.items.map((e,t)=>Q(`li`,{children:gO(e,`${n}-i-${t}`)},`${n}-i-${t}`))},n)}},vO=({text:e})=>Q(`div`,{className:`social-md`,"data-social-markdown":!0,children:_u(()=>hO(e),[e]).map(_O)}),yO={...nh,...oh,...ih},bO=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`},{level:`off`,label:`Off`}],xO=e=>Math.max(1,Math.round(e/1024)).toLocaleString(`en`),SO=(e,t)=>e.kind===`artwork`&&e.items.length>0&&(e.level===`public`&&t!==`public`||e.level===`friends`&&t===`off`),CO=(e,t)=>e.kind===`artwork`&&e.items.length>0&&e.level!==`public`&&t===`public`,wO=e=>Object.fromEntries(e.items.map(e=>[e.picture.url,e.caption??``])),TO={get:()=>Promise.reject(Error(`social: no storage`))},EO=({picture:e,alt:t,storage:n})=>{let r=_h(n??TO,n===void 0?null:e,Op);return n===void 0?null:r===void 0?Q(`span`,{className:`social-skel social-art-thumb-skel`,"data-panel-art-reading":e.url,"aria-hidden":`true`}):r===null?Q(`div`,{className:`social-artwork-missing`,"data-panel-art-missing":e.url,children:`Image unavailable`}):Q(`img`,{className:`social-art-thumb`,src:r,alt:t,"data-panel-art-img":e.url})},DO=({panel:e,index:t,total:n,onMove:r,onRemove:i,onListProblem:a,actions:o,storage:s})=>{let[c,l]=K(e.title),[u,d]=K(e.kind===`text`?e.body:``),[f,p]=K(()=>e.kind===`artwork`?wO(e):{}),[m,h]=K(e.title),[g,_]=K(e.kind===`text`?e.body:``),[v,y]=K(()=>e.kind===`artwork`?JSON.stringify(e.items):``),[b,x]=K(()=>e.kind===`artwork`?wO(e):{});e.title!==m&&(h(e.title),l(e.title));let S=e.kind===`text`?e.body:``;S!==g&&(_(S),d(S));let C=e.kind===`artwork`?JSON.stringify(e.items):``;C!==v&&(y(C),e.kind===`artwork`?(x(wO(e)),p(t=>{let n={};for(let r of e.items){let e=r.picture.url,i=r.caption??``,a=b[e];n[e]=a!==void 0&&Object.hasOwn(t,e)&&t[e]!==a&&i===a?t[e]:i}return n})):x({}));let[w,T]=K(`write`),[E,D]=K(!1),[O,k]=K(!1),[A,j]=K(null),[M,N]=K(null),[P,F]=K(!1),[I,L]=K(!1),[R,ee]=K(null),[te,z]=K(``),ne=J(null),re=J(null),ie=J(null),ae=J(null),oe=J(null);q(()=>()=>{R!==null&&URL.revokeObjectURL(R.url)},[R]);let se=e.kind===`artwork`?e.items.length:0;gu(()=>{oe.current===`level`&&M===null?(oe.current=null,ie.current?.querySelector(`input:checked`)?.focus()):oe.current===`file-or-save`&&R===null&&(oe.current=null,(ne.current??ae.current)?.focus())},[M,e.level,R,se]);let ce=async(e,t=!1)=>{if(E)return;D(!0),j(null),a(null),k(!1);let n=await e();return D(!1),n.ok?(N(null),F(!1),t&&k(!0)):(oe.current=null,n.reason===`sync-failed`&&(N(null),F(!1)),j(yO[n.reason])),n},le=t=>{if(!E){if(j(null),t===e.level){N(null);return}if(SO(e,t)||CO(e,t)){N(t);return}ce(()=>o.setLevel(e.id,t))}},ue=t=>{oe.current=`level`,ce(()=>o.setLevel(e.id,t))},B=()=>{E||(N(null),ie.current?.querySelector(`input:checked`)?.focus())},de=async e=>{if(E){j(`Another change is still saving. Try again in a moment.`);return}D(!0),L(!0),j(null),k(!1);let t=await o.fitArtwork(e);if(D(!1),L(!1),!t.ok){j(yO[t.reason]);return}ee({...t.picture,url:URL.createObjectURL(t.picture.blob)}),z(``)},fe=()=>{oe.current=`file-or-save`,ee(null),z(``)};return Q(`li`,{className:`social-section`,"data-social-panel-card":e.id,"data-social-panel-kind":e.kind,children:[Q(`div`,{className:`social-section-head`,children:[Q(`div`,{className:`social-panel-head-title`,children:[Q(`span`,{className:`social-panel-tag`,children:e.kind===`text`?`Text`:`Artwork`}),Q(`span`,{className:`social-choice-label`,children:e.title})]}),Q(`div`,{className:`social-section-moves`,children:[Q(`button`,{type:`button`,"aria-label":`Move ${e.title} up`,"aria-disabled":E||t===0,"data-panel-move":`${e.id}-up`,onClick:()=>{!E&&t>0&&r(-1)},children:[Q(Km,{}),`Move up`]}),Q(`button`,{type:`button`,"aria-label":`Move ${e.title} down`,"aria-disabled":E||t===n-1,"data-panel-move":`${e.id}-down`,onClick:()=>{!E&&t<n-1&&r(1)},children:[Q(qm,{}),`Move down`]}),Q(`button`,{type:`button`,ref:re,className:`social-danger`,"aria-disabled":E,"data-panel-delete-start":e.id,onClick:()=>{E||F(!0)},children:`Delete`})]})]}),P&&Q(`div`,{className:`social-warn`,"data-panel-delete-confirm":e.id,children:[Q(`p`,{children:e.kind===`artwork`&&e.items.length>0?`Delete this panel and its uploaded artwork from storage?`:`Delete this panel?`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-panel-delete-confirm-btn":!0,"aria-disabled":E,onClick:()=>void ce(i),children:E?`Deleting...`:`Delete panel`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:()=>{E||(F(!1),re.current?.focus())},children:`Cancel`})]})]}),Q(`div`,{className:`social-seg`,ref:ie,role:`radiogroup`,"aria-label":`Who sees ${e.title}`,children:bO.map(({level:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-level-${e.id}`,value:t,checked:(M??e.level)===t,"aria-disabled":E,onChange:()=>le(t)}),Q(`span`,{className:`social-choice-label`,children:n})]},t))}),M!==null&&SO(e,M)&&Q(`div`,{className:`social-warn`,"data-panel-level-confirm":e.id,children:[Q(`p`,{children:e.level===`public`?`Making this artwork panel non-public deletes its uploaded artwork so no public URL stays exposed.`:`Turning this artwork panel off deletes its uploaded artwork from storage.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-panel-level-confirm-btn":!0,"aria-disabled":E,onClick:()=>ue(M),children:E?`Saving...`:`Confirm change`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:B,children:[`Keep `,e.level===`public`?`public`:`for friends`]})]})]}),M!==null&&CO(e,M)&&Q(`div`,{className:`social-invite`,"data-panel-publish-confirm":e.id,children:[Q(`p`,{children:`Making this panel public lets anyone who opens your page see these artwork images.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,ref:lh,"data-panel-publish-confirm-btn":!0,"aria-disabled":E,onClick:()=>ue(`public`),children:E?`Publishing...`:`Make public`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:B,children:[`Keep `,e.level===`friends`?`for friends`:`off`]})]})]}),Q(`label`,{className:`social-label`,children:[`Title`,Q(`input`,{name:`panel-title-${e.id}`,autoComplete:`off`,value:c,onChange:e=>{l(e.currentTarget.value),k(!1),j(null)}})]}),e.kind===`text`?Q(G,{children:[Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Markdown mode for ${e.title}`,children:[`write`,`preview`].map(t=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-mode-${e.id}`,value:t,checked:w===t,onChange:()=>T(t)}),Q(`span`,{className:`social-choice-label`,children:t===`write`?`Write`:`Preview`})]},t))}),w===`write`?Q(G,{children:[Q(`label`,{className:`social-label`,children:[`Markdown text`,Q(`textarea`,{name:`panel-body-${e.id}`,rows:4,value:u,onChange:e=>{d(e.currentTarget.value),k(!1),j(null)}})]}),Q(`span`,{className:`social-muted`,children:[u.length,` / `,um]})]}):Q(`div`,{className:`social-md-preview`,"data-panel-preview":e.id,children:u.trim()?Q(vO,{text:u}):Q(`span`,{className:`social-muted`,children:`Nothing to preview yet.`})}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-panel-save":e.id,"aria-disabled":E,onClick:()=>void ce(()=>o.updateText(e.id,{title:c,body:u}),!0),children:E?`Saving...`:`Save panel`}),O&&Q(`span`,{className:`social-muted`,"data-panel-saved":e.id,children:`Saved`})]})]}):Q(G,{children:[e.items.length>0&&Q(`div`,{className:`social-art-list`,"data-panel-art-items":e.id,children:e.items.map((t,n)=>Q(`div`,{className:`social-art-row`,"data-panel-art-row":t.picture.url,children:[Q(`div`,{className:`social-art-row-head`,children:[Q(`span`,{className:`social-choice-label`,children:[`Artwork `,n+1]}),Q(`button`,{type:`button`,"data-panel-art-remove":t.picture.url,"aria-disabled":E,onClick:()=>void ce(()=>o.removeArtItem(e.id,t.picture.url)),children:`Remove`})]}),Q(EO,{picture:t.picture,alt:f[t.picture.url]?.trim()||`${e.title} artwork ${n+1}`,storage:s}),Q(`label`,{className:`social-label`,children:[`Caption`,Q(`input`,{name:`panel-caption-${e.id}-${n}`,autoComplete:`off`,value:f[t.picture.url]??``,placeholder:`Optional caption`,onChange:e=>{let n=e.currentTarget.value;p(e=>({...e,[t.picture.url]:n})),k(!1),j(null)}})]})]},t.picture.url))}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,ref:ae,className:`social-primary`,"data-panel-save":e.id,"aria-disabled":E,onClick:()=>void ce(()=>o.updateArtwork(e.id,{title:c,captions:f}),!0),children:E?`Saving...`:`Save panel`}),O&&Q(`span`,{className:`social-muted`,"data-panel-saved":e.id,children:`Saved`})]}),e.level===`off`?Q(`p`,{className:`social-muted`,"data-panel-art-off":e.id,children:`Set this panel to Friends or Public to upload artwork.`}):e.items.length<4&&Q(`div`,{className:`social-stack`,children:[Q(`label`,{className:`social-label`,children:[`Add artwork (`,e.items.length,` / `,4,`)`,I?`: resizing...`:``,Q(`input`,{ref:ne,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,"aria-disabled":E,"data-panel-file":e.id,onChange:e=>{let t=e.currentTarget.files?.[0];e.currentTarget.value=``,t&&de(t)}})]}),R!==null&&Q(`div`,{className:`social-stack`,"data-panel-art-preview":e.id,children:[Q(`img`,{className:`social-preview`,src:R.url,alt:`Fitted artwork preview`,"data-panel-art-preview-img":!0}),Q(`p`,{className:`social-muted`,"data-panel-art-preview-size":!0,children:[R.width,` by `,R.height,` pixels, `,xO(R.blob.size),` KB`,R.animated?`, animated`:``]}),Q(`label`,{className:`social-label`,children:[`Caption (optional)`,Q(`input`,{name:`panel-new-caption-${e.id}`,autoComplete:`off`,value:te,onChange:e=>z(e.currentTarget.value)})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,ref:lh,"data-panel-use-art":e.id,"aria-disabled":E,onClick:()=>{if(R===null)return;let t=R;ce(async()=>{let n=await o.addArtItem(e.id,t.blob,te);return(n.ok||n.reason===`sync-failed`)&&fe(),n})},children:`Add artwork`}),Q(`button`,{type:`button`,"data-panel-another-art":e.id,"aria-disabled":E,onClick:()=>{E||fe()},children:`Choose another`})]})]})]})]}),Q(uh,{children:A})]})},OO=({panels:e,actions:t,storage:n})=>{let[r,i]=K(null),[a,o]=K(null),[s,c]=K(null),[l,u]=K(!1),d=J(null),f=J(null),p=J(null),m=J(null),h=J(null),g=J(null),_=J(void 0);gu(()=>{if(g.current!==null){let e=g.current;g.current=null,d.current?.querySelector(`[data-panel-move="${e}"]`)?.focus()}if(_.current!==void 0){let e=_.current;_.current=void 0,e===null?f.current?.focus():(d.current?.querySelector(`[data-panel-delete-start="${e}"]`)??f.current)?.focus()}},[e]);let v=r?.kind??null;gu(()=>{if(v!==null)m.current?.focus();else if(h.current!==null){let e=h.current;h.current=null,(e===`text`?f:p).current?.focus()}},[v]);let y=t=>{if(!(l||e.length>=6)){if(r?.kind===t){m.current?.focus();return}h.current=null,o(null),c(null),i({kind:t,title:``,body:``,level:`friends`,mode:`write`})}},b=async()=>{if(l||r===null)return;let e=r.kind;u(!0),o(null),c(null);let n=e===`text`?await t.addText({title:r.title,body:r.body,level:r.level}):await t.addArtwork({title:r.title,level:r.level});u(!1),n.ok?(h.current=e,i(null)):n.reason===`sync-failed`?(h.current=e,i(null),c(yO[n.reason])):o(yO[n.reason])},x=async(n,r)=>{if(l)return;let i=e.findIndex(e=>e.id===n),a=i+r;if(i<0||a<0||a>=e.length)return;g.current=`${n}-${r===-1?`up`:`down`}`,u(!0),c(null);let o=await t.move(n,r);u(!1),o.ok||(g.current=null,c(yO[o.reason]))},S=async n=>{let r=e.findIndex(e=>e.id===n);_.current=r<0?null:e[r+1]?.id??e[r-1]?.id??null;let i=await t.remove(n);return i.ok||(_.current=void 0,i.reason===`sync-failed`&&c(yO[i.reason])),i};return Q(`div`,{className:`social-stack`,"data-social-panels-editor":!0,children:[Q(`div`,{className:`social-panel-bar`,children:[Q(`p`,{className:`social-muted`,children:`Add Markdown text boxes or artwork showcases. Public panels show on your page; Friends panels stay sealed for friends.`}),Q(`span`,{className:`social-panel-count`,"data-social-panel-count":!0,children:[e.length,` / `,6]})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,ref:f,"aria-pressed":r?.kind===`text`,"data-add-text-panel":!0,"aria-disabled":l||e.length>=6,onClick:()=>y(`text`),children:`Add text panel`}),Q(`button`,{type:`button`,ref:p,"aria-pressed":r?.kind===`artwork`,"data-add-artwork-panel":!0,"aria-disabled":l||e.length>=6,onClick:()=>y(`artwork`),children:`Add artwork panel`})]}),r!==null&&Q(`div`,{className:`social-invite`,"data-social-panel-create":r.kind,children:[Q(`h2`,{children:r.kind===`text`?`New text panel`:`New artwork panel`}),Q(`label`,{className:`social-label`,children:[`Title`,Q(`input`,{name:`panel-new-title`,ref:m,autoComplete:`off`,value:r.title,onChange:e=>{let t=e.currentTarget.value;i(e=>e===null?null:{...e,title:t}),o(null)}})]}),Q(`span`,{className:`social-label`,children:`Who sees it`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees this new panel`,children:bO.map(({level:e,label:t})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-new-level`,value:e,checked:r.level===e,onChange:()=>i(t=>t===null?null:{...t,level:e})}),Q(`span`,{className:`social-choice-label`,children:t})]},e))}),r.kind===`text`&&Q(G,{children:[Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`New panel Markdown mode`,children:[`write`,`preview`].map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-new-mode`,value:e,checked:r.mode===e,onChange:()=>i(t=>t===null?null:{...t,mode:e})}),Q(`span`,{className:`social-choice-label`,children:e===`write`?`Write`:`Preview`})]},e))}),r.mode===`write`?Q(G,{children:[Q(`label`,{className:`social-label`,children:[`Markdown text`,Q(`textarea`,{name:`panel-new-body`,rows:5,value:r.body,onChange:e=>{let t=e.currentTarget.value;i(e=>e===null?null:{...e,body:t}),o(null)}})]}),Q(`div`,{className:`social-muted`,children:[r.body.length,` / `,2e3," - Supports # headings, - lists, **bold**, *italic*, `code`, and [links](https://...)."]})]}):Q(`div`,{className:`social-md-preview`,"data-social-new-preview":!0,children:r.body.trim()?Q(vO,{text:r.body}):Q(`span`,{className:`social-muted`,children:`Nothing to preview yet.`})})]}),Q(uh,{children:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-create-panel":!0,"aria-disabled":l,onClick:()=>void b(),children:l?`Creating...`:`Create panel`}),Q(`button`,{type:`button`,"aria-disabled":l,onClick:()=>{l||(h.current=r.kind,i(null))},children:`Cancel`})]})]},r.kind),Q(uh,{children:s}),e.length===0?Q(`p`,{className:`social-muted`,"data-social-panels-empty":!0,children:`No custom panels yet.`}):Q(`ul`,{className:`social-list`,ref:d,children:e.map((r,i)=>Q(DO,{panel:r,index:i,total:e.length,onMove:e=>void x(r.id,e),onRemove:()=>S(r.id),onListProblem:c,actions:t,storage:n},r.id))})]})},kO={...nh,...rh},AO=e=>e.length<5&&e.at(-1)!==``?[...e,``]:e,jO=e=>({displayName:e.displayName,bio:e.bio,links:AO(e.links)}),MO=({profile:e,onSave:t})=>{let[n,r]=K(()=>jO(e)),[i,a]=K(()=>({displayName:e.displayName,bio:e.bio,links:e.links})),[o,s]=K(!1),[c,l]=K(null),[u,d]=K(!1),f=e=>{r(t=>({...t,...e})),l(null),d(!1)},p=async()=>{if(o)return;s(!0);let e=await t(n,i);s(!1);let r=Cf(n);e.ok&&r.ok&&a(r.profile),d(e.ok),l(e.ok?null:kO[e.reason])};return Q(`div`,{className:`social-stack`,"data-social-profile":!0,children:[Q(`label`,{className:`social-label`,children:[`Display name`,Q(`input`,{name:`display-name`,autoComplete:`off`,value:n.displayName,onChange:e=>f({displayName:e.currentTarget.value})})]}),Q(`label`,{className:`social-label`,children:[`Bio`,Q(`textarea`,{name:`bio`,rows:4,value:n.bio,onChange:e=>f({bio:e.currentTarget.value})})]}),Q(`span`,{className:`social-label`,children:`Links`}),n.links.map((e,t)=>Q(`input`,{name:`link-${t}`,"aria-label":`Link ${t+1}`,autoComplete:`off`,spellcheck:!1,placeholder:`https://`,value:e,onChange:e=>f({links:AO(n.links.map((n,r)=>r===t?e.currentTarget.value:n))})},t)),Q(uh,{children:c}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-save-profile":!0,"aria-disabled":o,onClick:()=>void p(),children:o?`Saving...`:`Save profile`}),u&&Q(`span`,{className:`social-muted`,"data-social-saved":!0,children:`Saved`})]})]})},NO=[{level:`me`,label:`Only me`},{level:`friends`,label:`Friends`},{level:`public`,label:`Public`}],PO=({notice:e,page:t})=>{let n=t.replace(/^https?:\/\//,``);return e===`moved`?Q(`p`,{className:`social-warn`,role:`status`,"data-social-notice":`moved`,children:[`Your old page was taken down. Publish again to show your profile at `,n,`.`]}):e===`old-page-stands`?Q(`p`,{className:`social-muted`,role:`status`,"data-social-notice":`old-page-stands`,children:`Your old page could not be taken down yet. Reload to try again.`}):null},FO=[{slot:`avatar`,label:`Avatar`},{slot:`background`,label:`Background`}],IO=e=>Math.max(1,Math.round(e/1024)).toLocaleString(`en`),LO=({preview:e,busy:t,onUse:n,onAnother:r})=>Q(`div`,{className:`social-stack`,"data-social-preview":e.slot,children:[Q(`img`,{className:e.slot===`avatar`?`social-avatar`:`social-preview`,src:e.url,alt:`Your new ${e.slot}`,"data-social-preview-image":!0}),Q(`p`,{className:`social-muted`,"data-social-preview-size":!0,children:[e.width,` by `,e.height,` pixels, `,IO(e.blob.size),` KB`,e.animated?`, animated`:``]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-use-picture":!0,ref:lh,"aria-disabled":t,onClick:n,children:`Use this picture`}),Q(`button`,{type:`button`,"data-another-picture":!0,"aria-disabled":t,onClick:r,children:`Choose another`})]})]}),RO=`Your page shows nothing: see the warning above.`,zO={lost:RO,taken:RO,retired:RO,unrecorded:`Your page could not be written. Write it again from the warning above.`,unknown:`Your page could not be checked just now. Reload to try again.`},BO={"not-kept":`Your profile page room keeps no messages. Turn on Messages kept for it under Rooms in your FKN settings.`,taken:`Someone else holds your profile page room now.`,"out-of-claims":`Your account is at its claimed room limit, so your profile is kept in your name room. Free a room under Rooms in your FKN settings, then make a page room.`,inline:`Your profile is kept in your name room instead of a separate page room.`,unavailable:`FKN rooms did not answer, so your profile page room has not updated yet.`},VO=({visibility:e,page:t,pictures:n,status:r,pageRoomStatus:i=null,oldPage:a=!1,site:o,actions:s})=>{let[c,l]=K(null),[u,d]=K(!1),[f,p]=K(null),[m,h]=K(null),[g,_]=K(null),v=J(null),y=J(!1),b=e.level,x=t.replace(/^https?:\/\//,``);q(()=>()=>{m!==null&&URL.revokeObjectURL(m.url)},[m]);let S=async(e,t=!1)=>{if(u)return;d(!0),p(null);let n=await e();n.ok&&t&&(y.current=!0),d(!1),n.ok?(l(null),t&&h(null)):p(oh[n.reason])},C=async(e,t)=>{if(u)return;d(!0),_(e),p(null);let n=await s.fitPicture(e,t);if(d(!1),_(null),!n.ok)return p(oh[n.reason]);h({...n.picture,slot:e,url:URL.createObjectURL(n.picture.blob)})},w=e=>{v.current=e,h(null)},T=e=>void S(async()=>{let t=await s.putPicture(e.slot,e.blob);return t.ok&&w(e.slot),t}),E=e=>t=>{t!==null&&v.current===e&&(v.current=null,t.focus())},D=e=>{e!==null&&y.current&&(y.current=!1,(e.querySelector(`input:checked`)??e).focus())},O=e=>{u||(p(null),e===b?l(null):e===`public`||b===`public`||b===`friends`&&e===`me`&&(n.avatar||n.background)?l(e):S(async()=>{let t=await s.setLevel(e);return t.ok&&e===`me`&&h(null),t}))},k=FO.map(({slot:e,label:t})=>Q(`div`,{className:`social-stack`,"data-social-picture":e,"data-social-picture-set":n[e],children:[Q(`label`,{className:`social-label`,children:[t,` picture: `,g===e?`resizing...`:n[e]?`one is set`:`none yet`,Q(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,"aria-disabled":u,"data-picture-input":e,ref:E(e),onChange:t=>{let n=t.currentTarget.files?.[0];t.currentTarget.value=``,n&&C(e,n)}})]}),m?.slot===e&&Q(LO,{preview:m,busy:u,onUse:()=>T(m),onAnother:()=>{u||w(e)}}),n[e]&&m?.slot!==e&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>void S(()=>s.removePicture(e)),children:[`Remove the `,t.toLowerCase()]})})]},e)),A=b===`public`&&c!==null&&c!==`public`?c:null,j=b===`friends`&&c===`me`,M=r===null?void 0:zO[r];return Q(`div`,{className:`social-stack`,"data-social-level":b,children:[Q(`div`,{className:`social-stack`,"data-social-page-link":t,children:[Q(`span`,{className:`social-label`,children:`Your page`}),Q(Ch,{url:t,site:o})]}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees your profile`,ref:b===`public`?void 0:D,children:NO.map(({level:e,label:t})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`visibility`,value:e,checked:(c??b)===e,"aria-disabled":u,onChange:()=>O(e)}),Q(`span`,{className:`social-choice-label`,children:t})]},e))}),c===`public`&&b!==`public`&&Q(`div`,{className:`social-invite`,"data-social-publish":!0,children:[Q(`h2`,{children:`Publish your profile`}),Q(`p`,{className:`social-muted`,children:[`Anyone who opens `,x,` sees your profile and pictures.`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-publish":!0,"aria-disabled":u,onClick:()=>void S(s.publish,!0),children:u?`Publishing...`:`Publish`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Cancel`})]})]}),A!==null&&Q(`div`,{className:`social-warn`,"data-social-unpublish":!0,children:[Q(`p`,{children:[`Unpublishing deletes your pictures and shows your profile only to `,A===`friends`?`your friends`:`you`,`.`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-unpublish":!0,ref:lh,"aria-disabled":u,onClick:()=>void S(()=>s.setLevel(A),!0),children:u?`Unpublishing...`:`Unpublish`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Keep it public`})]})]}),j&&Q(`div`,{className:`social-warn`,"data-social-hide-pictures":!0,children:[Q(`p`,{children:`Switching to Only me deletes your pictures and hides your profile from your friends.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-hide-pictures":!0,ref:lh,"aria-disabled":u,onClick:()=>void S(()=>s.setLevel(`me`),!0),children:u?`Saving...`:`Hide profile`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Keep for friends`})]})]}),b===`friends`&&!a&&Q(`div`,{className:`social-invite`,"data-social-friends-pictures":!0,children:[Q(`h2`,{children:`Profile pictures`}),Q(`p`,{className:`social-muted`,children:`Shown only to your friends. Static images are resized; animated GIF and WebP files keep their motion.`}),k]}),b===`public`&&Q(`div`,{className:`social-invite`,"data-social-public":r??`checking`,children:[Q(`h2`,{tabIndex:-1,ref:D,children:`Your public page`}),M!==void 0&&Q(`p`,{className:`social-warn-text`,role:`status`,"data-social-page-status":!0,children:M}),!a&&Q(G,{children:[Q(`p`,{className:`social-muted`,children:`Static images are resized; animated GIF and WebP files keep their motion.`}),k]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-unpublish-start":!0,"aria-disabled":u,onClick:()=>{u||l(`friends`)},children:`Unpublish`})})]}),i!==null&&BO[i]!==void 0&&Q(`div`,{className:`social-stack`,"data-social-page-room-status":i,children:[Q(`p`,{className:`social-warn-text`,role:`status`,children:BO[i]}),(i===`taken`||i===`out-of-claims`||i===`inline`)&&s.makePage!==void 0&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-make-page":!0,"aria-disabled":u,onClick:()=>void S(s.makePage),children:`Make a page room`})})]}),u&&c===null&&Q(`p`,{className:`social-muted`,role:`status`,children:`Saving...`}),Q(uh,{children:f})]})},HO=e=>X(e)??new Uint8Array(32),UO=(e,t)=>t==null?e.profile.avatar??null:t.avatar,WO=(e,t)=>{if(e.ok)return``;switch(e.reason){case`invalid`:return`Enter a message before sending.`;case`no-room`:return`Set up your messages room first.`;case`out-of-claims`:return`No messages room: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`;case`not-active`:return`You left this group.`;case`no-peer-room`:return t?`${t} has not opened Messages yet.`:`A group member has not opened Messages yet.`;case`unavailable`:return`Could not deliver right now. Try again in a moment.`;default:return nh[e.reason]}},GO=e=>{switch(e){case`none`:return{text:`Messages are not set up on this account yet.`,button:`Set up messages`};case`out-of-claims`:return{text:`No messages room: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`,button:`Set up messages`};case`taken`:return{text:`Your messages room is held under another session or account. Make a new messages room to continue.`,button:`Make a new messages room`};case`not-kept`:return{text:`Messages kept is turned off on your messages room in FKN settings.`,button:`Make a new messages room`};case`unavailable`:return{text:`FKN rooms did not answer right now. Try again in a moment.`,button:null};default:return null}},KO=(e,t)=>e.reduce((e,n)=>e+ +(!n.self&&n.seq>t),0),qO=e=>e.kind===`dm`?`dm:${e.fingerprint}`:`group:${e.groupId}`,JO=(e,t,n,r)=>{let i=0;for(let n of e)i+=KO(t[n.fingerprint]??[],r[`dm:${n.fingerprint}`]??0);for(let e of n)i+=KO(e.messages,r[`group:${e.id}`]??0);return i},YO=({status:e,friends:t,friendProfiles:n,storage:r,directMessages:i,groups:a,selected:o,onSelect:s,readCursors:c,actions:l})=>{let[u,d]=K(``),[f,p]=K(!1),[m,h]=K(null),[g,_]=K(!1),[v,y]=K(!1),[b,x]=K(``),[S,C]=K([]),[w,T]=K(!1),[E,D]=K(!1),O=J(null),k=new Map(t.map(e=>[e.fingerprint,e])),A=o?.kind===`dm`?k.get(o.fingerprint)??null:null,j=o?.kind===`group`?a.find(e=>e.id===o.groupId)??null:null,M=A===null?j===null?[]:j.messages:i[A.fingerprint]??[];q(()=>{h(null),T(!1),D(!1)},[o?.kind,o?.kind===`dm`?o.fingerprint:o?.groupId]),q(()=>{O.current!==null&&(O.current.scrollTop=O.current.scrollHeight)},[M.length,A?.fingerprint,j?.id]);let N=GO(e),P=[...t].sort((e,t)=>{let r=(i[e.fingerprint]??[]).at(-1)?.at??0;return((i[t.fingerprint]??[]).at(-1)?.at??0)-r||nD(e,n?.[e.fingerprint]).localeCompare(nD(t,n?.[t.fingerprint]))}),F=async()=>{if(g)return;_(!0),h(null);let e=await l.makeRoom();_(!1),e.ok||h(e.reason===`out-of-claims`?WO({ok:!1,reason:`out-of-claims`}):e.reason===`unavailable`||e.reason===`busy`?`Could not set up messages right now. Try again in a moment.`:nh[e.reason])},I=async()=>{if(f||u.trim()===``)return;p(!0),h(null);let e=A===null?j===null?{ok:!1,reason:`invalid`}:await l.sendGroup(j.id,u):await l.sendDirect(A,u);p(!1),e.ok?d(``):h(WO(e,A?.name))},L=async()=>{if(f)return;let e=t.filter(e=>S.includes(e.fingerprint));if(b.trim()===``||e.length===0){h(`Enter a group name and pick at least one friend.`);return}p(!0),h(null);let n=await l.createGroup(b,e);p(!1),n.ok&&n.groupId?(y(!1),x(``),C([]),s({kind:`group`,groupId:n.groupId})):n.ok||h(WO(n))},R=e=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},ee=async e=>{if(f||j===null)return;p(!0),h(null);let t=await l.addToGroup(j.id,e);p(!1),t.ok?T(!1):h(WO(t,e.name))},te=async()=>{if(f||j===null)return;p(!0),h(null);let e=await l.leaveGroup(j.id);p(!1),e.ok?D(!1):h(WO(e))},z=j===null?[]:t.filter(e=>!j.members.some(t=>t.fingerprint===e.fingerprint));return Q(`div`,{className:`social-stack`,"data-social-messages":!0,"data-social-chat-status":e??`loading`,children:[N!==null&&Q(`div`,{className:`social-card-box`,"data-social-chat-setup":!0,children:[Q(`p`,{className:e===`unavailable`?`social-muted`:`social-warn-text`,children:N.text}),N.button!==null&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-make-chat":!0,"aria-disabled":g,onClick:()=>void F(),children:g?`Setting up...`:N.button})})]}),Q(`div`,{className:`social-chat-shell`,children:[Q(`aside`,{className:`social-chat-list card social-card-box`,"aria-label":`Conversations`,children:[Q(`div`,{className:`social-link-bar`,children:[Q(`h2`,{children:`Conversations`}),t.length>0&&Q(`button`,{type:`button`,"data-social-new-group":!0,onClick:()=>{y(e=>!e),h(null)},children:v?`Cancel`:`New group`})]}),v&&Q(`div`,{className:`social-invite`,"data-social-group-creator":!0,children:[Q(`label`,{className:`social-label`,children:[`Group name`,Q(`input`,{name:`group-title`,autoComplete:`off`,maxLength:80,value:b,onChange:e=>x(e.currentTarget.value)})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Members`}),Q(`div`,{className:`social-checks`,children:t.map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`checkbox`,checked:S.includes(e.fingerprint),onChange:()=>R(e.fingerprint)}),Q(`span`,{className:`social-choice-label`,children:nD(e,n?.[e.fingerprint])})]},e.fingerprint))})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-create-group":!0,"aria-disabled":f||b.trim()===``||S.length===0,onClick:()=>void L(),children:`Create group`})})]}),a.length===0&&t.length===0?Q(`p`,{className:`social-muted`,children:`Add a friend first to start private or group conversations.`}):Q(`ul`,{className:`social-list`,children:[a.map(e=>{let t=e.messages.at(-1),r=t===void 0?``:t.self?t.senderName:(()=>{let e=k.get(t.senderFingerprint);return e?nD(e,n?.[e.fingerprint]):t.senderName})(),i=KO(e.messages,c[`group:${e.id}`]??0),a=o?.kind===`group`&&o.groupId===e.id;return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-chat-item`,"data-social-thread":`group:${e.id}`,"aria-current":a?`true`:void 0,onClick:()=>s({kind:`group`,groupId:e.id}),children:Q(`div`,{className:`social-chat-item-body`,children:[Q(`div`,{className:`social-chat-item-head`,children:[Q(`span`,{className:`social-person-name`,children:e.title}),i>0&&Q(`span`,{className:`social-nav-badge social-nav-badge-accent`,children:i})]}),Q(`span`,{className:`social-muted`,children:t?`${r}: ${t.body.slice(0,48)}`:`${e.members.length} members`})]})})},e.id)}),P.map(e=>{let t=n?.[e.fingerprint],a=nD(e,t),l=i[e.fingerprint]??[],u=l.at(-1),d=KO(l,c[`dm:${e.fingerprint}`]??0),f=o?.kind===`dm`&&o.fingerprint===e.fingerprint;return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-chat-item`,"data-social-thread":`dm:${e.name}`,"aria-current":f?`true`:void 0,onClick:()=>s({kind:`dm`,fingerprint:e.fingerprint}),children:[Q(bh,{signKey:HO(e.signKey),name:e.name,storage:r,avatar:UO(e,t),small:!0}),Q(`div`,{className:`social-chat-item-body`,children:[Q(`div`,{className:`social-chat-item-head`,children:[Q(`span`,{className:`social-person-name`,children:a}),d>0&&Q(`span`,{className:`social-nav-badge social-nav-badge-accent`,children:d})]}),Q(`span`,{className:`social-muted`,children:u?u.body.slice(0,48):e.name})]})]})},e.fingerprint)})]})]}),Q(`section`,{className:`social-chat-thread social-card-box`,"aria-label":`Conversation`,children:A===null&&j===null?Q(`p`,{className:`social-muted`,"data-social-chat-empty":!0,children:`Pick a conversation on the left, or start a new group chat.`}):Q(G,{children:[Q(`div`,{className:`social-main-head`,"data-social-thread-head":!0,children:[Q(`div`,{children:[Q(`h2`,{children:A===null?j?.title:nD(A,n?.[A.fingerprint])}),Q(`span`,{className:`social-muted`,children:A===null?j?.members.map(e=>e.name).join(`, `):A.name})]}),j!==null&&j.active&&Q(`div`,{className:`social-row`,children:[z.length>0&&Q(`button`,{type:`button`,"data-social-group-add-toggle":!0,onClick:()=>T(e=>!e),children:w?`Cancel`:`Add friend`}),E?Q(G,{children:[Q(`button`,{type:`button`,className:`social-danger`,"data-social-leave-confirm":!0,"aria-disabled":f,onClick:()=>void te(),children:`Confirm leave`}),Q(`button`,{type:`button`,"aria-disabled":f,onClick:()=>D(!1),children:`Cancel`})]}):Q(`button`,{type:`button`,"data-social-leave-group":!0,"aria-disabled":f,onClick:()=>D(!0),children:`Leave group`})]})]}),j!==null&&w&&z.length>0&&Q(`div`,{className:`social-invite`,"data-social-group-add":!0,children:[Q(`span`,{className:`social-label`,children:[`Add friend to `,j.title]}),Q(`div`,{className:`social-row`,children:z.map(e=>Q(`button`,{type:`button`,"data-social-add-group-member":e.name,"aria-disabled":f,onClick:()=>void ee(e),children:nD(e,n?.[e.fingerprint])},e.fingerprint))})]}),Q(`div`,{className:`social-chat-log`,ref:O,"data-social-chat-log":!0,children:M.length===0?Q(`p`,{className:`social-muted`,children:`No messages yet.`}):M.map(e=>{let t=e.self?void 0:k.get(e.senderFingerprint),r=t?nD(t,n?.[t.fingerprint]):e.senderName;return Q(`article`,{className:e.self?`social-chat-msg social-chat-msg-self`:`social-chat-msg`,"data-social-msg":e.id,children:[Q(`div`,{className:`social-chat-msg-meta`,children:[Q(`strong`,{children:r}),Q(`span`,{className:`social-muted`,children:new Date(e.at).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})})]}),Q(`p`,{className:`social-bio`,children:e.body})]},e.id)})}),j!==null&&!j.active?Q(`p`,{className:`social-muted`,"data-social-group-left":!0,children:`You left this group.`}):Q(`div`,{className:`social-chat-composer`,children:[Q(`label`,{className:`social-label`,children:[`Message`,Q(`textarea`,{name:`chat-message`,rows:2,maxLength:BS,value:u,onChange:e=>d(e.currentTarget.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),I())}})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-send-chat":!0,"aria-disabled":f||u.trim()===``,onClick:()=>void I(),children:f?`Sending...`:`Send`})})]}),Q(uh,{children:m})]})})]})]})},XO=1e4,ZO=e=>`${e.inbox}\0${e.seq}\0${e.sender.fingerprint}\0${e.sender.name}`,QO=e=>e.filter(({path:e})=>e===`v1/roster.json`||Jf(e)!==null).sort((e,t)=>e.path.localeCompare(t.path)).map(({path:e,updatedAt:t})=>`${e}:${t}`).join(`
17
- `),$O=e=>JSON.stringify({p:e.profile,f:e.friends,a:e.apps}),ek=e=>{if(typeof localStorage>`u`)return{};try{let t=localStorage.getItem(e);if(t===null)return{};let n=JSON.parse(t);if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n))typeof t==`number`&&Number.isSafeInteger(t)&&t>=0&&(r[e]=t);return r}catch{return{}}},tk=(e,t)=>{if(typeof localStorage<`u`)try{localStorage.setItem(e,JSON.stringify(t))}catch{}},nk=()=>null,rk=e=>Object.keys(e.apps).sort().flatMap(t=>{let n=jT(e,t);return n===null?[]:[{app:t,grant:n}]}),ik=(e,t)=>e.inbox===t.inbox&&e.seq===t.seq,ak=e=>{let[t,n]=K(e.state);return q(()=>(n(e.state()),e.on(n)),[e]),t},ok=({invite:e,onDismiss:t})=>{let n=ak(e);return Q(tO,{link:e.link,expiresAt:e.expiresAt,state:n,onAdd:e.add,onClose:()=>void e.close(),onSaveAgain:()=>void e.saveAgain(),onDismiss:t})},sk=({invite:e,site:t,onDismiss:n,storage:r})=>Q(rO,{state:ak(e),site:t,storage:r,onAccept:()=>void e.accept(),onDecline:()=>{e.decline(),n()},onSendAgain:()=>void e.sendAgain(),onDismiss:n}),ck={me:`Only me`,friends:`Friends`,public:`Public`},lk=Symbol(`watch-unstarted`),uk=Symbol(`watch-creating`),dk=({services:e,identity:t,listed:n,fresh:r,cutShort:i,onChanged:a,site:o,staged:s,onStagedTaken:c,adding:l,onAddDone:u,onAdd:d,editing:f,onEditDone:p,route:m,onRosterChange:h,resolveAppName:g,pollIntervalMs:_=XO})=>{let[v,y]=K(null),[b,x]=K(null),[S,C]=K(null),[w,T]=K([]),[E,D]=K(null),[O,k]=K(!1),A=o()!==null,j=!f&&s===null&&l===void 0&&!r&&m!==null,[M,N]=K(()=>f?`customize`:s!==null||l!==void 0?`friends`:r?`account`:m===null||m.tab===`apps`&&!A?`overview`:m.tab),[P,F]=K(()=>f?`layout`:j&&m.tab===`customize`?m.customizeTab:`general`),[I,L]=K(()=>j&&m.tab===`messages`&&m.groupId!==void 0?{kind:`group`,groupId:m.groupId}:null),R=J(j&&m.tab===`friends`?m.friendName??null:null),ee=J(j&&m.tab===`messages`?m.peerName??null:null),te=J(null),z=J(null),ne=J(m),re=J(`replace`),ie=J(null),ae=J({tab:M,customizeTab:P,viewing:S,chatKey:I===null?null:qO(I)});ae.current={tab:M,customizeTab:P,viewing:S,chatKey:I===null?null:qO(I)};let[oe,se]=K(!1),[ce,le]=K(null);q(()=>{(M!==`customize`||P!==`layout`)&&le(null)},[M,P]);let ue=J(null),B=_u(()=>lx(t.seed),[t.seed]),[de,fe]=K({}),pe=J(0),me=J(new Set),he=J([]),ge=J(0);q(()=>(pe.current+=1,me.current.clear(),he.current=[],ge.current=0,fe({}),()=>{pe.current+=1,he.current=[]}),[e]);let _e=J(null);q(()=>{let e=new Set;return _e.current=e,()=>{_e.current=null;for(let t of e)t()}},[]);let V=e=>_e.current!==null&&(_e.current.add(e),!0),ve=J(!0);q(()=>(ve.current=!0,()=>{ve.current=!1}),[]);let ye=J(null),be=J(null),xe=J(null),[Se,Ce]=K(!1),H=vu(e=>(e.ok&&(ye.current=e.roster,be.current=$O(e.roster),y(e.roster),$e.current?.refreshRoster(e.roster)),x(e.ok?null:nh[e.reason]),Ce(!e.ok&&e.reason===`reset`),e),[]),[we,Te]=K(!1),Ee=vu(async t=>{H(await(t??cp(e))),Te(!0)},[e,H]),De=J(n);q(()=>{Ee(De.current??void 0)},[Ee]);let Oe=J(Promise.resolve()),ke=vu(e=>{let t=Oe.current.then(e,e);return Oe.current=t.catch(()=>{}),t},[]),[Ae,je]=K(null),[Me,Ne]=K(null),Pe=J(null),Fe=J(null),[Ie,Le]=K(null),Re=_u(()=>({keys:B,name:t.name}),[B,t.name]),[ze,Be]=K(null),Ve=J(!1),He=J(!1),Ue=J(null),We=J(lk),Ge=J(null),Ke=J(new Map),[qe,Je]=K(0),[Ye,Xe]=K(null),[Ze,Qe]=K({directMessages:{},groups:[]}),$e=J(null),et=J(lk),[tt,nt]=K(0),rt=v===null?void 0:MC(v),it=_u(()=>typeof rt==`string`?`fkn.social.chat-read.${cf(B.signKey)}.${qy(rt)}`:`fkn.social.chat-read.${cf(B.signKey)}`,[B,rt]),[at,ot]=K(()=>ek(it));q(()=>{ot(ek(it))},[it]);let st=async t=>{let n=await cp(e);return n.ok?(H(n),t(ST(n.roster,He.current))):{ok:!1,reason:n.reason===`reset`?`list-reset`:n.reason}},ct=vu(async(t=!1)=>{let n=ye.current;if(n!==null&&gT(n)!==null){let t=await kT(e,n);Le(t.ok?`moved`:`old-page-stands`),t.ok&&(H(t),n=t.roster)}let r=n===null?null:Ve.current?{roster:n,inboxTaken:He.current}:(async e=>{Ve.current=!0;let t=Ge.current===null?{status:`unavailable`,inboxTaken:!1}:await Ge.current;return ve.current?(He.current=t.inboxTaken,{roster:ye.current??t.roster??e,inboxTaken:He.current}):{roster:e,inboxTaken:!1}})(n),i=await CT(e,Re,r,{lastNameStatus:Pe.current,lastCoreKey:Fe.current,skipNameIfUnchanged:!t});return i.roster!==void 0&&H({ok:!0,roster:i.roster}),Pe.current=i.status,Fe.current=i.coreKey,je(i.status),Ne(i.pageStatus),i},[e,Re,H]),lt=vu(()=>ke(async()=>{await ct(!1)}),[ke,ct]),ut=vu(()=>ke(async()=>{await ct(!0)}),[ke,ct]),dt=v!==null,ft=v===null?void 0:dw(v);q(()=>{if(!we||!dt||ye.current===null){We.current=lk,Ge.current=null;return}let t=dw(ye.current);if(t===null){We.current=null,He.current=!1,Be(e=>({status:`none`,waiting:[],accepted:e?.accepted??[]})),Ge.current=Promise.resolve({status:`none`,inboxTaken:!1});return}let n=!0;We.current=t??uk;let r=gw(e,B,()=>ye.current??Lf(),{onStatus:e=>{n&&(He.current=e===`taken`,Be(t=>({status:e,waiting:t?.waiting??[],accepted:t?.accepted??[]})))},onRoster:e=>{if(!n)return;We.current=dw(e)??uk;let t=be.current,r=$O(e);H({ok:!0,roster:e}),Ve.current&&t!==null&&r!==t&&lt()},onAccepted:e=>{n&&e.length!==0&&Be(t=>{let n=t??{status:`ready`,waiting:[],accepted:[]},r=[...n.accepted];for(let t of e)r.includes(t)||r.push(t);return{...n,accepted:r}})},onWaiting:t=>{if(!n)return;let r=t.map(e=>{let t=ZO(e),n=Ke.current.get(t);return n===void 0?e:{...e,sender:{...e.sender,confirmed:n}}});Be(e=>({status:e?.status??`ready`,waiting:r,accepted:e?.accepted??[]}));for(let r of t){let t=ZO(r);Ke.current.has(t)||(Ke.current.set(t,null),eS(e.rooms,r.sender.name,r.sender.signKey).then(e=>{Ke.current.set(t,e),n&&Be(t=>t===null?t:{...t,waiting:t.waiting.map(t=>ik(t,r)?{...t,sender:{...t.sender,confirmed:e}}:t)})}))}}});return Ue.current=r,Ge.current=r.ready,()=>{n=!1,Ue.current===r&&(Ue.current=null),r.leave()}},[we,dt,qe,e,B,H,lt]),q(()=>{if(!we||!dt||We.current===lk)return;let e=ft===void 0?uk:ft;We.current!==e&&Je(e=>e+1)},[we,dt,ft]);let pt=J(!1),mt=J(!1),ht=vu(async(t=!1)=>{if(we&&ve.current){if(pt.current){t&&(mt.current=!0);return}if(t||typeof document>`u`||document.visibilityState!==`hidden`){pt.current=!0;try{let n=await e.cloud.list();if(!ve.current)return;let r=QO(n);if(!t&&xe.current!==null&&r===xe.current)return;xe.current=r;let i=await cp(e);if(!ve.current)return;if(!i.ok){H(i);return}let a=be.current,o=$O(i.roster);H(i),a!==null&&o!==a&&lt()}catch{}finally{pt.current=!1,mt.current&&ve.current&&(mt.current=!1,ht(!0))}}}},[we,e,H,lt]);q(()=>h?.(()=>{ht(!0)}),[h,ht]),q(()=>{if(!we)return;let e=()=>{ht(!1)},t=()=>{document.visibilityState===`visible`&&ht(!1)};window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,t);let n=_>0?window.setInterval(()=>{ht(!1)},_):void 0;return()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,t),n!==void 0&&window.clearInterval(n)}},[we,_,ht]),q(()=>{we&&ut()},[we,ut]);let gt={claimAgain:async()=>{let n=await ke(()=>st(n=>$w(e,t,n)));return await ut(),n},rename:async t=>{let n=await ke(()=>st(n=>Zw(e,t,n)));return n.ok&&await a(),n},giveBack:t=>Qw(e,t)},_t=e=>{H({ok:!0,roster:e.roster}),Pe.current=e.status,je(e.status),e.pageStatus!==void 0&&Ne(e.pageStatus);let t=Ow(e.roster);Fe.current=typeof t==`string`?xT(bT(e.roster,t,He.current)):null},vt={setLevel:t=>ke(async()=>{if(ye.current===null)return{ok:!1,reason:`unavailable`};let n=await OT(e,Re,ye.current,t,He.current);return n.ok?(_t(n),{ok:!0}):(n.pageStatus!==void 0&&Ne(n.pageStatus),n)}),publish:()=>ke(async()=>{let t=await ET(e,Re,He.current);return t.ok?(_t(t),Le(null),{ok:!0}):t}),fitPicture:(e,t)=>cm(t,e,lm),putPicture:async(t,n)=>{let r=await ke(()=>Yp(e,t,n));return r.ok?(H(r),await lt(),{ok:!0}):r},removePicture:async t=>{let n=await ke(()=>Xp(e,t));return n.ok?(H(n),await lt(),{ok:!0}):n},makePage:()=>ke(async()=>{if(ye.current===null)return{ok:!1,reason:`unavailable`};let t=ye.current,n=Ow(t)??void 0,r;if(n===void 0){let t=await Zx(e.rooms,B,Re.name);if(t===null)return{ok:!1,reason:`unavailable`};r=Nw(t)}let i=await Pw(e,B,vT(t),r,n);return i.roster!==void 0&&H({ok:!0,roster:i.roster}),i.ok?(await ct(!0)).pageStatus===`ready`?{ok:!0}:{ok:!1,reason:`unavailable`}:(i.reason===`out-of-claims`&&Ne(`out-of-claims`),{ok:!1,reason:i.reason})})},yt=e=>e.pageStatus===`ready`||(e.pageStatus===`inline`||e.pageStatus===`unused`||e.pageStatus===`out-of-claims`)&&e.status===`held`,bt=async e=>{if(!e.ok)return e;`roster`in e&&H(e);let t=await ct(!1).catch(()=>null);return t!==null&&yt(t)?{ok:!0}:{ok:!1,reason:`sync-failed`}},xt=async({outcome:t,dropped:n})=>{if(!t.ok)return t;H(t);let r=null;try{r=await ct(!1)}catch{r=null}finally{await qp(e.storage,n)}return r!==null&&yt(r)?{ok:!0}:{ok:!1,reason:`sync-failed`}},St={addText:t=>ke(async()=>bt(await Nm(e,t))),addArtwork:t=>ke(async()=>bt(await Pm(e,t))),updateText:(t,n)=>ke(async()=>bt(await Fm(e,t,n))),updateArtwork:(t,n)=>ke(async()=>bt(await Im(e,t,n))),move:(t,n)=>ke(async()=>bt(await Lm(e,t,n))),setLevel:(t,n)=>ke(async()=>xt(await Rm(e,t,n))),remove:t=>ke(async()=>xt(await zm(e,t))),fitArtwork:e=>cm(e,`artwork`,lm),addArtItem:(t,n,r)=>ke(async()=>bt(await Bm(e,t,n,r))),removeArtItem:(t,n)=>ke(async()=>xt(await Vm(e,t,n)))},Ct=e=>({keys:B,name:t.name,profile:Tf(e),inbox:He.current?null:dw(e)??null,chatRoom:Ye===`taken`?null:MC(e)??null}),wt=async()=>{let t=He.current&&ye.current!==null?dw(ye.current):void 0,n=await ke(()=>fw(e,typeof t==`string`?t:void 0));return n.roster!==void 0&&H({ok:!0,roster:n.roster}),n.ok&&(He.current=!1,Be({status:`ready`,waiting:ze?.waiting??[],accepted:ze?.accepted??[]}),await lt()),n},Tt=e=>Be(t=>t===null?t:{...t,waiting:t.waiting.filter(t=>!ik(t,e))}),Et=()=>{let e=Ue.current;return e===null?void 0:(t,n)=>e.delete(n)},Dt={answer:async(t,n)=>{if(ye.current===null)return{ok:!1,reason:`unreachable`};let r=await xw(e,Ct(ye.current),t,n,Et());return r.roster!==void 0&&H({ok:!0,roster:r.roster}),r.ok&&Tt(t),r.ok&&n&&lt(),r},dismiss:async t=>{await Cw(e,t,Et()),Tt(t)},approve:async t=>{let n=await ke(()=>TT(e,Re,t,Et()));return n&&Tt(t),n}},Ot=vu(t=>rS(e.rooms,t),[e]),kt=t=>ke(async()=>{let n=await cp(e);if(!n.ok)return n;let r=await bw(e,Ct(n.roster),t);return Ee(),r}),At=e=>t=>e.friends[t]?.value.state===`active`,jt=e=>e.on(e=>{e.kind===`friends`&&Ee().then(lt)});q(()=>{if(s===null||v===null||ue.current===s)return;ue.current=s,c();let t=_E(e,Ct(v),s,At(v));V(t.decline),jt(t),D(t)});let Mt=async()=>{if(v===null||O||w.length>=3)return;k(!0);let t=await hE(e,Ct(v),At(v));if(k(!1),!t.ok)return x(t.reason===`no-writer`?nh[`no-writer`]:`No invite was made. Try again in a moment.`);if(!V(t.invite.close))return void t.invite.close();jt(t.invite),T(e=>[...e,t.invite])},Nt=t=>ke(async()=>await wT(e,Re,t)===`written`?null:ah),Pt={change:async(t,n)=>{if(`level`in n&&n.level===`friends`){let e=await Nt(e=>Gh(e,t));if(e!==null)return e}let r=await RT(e,t,n);return r.ok?(H(r),lt(),null):nh[r.reason]},remove:e=>Nt(t=>Wh(t,e))},Ft=J(null),[It,Lt]=K(!1);q(()=>{It&&(Ft.current?.focus(),Lt(!1))},[It]),q(()=>{f&&(N(`customize`),F(`layout`))},[f]),q(()=>{(s!==null||l!==void 0)&&N(`friends`)},[s,l]);let Rt=o()!==null,zt=_u(()=>v===null||!Rt?[]:rk(v),[v,Rt]),Bt=zt.filter(({grant:e})=>e.state===`asked`),Vt=zt.filter(({grant:e})=>e.state!==`asked`),[Ht,Ut]=K({}),Wt=J(new Set),Gt=J(0);q(()=>{Gt.current+=1,Wt.current.clear(),Ut({})},[g]),q(()=>{if(!g||!Rt||zt.length===0)return;let e=Gt.current;for(let{app:t}of zt)Yh(t)&&!Wt.current.has(t)&&(Wt.current.add(t),g(t).then(n=>{Gt.current===e&&ve.current&&Ut(e=>e[t]===n?e:{...e,[t]:n})}))},[g,Rt,zt]);let Kt=_u(()=>v===null?[]:Hf(v),[v]),qt=Kt.find(e=>e.fingerprint===S)??null,Jt=we&&dt&&ye.current!==null&&(M===`messages`||Kt.length>0||typeof rt==`string`);q(()=>{if(!Jt||ye.current===null){et.current=lk,$e.current=null;return}let n=MC(ye.current);if(n===null){et.current=null,$e.current=null,Xe(`none`);return}let r=!0;et.current=n??uk;let i=IC(e,B,t.name,()=>ye.current??Lf(),{onStatus:e=>{r&&Xe(e)},onRoster:e=>{if(!r)return;let t=ye.current===null?void 0:MC(ye.current),n=MC(e);et.current=n??uk,H({ok:!0,roster:e}),t!==n&&Ve.current&&lt()},onUpdate:e=>{r&&Qe(e)}});return $e.current=i,()=>{r=!1,$e.current===i&&($e.current=null),i.leave()}},[Jt,tt,e,B,t.name,H,lt]),q(()=>{if(!Jt||et.current===lk)return;let e=rt===void 0?uk:rt;et.current!==e&&nt(e=>e+1)},[Jt,rt]),q(()=>{if(m===null||m===ne.current)return;ne.current=m;let e=ae.current;if(m.tab===`apps`&&!Rt){R.current=null,ee.current=null,te.current=null,z.current=null,e.tab===`overview`&&e.viewing===null&&e.chatKey===null?(re.current=`push`,ie.current=`/overview`,o()?.navigate?.(`/overview`,!0)):(ie.current=jS(m),re.current=`replace`,N(`overview`),C(null),L(null));return}let t=jS(m),n=!1,r=!1,i=e.customizeTab,a=null,s=null;if(m.tab===`customize`&&(i=m.customizeTab),m.tab===`friends`){if(ee.current=null,z.current=null,m.friendName===void 0)R.current=null,te.current=null;else if(v!==null){let e=Hf(v).find(e=>e.name===m.friendName)??null;R.current=null,te.current=null,a=e?.fingerprint??null,e===null&&(n=!0)}else r=!0,R.current=m.friendName,te.current=null}else if(m.tab===`messages`){if(R.current=null,te.current=null,m.groupId!==void 0)ee.current=null,z.current=null,s={kind:`group`,groupId:m.groupId};else if(m.peerName!==void 0){if(v!==null){let e=Hf(v).find(e=>e.name===m.peerName)??null;ee.current=null,z.current=null,s=e===null?null:{kind:`dm`,fingerprint:e.fingerprint},e===null&&(n=!0)}else r=!0,ee.current=m.peerName,z.current=null}else ee.current=null,z.current=null}else R.current=null,ee.current=null,te.current=null,z.current=null;let c=s===null?null:qO(s),l=m.tab!==e.tab||i!==e.customizeTab||a!==e.viewing||c!==e.chatKey;if(n){if(ie.current=t,l)re.current=`replace`;else{let e=m.tab===`friends`?`/friends`:`/messages`;re.current=`push`,ie.current=e,o()?.navigate?.(e,!0)}}else!r&&ie.current!==null?(ie.current=t,re.current=`push`):re.current=l||ie.current===null?`suppress`:`push`;N(m.tab),m.tab===`customize`&&F(i),C(a),L(s)},[m,Rt,v,o]),q(()=>{if(v!==null){if(R.current!==null){let e=R.current;R.current=null;let t=(Hf(v).find(t=>t.name===e)??null)?.fingerprint??null;re.current=`replace`,S!==t&&(te.current={target:t},C(t))}if(ee.current!==null){let e=ee.current;ee.current=null;let t=Hf(v).find(t=>t.name===e)??null,n=t===null?null:{kind:`dm`,fingerprint:t.fingerprint};re.current=`replace`,(I===null?null:qO(I))!==(n===null?null:qO(n))&&(z.current={target:n},L(n))}}},[v,S,I]),q(()=>{if((R.current!==null||ee.current!==null)&&v===null)return;if(te.current!==null){if(S!==te.current.target)return;te.current=null}if(z.current!==null){let e=z.current.target===null?null:qO(z.current.target);if((I===null?null:qO(I))!==e)return;z.current=null}let e=M===`messages`&&I?.kind===`dm`?Kt.find(e=>e.fingerprint===I.fingerprint)?.name:void 0,t=M===`messages`&&I?.kind===`group`?I.groupId:void 0,n=jS(M===`customize`?{tab:`customize`,customizeTab:P}:M===`friends`?{tab:`friends`,...qt===null?{}:{friendName:qt.name}}:M===`messages`?{tab:`messages`,...t===void 0?e===void 0?{}:{peerName:e}:{groupId:t}}:{tab:M}),r=re.current;if(re.current=`push`,ie.current===null){ie.current=n,r!==`suppress`&&o()?.navigate?.(n,!0);return}if(r===`suppress`){ie.current=n;return}n!==ie.current&&(ie.current=n,o()?.navigate?.(n,r===`replace`))},[M,P,qt,Kt,I,v,S,o]),q(()=>{if(M!==`messages`||I===null)return;let e=(I.kind===`dm`?Ze.directMessages[I.fingerprint]??[]:Ze.groups.find(e=>e.id===I.groupId)?.messages??[]).at(-1)?.seq??0,t=qO(I);e>(at[t]??0)&&ot(n=>{if((n[t]??0)>=e)return n;let r={...n,[t]:e};return tk(it,r),r})},[M,I,Ze,at,it]),q(()=>{if(v===null||M!==`friends`&&M!==`inbox`&&M!==`messages`)return;for(let e of Kt)me.current.has(e.fingerprint)||(me.current.add(e.fingerprint),he.current.push(e));let t=pe.current,n=()=>{for(;pe.current===t&&ge.current<4;){let r=he.current.shift();if(r===void 0)return;ge.current+=1,dT(e.rooms,B,r).catch(()=>null).then(e=>{pe.current===t&&(--ge.current,fe(t=>({...t,[r.fingerprint]:e})),n())})}};n()},[v,M,Kt,e,B]);let Yt=_u(()=>{let e={};for(let t of Kt){let n=de[t.fingerprint];e[t.fingerprint]=n==null?t.profile.avatar??null:n.avatar}return e},[Kt,de]),Xt=J(void 0),Zt=e=>t=>{t!==null&&Xt.current===e&&(Xt.current=void 0,t.focus())},Qt=e=>{Xt.current=e,C(null)},$t=async()=>{let t=await nT(e);return t.ok&&(Xt.current=null,N(`friends`),await Ee().then(lt)),t},en=e=>{e!==null&&f&&(e.focus(),p())},tn=Bt.length+(ze?.waiting.length??0)+(ze?.accepted.length??0),nn=_u(()=>JO(Kt,Ze.directMessages,Ze.groups,at),[Kt,Ze,at]),rn=e=>{if(e===void 0)return;let t=ye.current===null?void 0:MC(ye.current);H({ok:!0,roster:e}),t!==MC(e)&&Ve.current&&lt()},an={makeRoom:()=>ke(async()=>{let t=await NC(e,ye.current!==null&&(Ye===`taken`||Ye===`not-kept`)?MC(ye.current)??void 0:void 0);return rn(t.roster),t.ok?(nt(e=>e+1),{ok:!0,roster:t.roster}):(t.reason===`out-of-claims`&&Xe(`out-of-claims`),t)}),sendDirect:async(n,r)=>{let i=await BC(e,{keys:B,name:t.name},n,r);return i.ok&&rn(i.roster),i},createGroup:async(n,r)=>{let i=await UC(e,{keys:B,name:t.name},n,r);return i.ok&&rn(i.roster),i},sendGroup:async(n,r)=>{let i=$e.current?.groupState(n);if(i==null)return{ok:!1,reason:`unavailable`};let a=await GC(e,{keys:B,name:t.name},i,r);return a.ok&&rn(a.roster),a},addToGroup:async(n,r)=>{let i=$e.current?.groupState(n);if(i==null)return{ok:!1,reason:`unavailable`};let a=await KC(e,{keys:B,name:t.name},i,r);return a.ok&&rn(a.roster),a},leaveGroup:async n=>{let r=$e.current?.groupState(n);if(r==null)return{ok:!1,reason:`unavailable`};let i=await qC(e,{keys:B,name:t.name},r);return i.ok&&rn(i.roster),i}},on=ES(Vu,t.name),sn=v===null?null:wf(v),cn=v===null?`friends`:bf(v).level,ln=v?.profile.avatar?.value??null,un=_h(e.storage,ln,wp.avatar),dn=[{id:`overview`,label:`Overview`},{id:`customize`,label:`Customize`},{id:`friends`,label:`Friends`,...Kt.length>0?{badge:Kt.length}:{}},{id:`messages`,label:`Messages`,...nn>0?{badge:nn,accentBadge:!0}:{}},{id:`inbox`,label:`Inbox`,...tn>0?{badge:tn,accentBadge:!0}:{}},...Rt?[{id:`apps`,label:`Apps`,...Vt.length>0?{badge:Vt.length}:{}}]:[],{id:`account`,label:`Account`}],fn=v!==null&&M===`customize`&&P===`layout`?ce??ub(v):null;return Q(`div`,{className:`social-workspace`,"data-social-state":`ready`,"data-social-theme":fn?.theme,"data-social-accent":fn?.accent,children:[Q(`aside`,{className:`social-sidebar`,children:[Q(`div`,{className:`social-sidebar-head`,children:Q(`span`,{className:`social-brand`,children:[Q(Wm,{size:16}),Q(`span`,{children:`FKN Social`})]})}),Q(`div`,{className:`social-sidebar-user`,"data-social-claim":Ae??`unknown`,children:[Q(vh,{signKey:B.signKey,src:un,url:ln?.url,avatarAlt:`${t.name}'s avatar`,small:!0}),Q(`div`,{children:[Q(`span`,{className:`social-brand-name`,"data-social-name":!0,children:t.name}),Q(`span`,{className:`social-muted`,children:ck[cn]})]})]}),Q(`nav`,{className:`social-nav`,"aria-label":`App pages`,children:dn.map(e=>Q(`button`,{type:`button`,className:`social-nav-btn`,"data-social-nav":e.id,"aria-current":M===e.id?`page`:void 0,onClick:()=>N(e.id),children:[Q(`span`,{className:`social-nav-label`,children:[Q(Gm,{id:e.id}),Q(`span`,{children:e.label})]}),e.badge!==void 0&&Q(`span`,{className:e.accentBadge?`social-nav-badge social-nav-badge-accent`:`social-nav-badge`,children:e.badge})]},e.id))})]}),Q(`main`,{className:`social-main`,"data-social-tab":M,children:[i&&Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}),Q(PO,{notice:Ie,page:on}),M!==`account`&&Q(FE,{status:Ae??`unknown`,onClaimAgain:gt.claimAgain,onRename:()=>{se(!0),N(`account`)}}),Q(uh,{children:b}),v===null&&b!==null&&Q(`div`,{className:`social-card-box`,children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>void Ee(),children:`Try again`})}),Se&&Q(fk,{onReset:$t})]}),M===`account`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Account`})}),Q(`div`,{className:`social-card-box`,children:Q(LE,{identity:t,fresh:r,status:Ae??`unknown`,actions:gt,avatar:un,avatarUrl:ln?.url,openRename:oe,onRenameOpened:()=>se(!1)})})]}),v!==null&&M!==`account`&&Q(G,{children:[M===`overview`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Overview`})}),Q(`div`,{className:`social-overview-grid`,children:[Q(`div`,{className:`social-card-box`,children:[Q(`div`,{className:`social-card`,children:[Q(vh,{signKey:B.signKey,src:un,url:ln?.url,avatarAlt:`${t.name}'s avatar`}),Q(`div`,{children:[Q(`div`,{className:`social-name`,style:ch(sn?.displayName||t.name),children:sn?.displayName||t.name}),sn?.displayName&&sn.displayName!==t.name&&Q(`div`,{className:`social-muted`,children:t.name}),Q(`div`,{className:`social-muted`,children:ck[cn]})]})]}),sn?.bio&&Q(`p`,{className:`social-bio`,children:sn.bio}),Q(Ch,{url:on,site:o})]}),Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Shortcuts`}),Q(`div`,{className:`social-stats-strip`,children:[Q(`div`,{className:`social-stat-cell`,children:[Q(`span`,{className:`social-stat-label`,children:`Friends`}),Q(`strong`,{className:`social-stat-value`,children:Kt.length})]}),Q(`div`,{className:`social-stat-cell`,children:[Q(`span`,{className:`social-stat-label`,children:`Inbox`}),Q(`strong`,{className:`social-stat-value`,children:tn})]})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>N(`customize`),children:`Customize`}),Q(`button`,{type:`button`,onClick:()=>N(`friends`),children:[`Friends (`,Kt.length,`)`]}),tn>0&&Q(`button`,{type:`button`,onClick:()=>N(`inbox`),children:[`Inbox (`,tn,`)`]})]}),ze!==null&&ze.status!==`ready`&&Q(`p`,{className:`social-warn-text`,children:`Check your inbox status under Inbox.`})]})]})]}),M===`customize`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Customize`})}),Q(`nav`,{className:`social-subtabs`,"aria-label":`Customize sections`,children:[[`general`,`General`],[`panels`,`Panels`],[`layout`,`Page layout`],[`visibility`,`Privacy`]].map(([e,t])=>Q(`button`,{type:`button`,className:`social-subtab`,"data-social-subtab":e,"aria-current":P===e?`page`:void 0,onClick:()=>F(e),children:t},e))}),P===`general`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Profile`}),Q(MO,{profile:wf(v),onSave:async(t,n)=>{let r=await dp(e,t,n);return r.ok&&(H(r),lt()),r}})]}),P===`panels`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Custom panels`}),Q(OO,{panels:Dm(v),actions:St,storage:e.storage})]}),P===`layout`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{tabIndex:-1,ref:en,"data-social-layout":!0,children:`Page layout`}),Q(sO,{layout:ub(v),onPreview:le,onSave:async(t,n)=>{let r=await yb(e,t,n);return r.ok&&(H(r),lt()),r}})]}),P===`visibility`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Who sees your profile`}),Q(VO,{visibility:bf(v),page:on,status:Ae,pageRoomStatus:Me,oldPage:gT(v)!==null,site:o,actions:vt,pictures:{avatar:(v.profile.avatar?.value??null)!==null,background:(v.profile.background?.value??null)!==null}})]})]}),M===`friends`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h2`,{tabIndex:-1,ref:Zt(null),children:`Friends`})}),E!==null&&Q(sk,{invite:E,storage:e.storage,site:o,onDismiss:()=>D(null)}),l!==void 0&&Q(eD,{name:l,own:B.signKey,isFriend:e=>At(v)(cf(e)),read:Ot,send:kt,onMake:wt,onClose:u,storage:e.storage},l),w.map(e=>Q(ok,{invite:e,onDismiss:()=>T(t=>t.filter(t=>t!==e))},e.link)),qt===null?Q(`div`,{className:`social-friends-grid`,children:[Q(`div`,{className:`social-card-box`,children:Q(iD,{friends:Kt,onOpen:C,focusRef:Zt,storage:e.storage,profiles:de})}),Q(`div`,{className:`social-card-box`,children:[Q($E,{onAdd:d}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-new-invite":!0,"aria-disabled":O||w.length>=3,onClick:()=>void Mt(),children:O?`Making a link...`:`Invite a friend`})}),w.length>=3&&Q(`p`,{className:`social-muted`,children:`Close an invite, or press Done, to make another.`})]})]}):Q(`div`,{className:`social-card-box`,children:Q(cD,{friend:qt,site:o,storage:e.storage,live:de[qt.fingerprint],onBack:()=>Qt(qt.fingerprint),onMessage:()=>{L({kind:`dm`,fingerprint:qt.fingerprint}),C(null),N(`messages`)},onInvite:async t=>Sw(e,Ct(v),qt,t),onNickname:async t=>H(await hp(e,qt.fingerprint,t)),onRemove:async()=>{let t=Kt[Kt.indexOf(qt)+1]?.fingerprint??null,n=H(await _p(e,qt.fingerprint));return n.ok&&(Qt(t),lt()),n}},qt.fingerprint)})]}),M===`inbox`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Inbox`})}),Q(`div`,{className:`social-card-box`,children:[Q(CE,{asks:Bt,actions:Pt,names:Ht,onAnswered:()=>{N(`apps`),Lt(!0)}}),Q(ZE,{status:ze?.status??null,waiting:ze?.waiting??[],accepted:ze?.accepted??[],site:o,actions:Dt,onMake:wt,storage:e.storage,friendAvatars:Yt}),Bt.length===0&&ze?.status===`ready`&&ze.waiting.length===0&&ze.accepted.length===0&&Q(`p`,{className:`social-muted`,children:`Nothing waiting.`})]})]}),M===`messages`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Messages`})}),Q(YO,{status:Ye,friends:Kt,friendProfiles:de,storage:e.storage,directMessages:Ze.directMessages,groups:Ze.groups,selected:I,onSelect:L,readCursors:at,actions:an})]}),M===`apps`&&Rt&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h2`,{ref:Ft,tabIndex:-1,children:`Apps`})}),Q(`div`,{className:`social-card-box`,children:Vt.length>0?Q(DE,{apps:Vt,actions:Pt,names:Ht}):Q(`p`,{className:`social-muted`,children:`No connected apps yet.`})})]})]})]})]})},fk=({onReset:e})=>{let[t,n]=K(!1),[r,i]=K(!1),[a,o]=K(null),s=J(null),c=()=>{r||(n(!1),o(null),s.current?.focus())},l=async()=>{if(r)return;i(!0),o(null);let t=await e();i(!1),t.ok||o(t.reason)};return Q(G,{children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,ref:s,"data-social-reset":!0,onClick:()=>n(!0),children:`Reset Social`})}),t&&Q(`div`,{className:`social-warn`,"data-social-reset-ask":!0,children:[Q(`p`,{children:`Your friend list, profile, page layout, favourites and app permissions will be deleted for good.`}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-social-reset-confirm":!0,"aria-disabled":r,onClick:()=>void l(),children:r?`Resetting...`:`Reset`}),Q(`button`,{type:`button`,"aria-disabled":r,onClick:c,children:`Cancel`})]})]})]})},pk=({title:e,children:t,onRetry:n})=>Q(G,{children:[Q(`h1`,{children:e}),Q(`p`,{children:t}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:n,children:`Try again`})})]}),mk=({services:e,onChanged:t})=>{let[n,r]=K(!1),[i,a]=K(!1),[o,s]=K(null),c=async e=>(e.ok&&await t(),e),l=async()=>{if(i)return;a(!0),s(null);let t=await c(await tT(e));a(!1),t.ok||s(t.reason)};return Q(G,{children:[Q(`h1`,{children:`Your saved identity will not open`}),Q(`p`,{children:`Enter your recovery key to bring it back.`}),Q(jE,{onRestore:async t=>c(await eT(e,t))}),Q(`h2`,{children:`No recovery key?`}),Q(`p`,{className:`social-muted`,children:`You can start over with a new key, which nothing links to the old one.`}),Q(eh,{reason:o}),Q(`div`,{className:`social-row`,children:n?Q(`button`,{type:`button`,"aria-disabled":i,onClick:()=>void l(),children:`Start over with a new key`}):Q(`button`,{type:`button`,onClick:()=>r(!0),children:`Start over`})})]})},hk=({services:e,canRestore:t,inviteWaiting:n,onPicked:r,onChanged:i})=>{let[a,o]=K(!1);return Q(G,{children:[Q(`h1`,{children:`Pick your name`}),n&&Q(`p`,{className:`social-warn`,"data-social-invite-waiting":!0,children:`Pick your name first, then the invite opens.`}),Q(AE,{label:`Claim name`,onPick:async t=>{let n=await Zw(e,t);return n.ok&&await r(),n}}),t&&(a?Q(G,{children:[Q(`h2`,{children:`Restore from a recovery key`}),Q(jE,{onRestore:async t=>{let n=await eT(e,t);return n.ok&&await i(),n}})]}):Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>o(!0),children:`I have a recovery key`})}))]})},gk=({state:e,props:t,listed:n=null,reload:r,fresh:i,setFresh:a,cutShort:o=!1,staged:s=null,onStagedTaken:c=()=>{},adding:l,onAddDone:u=()=>{},onAdd:d=()=>{},editing:f=!1,onEditDone:p=()=>{},route:m=null})=>{let{services:h}=t,g=()=>void r();switch(e.kind){case`unreachable`:return Q(pk,{title:`FKN cannot be reached`,onRetry:g,children:`Check your connection, then try again.`});case`signed-out`:return Q(G,{children:[Q(`h1`,{children:`Sign in to FKN`}),Q(`p`,{children:`Sign in to FKN, then come back here.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:g,children:`I signed in`})})]});case`no-keys`:return Q(pk,{title:`Set up encryption first`,onRetry:g,children:`Set up an encryption key in your FKN account, then try again.`});case`locked`:return Q(G,{children:[Q(`h1`,{children:`Unlock your FKN storage`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>void t.unlock().then(r),children:`Unlock`})})]});case`reset`:return Q(mk,{services:h,onChanged:r});case`newer`:return Q(pk,{title:`This needs a newer FKN Social`,onRetry:g,children:`Reload the page to update.`});case`no-identity`:return Q(hk,{services:h,canRestore:!0,inviteWaiting:s!==null,onPicked:async()=>{a(!0),await r()},onChanged:r});case`ready`:{let{identity:g}=e;return g.name===null?Q(hk,{services:h,canRestore:!1,inviteWaiting:s!==null,onPicked:async()=>{a(!0),await r()},onChanged:r}):Q(dk,{services:h,identity:{...g,name:g.name},listed:n,fresh:i,cutShort:o,onChanged:r,site:t.site??nk,staged:s,onStagedTaken:c,adding:l,onAddDone:u,onAdd:d,editing:f,onEditDone:p,route:m,onRosterChange:t.onRosterChange,resolveAppName:t.resolveAppName,pollIntervalMs:t.pollIntervalMs})}}},_k=e=>{let[t,n]=K(null),[r,i]=K(null),[a,o]=K(!1),[s,c]=K(null),[l,u]=K(!1),[d,f]=K(void 0),[p,m]=K(!1),[h,g]=K(null),_=vu(()=>m(!1),[]),v=J(0),[y,b]=K(0),x=_u(()=>({...Jw(e.services,()=>v.current===y),compact:e.services.compact??`background`}),[e.services,y]),S=vu(async()=>{let e=null,t=await Xw(x,()=>{e=cp(x)});v.current===y&&(i(e),n(t))},[x,y]);q(()=>{S()},[S]);let{onAccountChange:C,invites:w,adds:T,edits:E,paths:D}=e;q(()=>{let e=C(e=>{e?.switched!==!1&&(v.current+=1,b(v.current),n(null),o(!1))});return()=>{e.then(e=>e())}},[C]),q(()=>w?.(e=>{u(e===null),e!==null&&c(e)}),[w]),q(()=>T?.(f),[T]),q(()=>E?.(()=>m(!0)),[E]),q(()=>D?.(g),[D]);let O=t?.kind===`ready`&&t.identity.name!==null;if(q(()=>{p&&t!==null&&!O&&m(!1)},[p,t,O]),t===null)return Q(Xm,{state:`loading`,label:`Loading...`,error:l?Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}):void 0});let k=Q(gk,{state:t,props:{...e,services:x},listed:r,reload:S,fresh:a,setFresh:o,cutShort:l,staged:s,onStagedTaken:()=>c(null),adding:d,onAddDone:()=>f(void 0),onAdd:f,editing:p,onEditDone:_,route:h});return O?k:Q(Ym,{children:[l&&Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}),Q(`div`,{"data-social-state":t.kind,children:k})]})},{blue:vk}=Jy,yk=e=>Yy.map(t=>`[data-social-accent="${t}"] { --accent: ${Jy[t][e].accent}; --accent-text: ${Jy[t][e].text}; }`).join(`
18
- `),bk=Zy.map(e=>{let t=Xy[e],n=t.light?$y.light:$y.dark,r=t.light?`#e3e7ef`:t.head,i=t.light?`#d5dbe6`:`color-mix(in srgb, ${t.head} 82%, #ffffff)`,a=t.light?`#9fa8b9`:`color-mix(in srgb, ${t.border} 72%, #ffffff)`,o=t.light?`color-mix(in srgb, ${t.accent} 86%, #000000)`:`color-mix(in srgb, ${t.accent} 86%, #ffffff)`;return`[data-social-theme="${e}"] {
16
+ `),n=[],r=null,i=null,a=()=>{if(r===null)return;let e=[];for(let[t,n]of r.entries())t>0&&e.push({kind:`break`}),e.push(...vO(n,0));n.push({kind:`paragraph`,children:e}),r=null},o=()=>{i!==null&&(n.push({kind:`list`,items:i}),i=null)};for(let e of t){if(e.trim()===``){a(),o();continue}let t=yO(e);if(t!==null){a(),o(),n.push({kind:`heading`,level:t.level,children:vO(t.body,0)});continue}let s=bO(e);if(s!==null){a(),i===null&&(i=[]),i.push(vO(s,0));continue}o(),r===null&&(r=[]),r.push(e)}return a(),o(),n},SO=(e,t)=>e.map((e,n)=>{let r=`${t}-${n}`;switch(e.kind){case`text`:return Q(G,{children:e.text},r);case`break`:return Q(`br`,{},r);case`code`:return Q(`code`,{children:e.text},r);case`strong`:return Q(`strong`,{children:SO(e.children,r)},r);case`em`:return Q(`em`,{children:SO(e.children,r)},r);case`link`:return Q(`a`,{className:`social-page-link`,href:e.href,target:`_blank`,rel:`noopener noreferrer nofollow ugc`,children:e.label},r)}}),CO=(e,t)=>{let n=`b-${t}`;switch(e.kind){case`heading`:{let t=SO(e.children,n);return e.level===1?Q(`h3`,{children:t},n):e.level===2?Q(`h4`,{children:t},n):Q(`h5`,{children:t},n)}case`paragraph`:return Q(`p`,{children:SO(e.children,n)},n);case`list`:return Q(`ul`,{children:e.items.map((e,t)=>Q(`li`,{children:SO(e,`${n}-i-${t}`)},`${n}-i-${t}`))},n)}},wO=({text:e})=>Q(`div`,{className:`social-md`,"data-social-markdown":!0,children:_u(()=>xO(e),[e]).map(CO)}),TO={...nh,...oh,...ih},EO=[{level:`public`,label:`Public`},{level:`friends`,label:`Friends`},{level:`off`,label:`Off`}],DO=e=>Math.max(1,Math.round(e/1024)).toLocaleString(`en`),OO=(e,t)=>e.kind===`artwork`&&e.items.length>0&&(e.level===`public`&&t!==`public`||e.level===`friends`&&t===`off`),kO=(e,t)=>e.kind===`artwork`&&e.items.length>0&&e.level!==`public`&&t===`public`,AO=e=>Object.fromEntries(e.items.map(e=>[e.picture.url,e.caption??``])),jO={get:()=>Promise.reject(Error(`social: no storage`))},MO=({picture:e,alt:t,storage:n})=>{let r=_h(n??jO,n===void 0?null:e,Op);return n===void 0?null:r===void 0?Q(`span`,{className:`social-skel social-art-thumb-skel`,"data-panel-art-reading":e.url,"aria-hidden":`true`}):r===null?Q(`div`,{className:`social-artwork-missing`,"data-panel-art-missing":e.url,children:`Image unavailable`}):Q(`img`,{className:`social-art-thumb`,src:r,alt:t,"data-panel-art-img":e.url})},NO=({panel:e,index:t,total:n,onMove:r,onRemove:i,onListProblem:a,actions:o,storage:s})=>{let[c,l]=K(e.title),[u,d]=K(e.kind===`text`?e.body:``),[f,p]=K(()=>e.kind===`artwork`?AO(e):{}),[m,h]=K(e.title),[g,_]=K(e.kind===`text`?e.body:``),[v,y]=K(()=>e.kind===`artwork`?JSON.stringify(e.items):``),[b,x]=K(()=>e.kind===`artwork`?AO(e):{});e.title!==m&&(h(e.title),l(e.title));let S=e.kind===`text`?e.body:``;S!==g&&(_(S),d(S));let C=e.kind===`artwork`?JSON.stringify(e.items):``;C!==v&&(y(C),e.kind===`artwork`?(x(AO(e)),p(t=>{let n={};for(let r of e.items){let e=r.picture.url,i=r.caption??``,a=b[e];n[e]=a!==void 0&&Object.hasOwn(t,e)&&t[e]!==a&&i===a?t[e]:i}return n})):x({}));let[w,T]=K(`write`),[E,D]=K(!1),[O,k]=K(!1),[A,j]=K(null),[M,N]=K(null),[P,F]=K(!1),[I,L]=K(!1),[R,ee]=K(null),[te,z]=K(``),ne=J(null),re=J(null),ie=J(null),ae=J(null),oe=J(null);q(()=>()=>{R!==null&&URL.revokeObjectURL(R.url)},[R]);let se=e.kind===`artwork`?e.items.length:0;gu(()=>{oe.current===`level`&&M===null?(oe.current=null,ie.current?.querySelector(`input:checked`)?.focus()):oe.current===`file-or-save`&&R===null&&(oe.current=null,(ne.current??ae.current)?.focus())},[M,e.level,R,se]);let ce=async(e,t=!1)=>{if(E)return;D(!0),j(null),a(null),k(!1);let n=await e();return D(!1),n.ok?(N(null),F(!1),t&&k(!0)):(oe.current=null,n.reason===`sync-failed`&&(N(null),F(!1)),j(TO[n.reason])),n},le=t=>{if(!E){if(j(null),t===e.level){N(null);return}if(OO(e,t)||kO(e,t)){N(t);return}ce(()=>o.setLevel(e.id,t))}},ue=t=>{oe.current=`level`,ce(()=>o.setLevel(e.id,t))},B=()=>{E||(N(null),ie.current?.querySelector(`input:checked`)?.focus())},de=async e=>{if(E){j(`Another change is still saving. Try again in a moment.`);return}D(!0),L(!0),j(null),k(!1);let t=await o.fitArtwork(e);if(D(!1),L(!1),!t.ok){j(TO[t.reason]);return}ee({...t.picture,url:URL.createObjectURL(t.picture.blob)}),z(``)},fe=()=>{oe.current=`file-or-save`,ee(null),z(``)};return Q(`li`,{className:`social-section`,"data-social-panel-card":e.id,"data-social-panel-kind":e.kind,children:[Q(`div`,{className:`social-section-head`,children:[Q(`div`,{className:`social-panel-head-title`,children:[Q(`span`,{className:`social-panel-tag`,children:e.kind===`text`?`Text`:`Artwork`}),Q(`span`,{className:`social-choice-label`,children:e.title})]}),Q(`div`,{className:`social-section-moves`,children:[Q(`button`,{type:`button`,"aria-label":`Move ${e.title} up`,"aria-disabled":E||t===0,"data-panel-move":`${e.id}-up`,onClick:()=>{!E&&t>0&&r(-1)},children:[Q(Km,{}),`Move up`]}),Q(`button`,{type:`button`,"aria-label":`Move ${e.title} down`,"aria-disabled":E||t===n-1,"data-panel-move":`${e.id}-down`,onClick:()=>{!E&&t<n-1&&r(1)},children:[Q(qm,{}),`Move down`]}),Q(`button`,{type:`button`,ref:re,className:`social-danger`,"aria-disabled":E,"data-panel-delete-start":e.id,onClick:()=>{E||F(!0)},children:`Delete`})]})]}),P&&Q(`div`,{className:`social-warn`,"data-panel-delete-confirm":e.id,children:[Q(`p`,{children:e.kind===`artwork`&&e.items.length>0?`Delete this panel and its uploaded artwork from storage?`:`Delete this panel?`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-panel-delete-confirm-btn":!0,"aria-disabled":E,onClick:()=>void ce(i),children:E?`Deleting...`:`Delete panel`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:()=>{E||(F(!1),re.current?.focus())},children:`Cancel`})]})]}),Q(`div`,{className:`social-seg`,ref:ie,role:`radiogroup`,"aria-label":`Who sees ${e.title}`,children:EO.map(({level:t,label:n})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-level-${e.id}`,value:t,checked:(M??e.level)===t,"aria-disabled":E,onChange:()=>le(t)}),Q(`span`,{className:`social-choice-label`,children:n})]},t))}),M!==null&&OO(e,M)&&Q(`div`,{className:`social-warn`,"data-panel-level-confirm":e.id,children:[Q(`p`,{children:e.level===`public`?`Making this artwork panel non-public deletes its uploaded artwork so no public URL stays exposed.`:`Turning this artwork panel off deletes its uploaded artwork from storage.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-panel-level-confirm-btn":!0,"aria-disabled":E,onClick:()=>ue(M),children:E?`Saving...`:`Confirm change`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:B,children:[`Keep `,e.level===`public`?`public`:`for friends`]})]})]}),M!==null&&kO(e,M)&&Q(`div`,{className:`social-invite`,"data-panel-publish-confirm":e.id,children:[Q(`p`,{children:`Making this panel public lets anyone who opens your page see these artwork images.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,ref:lh,"data-panel-publish-confirm-btn":!0,"aria-disabled":E,onClick:()=>ue(`public`),children:E?`Publishing...`:`Make public`}),Q(`button`,{type:`button`,"aria-disabled":E,onClick:B,children:[`Keep `,e.level===`friends`?`for friends`:`off`]})]})]}),Q(`label`,{className:`social-label`,children:[`Title`,Q(`input`,{name:`panel-title-${e.id}`,autoComplete:`off`,value:c,onChange:e=>{l(e.currentTarget.value),k(!1),j(null)}})]}),e.kind===`text`?Q(G,{children:[Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Markdown mode for ${e.title}`,children:[`write`,`preview`].map(t=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-mode-${e.id}`,value:t,checked:w===t,onChange:()=>T(t)}),Q(`span`,{className:`social-choice-label`,children:t===`write`?`Write`:`Preview`})]},t))}),w===`write`?Q(G,{children:[Q(`label`,{className:`social-label`,children:[`Markdown text`,Q(`textarea`,{name:`panel-body-${e.id}`,rows:4,value:u,onChange:e=>{d(e.currentTarget.value),k(!1),j(null)}})]}),Q(`span`,{className:`social-muted`,children:[u.length,` / `,um]})]}):Q(`div`,{className:`social-md-preview`,"data-panel-preview":e.id,children:u.trim()?Q(wO,{text:u}):Q(`span`,{className:`social-muted`,children:`Nothing to preview yet.`})}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-panel-save":e.id,"aria-disabled":E,onClick:()=>void ce(()=>o.updateText(e.id,{title:c,body:u}),!0),children:E?`Saving...`:`Save panel`}),O&&Q(`span`,{className:`social-muted`,"data-panel-saved":e.id,children:`Saved`})]})]}):Q(G,{children:[e.items.length>0&&Q(`div`,{className:`social-art-list`,"data-panel-art-items":e.id,children:e.items.map((t,n)=>Q(`div`,{className:`social-art-row`,"data-panel-art-row":t.picture.url,children:[Q(`div`,{className:`social-art-row-head`,children:[Q(`span`,{className:`social-choice-label`,children:[`Artwork `,n+1]}),Q(`button`,{type:`button`,"data-panel-art-remove":t.picture.url,"aria-disabled":E,onClick:()=>void ce(()=>o.removeArtItem(e.id,t.picture.url)),children:`Remove`})]}),Q(MO,{picture:t.picture,alt:f[t.picture.url]?.trim()||`${e.title} artwork ${n+1}`,storage:s}),Q(`label`,{className:`social-label`,children:[`Caption`,Q(`input`,{name:`panel-caption-${e.id}-${n}`,autoComplete:`off`,value:f[t.picture.url]??``,placeholder:`Optional caption`,onChange:e=>{let n=e.currentTarget.value;p(e=>({...e,[t.picture.url]:n})),k(!1),j(null)}})]})]},t.picture.url))}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,ref:ae,className:`social-primary`,"data-panel-save":e.id,"aria-disabled":E,onClick:()=>void ce(()=>o.updateArtwork(e.id,{title:c,captions:f}),!0),children:E?`Saving...`:`Save panel`}),O&&Q(`span`,{className:`social-muted`,"data-panel-saved":e.id,children:`Saved`})]}),e.level===`off`?Q(`p`,{className:`social-muted`,"data-panel-art-off":e.id,children:`Set this panel to Friends or Public to upload artwork.`}):e.items.length<4&&Q(`div`,{className:`social-stack`,children:[Q(`label`,{className:`social-label`,children:[`Add artwork (`,e.items.length,` / `,4,`)`,I?`: resizing...`:``,Q(`input`,{ref:ne,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,"aria-disabled":E,"data-panel-file":e.id,onChange:e=>{let t=e.currentTarget.files?.[0];e.currentTarget.value=``,t&&de(t)}})]}),R!==null&&Q(`div`,{className:`social-stack`,"data-panel-art-preview":e.id,children:[Q(`img`,{className:`social-preview`,src:R.url,alt:`Fitted artwork preview`,"data-panel-art-preview-img":!0}),Q(`p`,{className:`social-muted`,"data-panel-art-preview-size":!0,children:[R.width,` by `,R.height,` pixels, `,DO(R.blob.size),` KB`,R.animated?`, animated`:``]}),Q(`label`,{className:`social-label`,children:[`Caption (optional)`,Q(`input`,{name:`panel-new-caption-${e.id}`,autoComplete:`off`,value:te,onChange:e=>z(e.currentTarget.value)})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,ref:lh,"data-panel-use-art":e.id,"aria-disabled":E,onClick:()=>{if(R===null)return;let t=R;ce(async()=>{let n=await o.addArtItem(e.id,t.blob,te);return(n.ok||n.reason===`sync-failed`)&&fe(),n})},children:`Add artwork`}),Q(`button`,{type:`button`,"data-panel-another-art":e.id,"aria-disabled":E,onClick:()=>{E||fe()},children:`Choose another`})]})]})]})]}),Q(uh,{children:A})]})},PO=({panels:e,actions:t,storage:n})=>{let[r,i]=K(null),[a,o]=K(null),[s,c]=K(null),[l,u]=K(!1),d=J(null),f=J(null),p=J(null),m=J(null),h=J(null),g=J(null),_=J(void 0);gu(()=>{if(g.current!==null){let e=g.current;g.current=null,d.current?.querySelector(`[data-panel-move="${e}"]`)?.focus()}if(_.current!==void 0){let e=_.current;_.current=void 0,e===null?f.current?.focus():(d.current?.querySelector(`[data-panel-delete-start="${e}"]`)??f.current)?.focus()}},[e]);let v=r?.kind??null;gu(()=>{if(v!==null)m.current?.focus();else if(h.current!==null){let e=h.current;h.current=null,(e===`text`?f:p).current?.focus()}},[v]);let y=t=>{if(!(l||e.length>=6)){if(r?.kind===t){m.current?.focus();return}h.current=null,o(null),c(null),i({kind:t,title:``,body:``,level:`friends`,mode:`write`})}},b=async()=>{if(l||r===null)return;let e=r.kind;u(!0),o(null),c(null);let n=e===`text`?await t.addText({title:r.title,body:r.body,level:r.level}):await t.addArtwork({title:r.title,level:r.level});u(!1),n.ok?(h.current=e,i(null)):n.reason===`sync-failed`?(h.current=e,i(null),c(TO[n.reason])):o(TO[n.reason])},x=async(n,r)=>{if(l)return;let i=e.findIndex(e=>e.id===n),a=i+r;if(i<0||a<0||a>=e.length)return;g.current=`${n}-${r===-1?`up`:`down`}`,u(!0),c(null);let o=await t.move(n,r);u(!1),o.ok||(g.current=null,c(TO[o.reason]))},S=async n=>{let r=e.findIndex(e=>e.id===n);_.current=r<0?null:e[r+1]?.id??e[r-1]?.id??null;let i=await t.remove(n);return i.ok||(_.current=void 0,i.reason===`sync-failed`&&c(TO[i.reason])),i};return Q(`div`,{className:`social-stack`,"data-social-panels-editor":!0,children:[Q(`div`,{className:`social-panel-bar`,children:[Q(`p`,{className:`social-muted`,children:`Add Markdown text boxes or artwork showcases. Public panels show on your page; Friends panels stay sealed for friends.`}),Q(`span`,{className:`social-panel-count`,"data-social-panel-count":!0,children:[e.length,` / `,6]})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,ref:f,"aria-pressed":r?.kind===`text`,"data-add-text-panel":!0,"aria-disabled":l||e.length>=6,onClick:()=>y(`text`),children:`Add text panel`}),Q(`button`,{type:`button`,ref:p,"aria-pressed":r?.kind===`artwork`,"data-add-artwork-panel":!0,"aria-disabled":l||e.length>=6,onClick:()=>y(`artwork`),children:`Add artwork panel`})]}),r!==null&&Q(`div`,{className:`social-invite`,"data-social-panel-create":r.kind,children:[Q(`h2`,{children:r.kind===`text`?`New text panel`:`New artwork panel`}),Q(`label`,{className:`social-label`,children:[`Title`,Q(`input`,{name:`panel-new-title`,ref:m,autoComplete:`off`,value:r.title,onChange:e=>{let t=e.currentTarget.value;i(e=>e===null?null:{...e,title:t}),o(null)}})]}),Q(`span`,{className:`social-label`,children:`Who sees it`}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees this new panel`,children:EO.map(({level:e,label:t})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-new-level`,value:e,checked:r.level===e,onChange:()=>i(t=>t===null?null:{...t,level:e})}),Q(`span`,{className:`social-choice-label`,children:t})]},e))}),r.kind===`text`&&Q(G,{children:[Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`New panel Markdown mode`,children:[`write`,`preview`].map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`panel-new-mode`,value:e,checked:r.mode===e,onChange:()=>i(t=>t===null?null:{...t,mode:e})}),Q(`span`,{className:`social-choice-label`,children:e===`write`?`Write`:`Preview`})]},e))}),r.mode===`write`?Q(G,{children:[Q(`label`,{className:`social-label`,children:[`Markdown text`,Q(`textarea`,{name:`panel-new-body`,rows:5,value:r.body,onChange:e=>{let t=e.currentTarget.value;i(e=>e===null?null:{...e,body:t}),o(null)}})]}),Q(`div`,{className:`social-muted`,children:[r.body.length,` / `,2e3," - Supports # headings, - lists, **bold**, *italic*, `code`, and [links](https://...)."]})]}):Q(`div`,{className:`social-md-preview`,"data-social-new-preview":!0,children:r.body.trim()?Q(wO,{text:r.body}):Q(`span`,{className:`social-muted`,children:`Nothing to preview yet.`})})]}),Q(uh,{children:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-create-panel":!0,"aria-disabled":l,onClick:()=>void b(),children:l?`Creating...`:`Create panel`}),Q(`button`,{type:`button`,"aria-disabled":l,onClick:()=>{l||(h.current=r.kind,i(null))},children:`Cancel`})]})]},r.kind),Q(uh,{children:s}),e.length===0?Q(`p`,{className:`social-muted`,"data-social-panels-empty":!0,children:`No custom panels yet.`}):Q(`ul`,{className:`social-list`,ref:d,children:e.map((r,i)=>Q(NO,{panel:r,index:i,total:e.length,onMove:e=>void x(r.id,e),onRemove:()=>S(r.id),onListProblem:c,actions:t,storage:n},r.id))})]})},FO={...nh,...rh},IO=e=>e.length<5&&e.at(-1)!==``?[...e,``]:e,LO=e=>({displayName:e.displayName,bio:e.bio,links:IO(e.links)}),RO=({profile:e,onSave:t})=>{let[n,r]=K(()=>LO(e)),[i,a]=K(()=>({displayName:e.displayName,bio:e.bio,links:e.links})),[o,s]=K(!1),[c,l]=K(null),[u,d]=K(!1),f=e=>{r(t=>({...t,...e})),l(null),d(!1)},p=async()=>{if(o)return;s(!0);let e=await t(n,i);s(!1);let r=Cf(n);e.ok&&r.ok&&a(r.profile),d(e.ok),l(e.ok?null:FO[e.reason])};return Q(`div`,{className:`social-stack`,"data-social-profile":!0,children:[Q(`label`,{className:`social-label`,children:[`Display name`,Q(`input`,{name:`display-name`,autoComplete:`off`,value:n.displayName,onChange:e=>f({displayName:e.currentTarget.value})})]}),Q(`label`,{className:`social-label`,children:[`Bio`,Q(`textarea`,{name:`bio`,rows:4,value:n.bio,onChange:e=>f({bio:e.currentTarget.value})})]}),Q(`span`,{className:`social-label`,children:`Links`}),n.links.map((e,t)=>Q(`input`,{name:`link-${t}`,"aria-label":`Link ${t+1}`,autoComplete:`off`,spellcheck:!1,placeholder:`https://`,value:e,onChange:e=>f({links:IO(n.links.map((n,r)=>r===t?e.currentTarget.value:n))})},t)),Q(uh,{children:c}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-save-profile":!0,"aria-disabled":o,onClick:()=>void p(),children:o?`Saving...`:`Save profile`}),u&&Q(`span`,{className:`social-muted`,"data-social-saved":!0,children:`Saved`})]})]})},zO=[{level:`me`,label:`Only me`},{level:`friends`,label:`Friends`},{level:`public`,label:`Public`}],BO=({notice:e,page:t})=>{let n=t.replace(/^https?:\/\//,``);return e===`moved`?Q(`p`,{className:`social-warn`,role:`status`,"data-social-notice":`moved`,children:[`Your old page was taken down. Publish again to show your profile at `,n,`.`]}):e===`old-page-stands`?Q(`p`,{className:`social-muted`,role:`status`,"data-social-notice":`old-page-stands`,children:`Your old page could not be taken down yet. Reload to try again.`}):null},VO=[{slot:`avatar`,label:`Avatar`},{slot:`background`,label:`Background`}],HO=e=>Math.max(1,Math.round(e/1024)).toLocaleString(`en`),UO=({preview:e,busy:t,onUse:n,onAnother:r})=>Q(`div`,{className:`social-stack`,"data-social-preview":e.slot,children:[Q(`img`,{className:e.slot===`avatar`?`social-avatar`:`social-preview`,src:e.url,alt:`Your new ${e.slot}`,"data-social-preview-image":!0}),Q(`p`,{className:`social-muted`,"data-social-preview-size":!0,children:[e.width,` by `,e.height,` pixels, `,HO(e.blob.size),` KB`,e.animated?`, animated`:``]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-use-picture":!0,ref:lh,"aria-disabled":t,onClick:n,children:`Use this picture`}),Q(`button`,{type:`button`,"data-another-picture":!0,"aria-disabled":t,onClick:r,children:`Choose another`})]})]}),WO=`Your page shows nothing: see the warning above.`,GO={lost:WO,taken:WO,retired:WO,unrecorded:`Your page could not be written. Write it again from the warning above.`,unknown:`Your page could not be checked just now. Reload to try again.`},KO={"not-kept":`Your profile page room keeps no messages. Turn on Messages kept for it under Rooms in your FKN settings.`,taken:`Someone else holds your profile page room now.`,"out-of-claims":`Your account is at its claimed room limit, so your profile is kept in your name room. Free a room under Rooms in your FKN settings, then make a page room.`,inline:`Your profile is kept in your name room instead of a separate page room.`,unavailable:`FKN rooms did not answer, so your profile page room has not updated yet.`},qO=({visibility:e,page:t,pictures:n,status:r,pageRoomStatus:i=null,oldPage:a=!1,site:o,actions:s})=>{let[c,l]=K(null),[u,d]=K(!1),[f,p]=K(null),[m,h]=K(null),[g,_]=K(null),v=J(null),y=J(!1),b=e.level,x=t.replace(/^https?:\/\//,``);q(()=>()=>{m!==null&&URL.revokeObjectURL(m.url)},[m]);let S=async(e,t=!1)=>{if(u)return;d(!0),p(null);let n=await e();n.ok&&t&&(y.current=!0),d(!1),n.ok?(l(null),t&&h(null)):p(oh[n.reason])},C=async(e,t)=>{if(u)return;d(!0),_(e),p(null);let n=await s.fitPicture(e,t);if(d(!1),_(null),!n.ok)return p(oh[n.reason]);h({...n.picture,slot:e,url:URL.createObjectURL(n.picture.blob)})},w=e=>{v.current=e,h(null)},T=e=>void S(async()=>{let t=await s.putPicture(e.slot,e.blob);return t.ok&&w(e.slot),t}),E=e=>t=>{t!==null&&v.current===e&&(v.current=null,t.focus())},D=e=>{e!==null&&y.current&&(y.current=!1,(e.querySelector(`input:checked`)??e).focus())},O=e=>{u||(p(null),e===b?l(null):e===`public`||b===`public`||b===`friends`&&e===`me`&&(n.avatar||n.background)?l(e):S(async()=>{let t=await s.setLevel(e);return t.ok&&e===`me`&&h(null),t}))},k=VO.map(({slot:e,label:t})=>Q(`div`,{className:`social-stack`,"data-social-picture":e,"data-social-picture-set":n[e],children:[Q(`label`,{className:`social-label`,children:[t,` picture: `,g===e?`resizing...`:n[e]?`one is set`:`none yet`,Q(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,"aria-disabled":u,"data-picture-input":e,ref:E(e),onChange:t=>{let n=t.currentTarget.files?.[0];t.currentTarget.value=``,n&&C(e,n)}})]}),m?.slot===e&&Q(UO,{preview:m,busy:u,onUse:()=>T(m),onAnother:()=>{u||w(e)}}),n[e]&&m?.slot!==e&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>void S(()=>s.removePicture(e)),children:[`Remove the `,t.toLowerCase()]})})]},e)),A=b===`public`&&c!==null&&c!==`public`?c:null,j=b===`friends`&&c===`me`,M=r===null?void 0:GO[r];return Q(`div`,{className:`social-stack`,"data-social-level":b,children:[Q(`div`,{className:`social-stack`,"data-social-page-link":t,children:[Q(`span`,{className:`social-label`,children:`Your page`}),Q(Ch,{url:t,site:o})]}),Q(`div`,{className:`social-seg`,role:`radiogroup`,"aria-label":`Who sees your profile`,ref:b===`public`?void 0:D,children:zO.map(({level:e,label:t})=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`radio`,name:`visibility`,value:e,checked:(c??b)===e,"aria-disabled":u,onChange:()=>O(e)}),Q(`span`,{className:`social-choice-label`,children:t})]},e))}),c===`public`&&b!==`public`&&Q(`div`,{className:`social-invite`,"data-social-publish":!0,children:[Q(`h2`,{children:`Publish your profile`}),Q(`p`,{className:`social-muted`,children:[`Anyone who opens `,x,` sees your profile and pictures.`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,"data-publish":!0,"aria-disabled":u,onClick:()=>void S(s.publish,!0),children:u?`Publishing...`:`Publish`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Cancel`})]})]}),A!==null&&Q(`div`,{className:`social-warn`,"data-social-unpublish":!0,children:[Q(`p`,{children:[`Unpublishing deletes your pictures and shows your profile only to `,A===`friends`?`your friends`:`you`,`.`]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-unpublish":!0,ref:lh,"aria-disabled":u,onClick:()=>void S(()=>s.setLevel(A),!0),children:u?`Unpublishing...`:`Unpublish`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Keep it public`})]})]}),j&&Q(`div`,{className:`social-warn`,"data-social-hide-pictures":!0,children:[Q(`p`,{children:`Switching to Only me deletes your pictures and hides your profile from your friends.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,"data-hide-pictures":!0,ref:lh,"aria-disabled":u,onClick:()=>void S(()=>s.setLevel(`me`),!0),children:u?`Saving...`:`Hide profile`}),Q(`button`,{type:`button`,"aria-disabled":u,onClick:()=>{u||l(null)},children:`Keep for friends`})]})]}),b===`friends`&&!a&&Q(`div`,{className:`social-invite`,"data-social-friends-pictures":!0,children:[Q(`h2`,{children:`Profile pictures`}),Q(`p`,{className:`social-muted`,children:`Shown only to your friends. Static images are resized; animated GIF and WebP files keep their motion.`}),k]}),b===`public`&&Q(`div`,{className:`social-invite`,"data-social-public":r??`checking`,children:[Q(`h2`,{tabIndex:-1,ref:D,children:`Your public page`}),M!==void 0&&Q(`p`,{className:`social-warn-text`,role:`status`,"data-social-page-status":!0,children:M}),!a&&Q(G,{children:[Q(`p`,{className:`social-muted`,children:`Static images are resized; animated GIF and WebP files keep their motion.`}),k]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-unpublish-start":!0,"aria-disabled":u,onClick:()=>{u||l(`friends`)},children:`Unpublish`})})]}),i!==null&&KO[i]!==void 0&&Q(`div`,{className:`social-stack`,"data-social-page-room-status":i,children:[Q(`p`,{className:`social-warn-text`,role:`status`,children:KO[i]}),(i===`taken`||i===`out-of-claims`||i===`inline`)&&s.makePage!==void 0&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,"data-make-page":!0,"aria-disabled":u,onClick:()=>void S(s.makePage),children:`Make a page room`})})]}),u&&c===null&&Q(`p`,{className:`social-muted`,role:`status`,children:`Saving...`}),Q(uh,{children:f})]})},JO=e=>X(e)??new Uint8Array(32),YO=(e,t)=>t==null?e.profile.avatar??null:t.avatar,XO=(e,t)=>{if(e.ok)return``;switch(e.reason){case`invalid`:return`Enter a message before sending.`;case`no-room`:return`Set up your messages room first.`;case`out-of-claims`:return`No messages room: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`;case`not-active`:return`You left this group.`;case`no-peer-room`:return t?`${t} has not opened Messages yet.`:`A group member has not opened Messages yet.`;case`unavailable`:return`Could not deliver right now. Try again in a moment.`;default:return nh[e.reason]}},ZO=e=>{switch(e){case`none`:return{text:`Messages are not set up on this account yet.`,button:`Set up messages`};case`out-of-claims`:return{text:`No messages room: your FKN account holds as many claimed rooms as it can. Unclaim one under Rooms in your FKN settings.`,button:`Set up messages`};case`taken`:return{text:`Your messages room is held under another session or account. Make a new messages room to continue.`,button:`Make a new messages room`};case`not-kept`:return{text:`Messages kept is turned off on your messages room in FKN settings.`,button:`Make a new messages room`};case`unavailable`:return{text:`FKN rooms did not answer right now. Try again in a moment.`,button:null};default:return null}},QO=(e,t)=>e.reduce((e,n)=>e+ +(!n.self&&n.seq>t),0),$O=e=>e.kind===`dm`?`dm:${e.fingerprint}`:`group:${e.groupId}`,ek=(e,t,n,r)=>{let i=0;for(let n of e)i+=QO(t[n.fingerprint]??[],r[`dm:${n.fingerprint}`]??0);for(let e of n)i+=QO(e.messages,r[`group:${e.id}`]??0);return i},tk=({status:e,friends:t,friendProfiles:n,storage:r,directMessages:i,groups:a,selected:o,onSelect:s,readCursors:c,actions:l})=>{let[u,d]=K(``),[f,p]=K(!1),[m,h]=K(null),[g,_]=K(!1),[v,y]=K(!1),[b,x]=K(``),[S,C]=K([]),[w,T]=K(!1),[E,D]=K(!1),O=J(null),k=new Map(t.map(e=>[e.fingerprint,e])),A=o?.kind===`dm`?k.get(o.fingerprint)??null:null,j=o?.kind===`group`?a.find(e=>e.id===o.groupId)??null:null,M=A===null?j===null?[]:j.messages:i[A.fingerprint]??[];q(()=>{h(null),T(!1),D(!1)},[o?.kind,o?.kind===`dm`?o.fingerprint:o?.groupId]),q(()=>{O.current!==null&&(O.current.scrollTop=O.current.scrollHeight)},[M.length,A?.fingerprint,j?.id]);let N=ZO(e),P=[...t].sort((e,t)=>{let r=(i[e.fingerprint]??[]).at(-1)?.at??0;return((i[t.fingerprint]??[]).at(-1)?.at??0)-r||cD(e,n?.[e.fingerprint]).localeCompare(cD(t,n?.[t.fingerprint]))}),F=async()=>{if(g)return;_(!0),h(null);let e=await l.makeRoom();_(!1),e.ok||h(e.reason===`out-of-claims`?XO({ok:!1,reason:`out-of-claims`}):e.reason===`unavailable`||e.reason===`busy`?`Could not set up messages right now. Try again in a moment.`:nh[e.reason])},I=async()=>{if(f||u.trim()===``)return;p(!0),h(null);let e=A===null?j===null?{ok:!1,reason:`invalid`}:await l.sendGroup(j.id,u):await l.sendDirect(A,u);p(!1),e.ok?d(``):h(XO(e,A?.name))},L=async()=>{if(f)return;let e=t.filter(e=>S.includes(e.fingerprint));if(b.trim()===``||e.length===0){h(`Enter a group name and pick at least one friend.`);return}p(!0),h(null);let n=await l.createGroup(b,e);p(!1),n.ok&&n.groupId?(y(!1),x(``),C([]),s({kind:`group`,groupId:n.groupId})):n.ok||h(XO(n))},R=e=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},ee=async e=>{if(f||j===null)return;p(!0),h(null);let t=await l.addToGroup(j.id,e);p(!1),t.ok?T(!1):h(XO(t,e.name))},te=async()=>{if(f||j===null)return;p(!0),h(null);let e=await l.leaveGroup(j.id);p(!1),e.ok?D(!1):h(XO(e))},z=j===null?[]:t.filter(e=>!j.members.some(t=>t.fingerprint===e.fingerprint));return Q(`div`,{className:`social-stack`,"data-social-messages":!0,"data-social-chat-status":e??`loading`,children:[N!==null&&Q(`div`,{className:`social-card-box`,"data-social-chat-setup":!0,children:[Q(`p`,{className:e===`unavailable`?`social-muted`:`social-warn-text`,children:N.text}),N.button!==null&&Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-make-chat":!0,"aria-disabled":g,onClick:()=>void F(),children:g?`Setting up...`:N.button})})]}),Q(`div`,{className:`social-chat-shell`,children:[Q(`aside`,{className:`social-chat-list card social-card-box`,"aria-label":`Conversations`,children:[Q(`div`,{className:`social-link-bar`,children:[Q(`h2`,{children:`Conversations`}),t.length>0&&Q(`button`,{type:`button`,"data-social-new-group":!0,onClick:()=>{y(e=>!e),h(null)},children:v?`Cancel`:`New group`})]}),v&&Q(`div`,{className:`social-invite`,"data-social-group-creator":!0,children:[Q(`label`,{className:`social-label`,children:[`Group name`,Q(`input`,{name:`group-title`,autoComplete:`off`,maxLength:80,value:b,onChange:e=>x(e.currentTarget.value)})]}),Q(`div`,{className:`social-stack`,children:[Q(`span`,{className:`social-label`,children:`Members`}),Q(`div`,{className:`social-checks`,children:t.map(e=>Q(`label`,{className:`social-choice`,children:[Q(`input`,{type:`checkbox`,checked:S.includes(e.fingerprint),onChange:()=>R(e.fingerprint)}),Q(`span`,{className:`social-choice-label`,children:cD(e,n?.[e.fingerprint])})]},e.fingerprint))})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-create-group":!0,"aria-disabled":f||b.trim()===``||S.length===0,onClick:()=>void L(),children:`Create group`})})]}),a.length===0&&t.length===0?Q(`p`,{className:`social-muted`,children:`Add a friend first to start private or group conversations.`}):Q(`ul`,{className:`social-list`,children:[a.map(e=>{let t=e.messages.at(-1),r=t===void 0?``:t.self?t.senderName:(()=>{let e=k.get(t.senderFingerprint);return e?cD(e,n?.[e.fingerprint]):t.senderName})(),i=QO(e.messages,c[`group:${e.id}`]??0),a=o?.kind===`group`&&o.groupId===e.id;return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-chat-item`,"data-social-thread":`group:${e.id}`,"aria-current":a?`true`:void 0,onClick:()=>s({kind:`group`,groupId:e.id}),children:Q(`div`,{className:`social-chat-item-body`,children:[Q(`div`,{className:`social-chat-item-head`,children:[Q(`span`,{className:`social-person-name`,children:e.title}),i>0&&Q(`span`,{className:`social-nav-badge social-nav-badge-accent`,children:i})]}),Q(`span`,{className:`social-muted`,children:t?`${r}: ${t.body.slice(0,48)}`:`${e.members.length} members`})]})})},e.id)}),P.map(e=>{let t=n?.[e.fingerprint],a=cD(e,t),l=i[e.fingerprint]??[],u=l.at(-1),d=QO(l,c[`dm:${e.fingerprint}`]??0),f=o?.kind===`dm`&&o.fingerprint===e.fingerprint;return Q(`li`,{children:Q(`button`,{type:`button`,className:`social-chat-item`,"data-social-thread":`dm:${e.name}`,"aria-current":f?`true`:void 0,onClick:()=>s({kind:`dm`,fingerprint:e.fingerprint}),children:[Q(bh,{signKey:JO(e.signKey),name:e.name,storage:r,avatar:YO(e,t),small:!0}),Q(`div`,{className:`social-chat-item-body`,children:[Q(`div`,{className:`social-chat-item-head`,children:[Q(`span`,{className:`social-person-name`,children:a}),d>0&&Q(`span`,{className:`social-nav-badge social-nav-badge-accent`,children:d})]}),Q(`span`,{className:`social-muted`,children:u?u.body.slice(0,48):e.name})]})]})},e.fingerprint)})]})]}),Q(`section`,{className:`social-chat-thread social-card-box`,"aria-label":`Conversation`,children:A===null&&j===null?Q(`p`,{className:`social-muted`,"data-social-chat-empty":!0,children:`Pick a conversation on the left, or start a new group chat.`}):Q(G,{children:[Q(`div`,{className:`social-main-head`,"data-social-thread-head":!0,children:[Q(`div`,{children:[Q(`h2`,{children:A===null?j?.title:cD(A,n?.[A.fingerprint])}),Q(`span`,{className:`social-muted`,children:A===null?j?.members.map(e=>e.name).join(`, `):A.name})]}),j!==null&&j.active&&Q(`div`,{className:`social-row`,children:[z.length>0&&Q(`button`,{type:`button`,"data-social-group-add-toggle":!0,onClick:()=>T(e=>!e),children:w?`Cancel`:`Add friend`}),E?Q(G,{children:[Q(`button`,{type:`button`,className:`social-danger`,"data-social-leave-confirm":!0,"aria-disabled":f,onClick:()=>void te(),children:`Confirm leave`}),Q(`button`,{type:`button`,"aria-disabled":f,onClick:()=>D(!1),children:`Cancel`})]}):Q(`button`,{type:`button`,"data-social-leave-group":!0,"aria-disabled":f,onClick:()=>D(!0),children:`Leave group`})]})]}),j!==null&&w&&z.length>0&&Q(`div`,{className:`social-invite`,"data-social-group-add":!0,children:[Q(`span`,{className:`social-label`,children:[`Add friend to `,j.title]}),Q(`div`,{className:`social-row`,children:z.map(e=>Q(`button`,{type:`button`,"data-social-add-group-member":e.name,"aria-disabled":f,onClick:()=>void ee(e),children:cD(e,n?.[e.fingerprint])},e.fingerprint))})]}),Q(`div`,{className:`social-chat-log`,ref:O,"data-social-chat-log":!0,children:M.length===0?Q(`p`,{className:`social-muted`,children:`No messages yet.`}):M.map(e=>{let t=e.self?void 0:k.get(e.senderFingerprint),r=t?cD(t,n?.[t.fingerprint]):e.senderName;return Q(`article`,{className:e.self?`social-chat-msg social-chat-msg-self`:`social-chat-msg`,"data-social-msg":e.id,children:[Q(`div`,{className:`social-chat-msg-meta`,children:[Q(`strong`,{children:r}),Q(`span`,{className:`social-muted`,children:new Date(e.at).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})})]}),Q(`p`,{className:`social-bio`,children:e.body})]},e.id)})}),j!==null&&!j.active?Q(`p`,{className:`social-muted`,"data-social-group-left":!0,children:`You left this group.`}):Q(`div`,{className:`social-chat-composer`,children:[Q(`label`,{className:`social-label`,children:[`Message`,Q(`textarea`,{name:`chat-message`,rows:2,maxLength:WS,value:u,onChange:e=>d(e.currentTarget.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),I())}})]}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-social-send-chat":!0,"aria-disabled":f||u.trim()===``,onClick:()=>void I(),children:f?`Sending...`:`Send`})})]}),Q(uh,{children:m})]})})]})]})},nk=1e4,rk=e=>`${e.inbox}\0${e.seq}\0${e.sender.fingerprint}\0${e.sender.name}`,ik=e=>e.filter(({path:e})=>e===`v1/roster.json`||Jf(e)!==null).sort((e,t)=>e.path.localeCompare(t.path)).map(({path:e,updatedAt:t})=>`${e}:${t}`).join(`
17
+ `),ak=e=>JSON.stringify({p:e.profile,f:e.friends,a:e.apps}),ok=e=>{if(typeof localStorage>`u`)return{};try{let t=localStorage.getItem(e);if(t===null)return{};let n=JSON.parse(t);if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n))typeof t==`number`&&Number.isSafeInteger(t)&&t>=0&&(r[e]=t);return r}catch{return{}}},sk=(e,t)=>{if(typeof localStorage<`u`)try{localStorage.setItem(e,JSON.stringify(t))}catch{}},ck=()=>null,lk=e=>Object.keys(e.apps).sort().flatMap(t=>{let n=LT(e,t);return n===null?[]:[{app:t,grant:n}]}),uk=(e,t)=>e.inbox===t.inbox&&e.seq===t.seq,dk=e=>{let[t,n]=K(e.state);return q(()=>(n(e.state()),e.on(n)),[e]),t},fk=({invite:e,onDismiss:t})=>{let n=dk(e);return Q(sO,{link:e.link,expiresAt:e.expiresAt,state:n,onAdd:e.add,onClose:()=>void e.close(),onSaveAgain:()=>void e.saveAgain(),onDismiss:t})},pk=({invite:e,site:t,onDismiss:n,storage:r})=>Q(lO,{state:dk(e),site:t,storage:r,onAccept:()=>void e.accept(),onDecline:()=>{e.decline(),n()},onSendAgain:()=>void e.sendAgain(),onDismiss:n}),mk={me:`Only me`,friends:`Friends`,public:`Public`},hk=Symbol(`watch-unstarted`),gk=Symbol(`watch-creating`),_k=({services:e,identity:t,listed:n,fresh:r,cutShort:i,onChanged:a,site:o,staged:s,onStagedTaken:c,adding:l,onAddDone:u,onAdd:d,editing:f,onEditDone:p,route:m,onRosterChange:h,resolveAppName:g,pollIntervalMs:_=nk})=>{let[v,y]=K(null),[b,x]=K(null),[S,C]=K(null),[w,T]=K([]),[E,D]=K(null),[O,k]=K(!1),A=o()!==null,j=!f&&s===null&&l===void 0&&!r&&m!==null,[M,N]=K(()=>f?`customize`:s!==null||l!==void 0?`friends`:r?`account`:m===null||m.tab===`apps`&&!A?`overview`:m.tab),[P,F]=K(()=>f?`layout`:j&&m.tab===`customize`?m.customizeTab:`general`),[I,L]=K(()=>j&&m.tab===`messages`&&m.groupId!==void 0?{kind:`group`,groupId:m.groupId}:null),R=J(j&&m.tab===`friends`?m.friendName??null:null),ee=J(j&&m.tab===`messages`?m.peerName??null:null),te=J(null),z=J(null),ne=J(m),re=J(`replace`),ie=J(null),ae=J({tab:M,customizeTab:P,viewing:S,chatKey:I===null?null:$O(I)});ae.current={tab:M,customizeTab:P,viewing:S,chatKey:I===null?null:$O(I)};let[oe,se]=K(!1),[ce,le]=K(null);q(()=>{(M!==`customize`||P!==`layout`)&&le(null)},[M,P]);let ue=J(null),B=_u(()=>dx(t.seed),[t.seed]),[de,fe]=K({}),pe=J(0),me=J(new Set),he=J([]),ge=J(0);q(()=>(pe.current+=1,me.current.clear(),he.current=[],ge.current=0,fe({}),()=>{pe.current+=1,he.current=[]}),[e]);let _e=J(null);q(()=>{let e=new Set;return _e.current=e,()=>{_e.current=null;for(let t of e)t()}},[]);let V=e=>_e.current!==null&&(_e.current.add(e),!0),ve=J(!0);q(()=>(ve.current=!0,()=>{ve.current=!1}),[]);let ye=J(null),be=J(null),xe=J(null),[Se,Ce]=K(!1),H=vu(e=>(e.ok&&(ye.current=e.roster,be.current=ak(e.roster),y(e.roster),$e.current?.refreshRoster(e.roster)),x(e.ok?null:nh[e.reason]),Ce(!e.ok&&e.reason===`reset`),e),[]),[we,Te]=K(!1),Ee=vu(async t=>{H(await(t??cp(e))),Te(!0)},[e,H]),De=J(n);q(()=>{Ee(De.current??void 0)},[Ee]);let Oe=J(Promise.resolve()),ke=vu(e=>{let t=Oe.current.then(e,e);return Oe.current=t.catch(()=>{}),t},[]),[Ae,je]=K(null),[Me,Ne]=K(null),Pe=J(null),Fe=J(null),[Ie,Le]=K(null),Re=_u(()=>({keys:B,name:t.name}),[B,t.name]),[ze,Be]=K(null),Ve=J(!1),He=J(!1),Ue=J(null),We=J(hk),Ge=J(null),Ke=J(new Map),[qe,Je]=K(0),[Ye,Xe]=K(null),[Ze,Qe]=K({directMessages:{},groups:[]}),$e=J(null),et=J(hk),[tt,nt]=K(0),rt=v===null?void 0:LC(v),it=_u(()=>typeof rt==`string`?`fkn.social.chat-read.${cf(B.signKey)}.${qy(rt)}`:`fkn.social.chat-read.${cf(B.signKey)}`,[B,rt]),[at,ot]=K(()=>ok(it));q(()=>{ot(ok(it))},[it]);let st=async t=>{let n=await cp(e);return n.ok?(H(n),t(OT(n.roster,He.current))):{ok:!1,reason:n.reason===`reset`?`list-reset`:n.reason}},ct=vu(async(t=!1)=>{let n=ye.current;if(n!==null&&ST(n)!==null){let t=await FT(e,n);Le(t.ok?`moved`:`old-page-stands`),t.ok&&(H(t),n=t.roster)}let r=n===null?null:Ve.current?{roster:n,inboxTaken:He.current}:(async e=>{Ve.current=!0;let t=Ge.current===null?{status:`unavailable`,inboxTaken:!1}:await Ge.current;return ve.current?(He.current=t.inboxTaken,{roster:ye.current??t.roster??e,inboxTaken:He.current}):{roster:e,inboxTaken:!1}})(n),i=await kT(e,Re,r,{lastNameStatus:Pe.current,lastCoreKey:Fe.current,skipNameIfUnchanged:!t});return i.roster!==void 0&&H({ok:!0,roster:i.roster}),Pe.current=i.status,Fe.current=i.coreKey,je(i.status),Ne(i.pageStatus),i},[e,Re,H]),lt=vu(()=>ke(async()=>{await ct(!1)}),[ke,ct]),ut=vu(()=>ke(async()=>{await ct(!0)}),[ke,ct]),dt=v!==null,ft=v===null?void 0:gw(v);q(()=>{if(!we||!dt||ye.current===null){We.current=hk,Ge.current=null;return}let t=gw(ye.current);if(t===null){We.current=null,He.current=!1,Be(e=>({status:`none`,waiting:[],accepted:e?.accepted??[]})),Ge.current=Promise.resolve({status:`none`,inboxTaken:!1});return}let n=!0;We.current=t??gk;let r=Sw(e,B,()=>ye.current??Lf(),{onStatus:e=>{n&&(He.current=e===`taken`,Be(t=>({status:e,waiting:t?.waiting??[],accepted:t?.accepted??[]})))},onRoster:e=>{if(!n)return;We.current=gw(e)??gk;let t=be.current,r=ak(e);H({ok:!0,roster:e}),Ve.current&&t!==null&&r!==t&&lt()},onAccepted:e=>{n&&e.length!==0&&Be(t=>{let n=t??{status:`ready`,waiting:[],accepted:[]},r=[...n.accepted];for(let t of e)r.includes(t)||r.push(t);return{...n,accepted:r}})},onWaiting:t=>{if(!n)return;let r=t.map(e=>{let t=rk(e),n=Ke.current.get(t);return n===void 0?e:{...e,sender:{...e.sender,confirmed:n}}});Be(e=>({status:e?.status??`ready`,waiting:r,accepted:e?.accepted??[]}));for(let r of t){let t=rk(r);Ke.current.has(t)||(Ke.current.set(t,null),iS(e.rooms,r.sender.name,r.sender.signKey).then(e=>{Ke.current.set(t,e),n&&Be(t=>t===null?t:{...t,waiting:t.waiting.map(t=>uk(t,r)?{...t,sender:{...t.sender,confirmed:e}}:t)})}))}}});return Ue.current=r,Ge.current=r.ready,()=>{n=!1,Ue.current===r&&(Ue.current=null),r.leave()}},[we,dt,qe,e,B,H,lt]),q(()=>{if(!we||!dt||We.current===hk)return;let e=ft===void 0?gk:ft;We.current!==e&&Je(e=>e+1)},[we,dt,ft]);let pt=J(!1),mt=J(!1),ht=vu(async(t=!1)=>{if(we&&ve.current){if(pt.current){t&&(mt.current=!0);return}if(t||typeof document>`u`||document.visibilityState!==`hidden`){pt.current=!0;try{let n=await e.cloud.list();if(!ve.current)return;let r=ik(n);if(!t&&xe.current!==null&&r===xe.current)return;xe.current=r;let i=await cp(e);if(!ve.current)return;if(!i.ok){H(i);return}let a=be.current,o=ak(i.roster);H(i),a!==null&&o!==a&&lt()}catch{}finally{pt.current=!1,mt.current&&ve.current&&(mt.current=!1,ht(!0))}}}},[we,e,H,lt]);q(()=>h?.(()=>{ht(!0)}),[h,ht]),q(()=>{if(!we)return;let e=()=>{ht(!1)},t=()=>{document.visibilityState===`visible`&&ht(!1)};window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,t);let n=_>0?window.setInterval(()=>{ht(!1)},_):void 0;return()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,t),n!==void 0&&window.clearInterval(n)}},[we,_,ht]),q(()=>{we&&ut()},[we,ut]);let gt={claimAgain:async()=>{let n=await ke(()=>st(n=>aT(e,t,n)));return await ut(),n},rename:async t=>{let n=await ke(()=>st(n=>rT(e,t,n)));return n.ok&&await a(),n},giveBack:t=>iT(e,t)},_t=e=>{H({ok:!0,roster:e.roster}),Pe.current=e.status,je(e.status),e.pageStatus!==void 0&&Ne(e.pageStatus);let t=Pw(e.roster);Fe.current=typeof t==`string`?DT(ET(e.roster,t,He.current)):null},vt={setLevel:t=>ke(async()=>{if(ye.current===null)return{ok:!1,reason:`unavailable`};let n=await PT(e,Re,ye.current,t,He.current);return n.ok?(_t(n),{ok:!0}):(n.pageStatus!==void 0&&Ne(n.pageStatus),n)}),publish:()=>ke(async()=>{let t=await MT(e,Re,He.current);return t.ok?(_t(t),Le(null),{ok:!0}):t}),fitPicture:(e,t)=>cm(t,e,lm),putPicture:async(t,n)=>{let r=await ke(()=>Yp(e,t,n));return r.ok?(H(r),await lt(),{ok:!0}):r},removePicture:async t=>{let n=await ke(()=>Xp(e,t));return n.ok?(H(n),await lt(),{ok:!0}):n},makePage:()=>ke(async()=>{if(ye.current===null)return{ok:!1,reason:`unavailable`};let t=ye.current,n=Pw(t)??void 0,r;if(n===void 0){let t=await tS(e.rooms,B,Re.name);if(t===null)return{ok:!1,reason:`unavailable`};r=zw(t)}let i=await Bw(e,B,wT(t),r,n);return i.roster!==void 0&&H({ok:!0,roster:i.roster}),i.ok?(await ct(!0)).pageStatus===`ready`?{ok:!0}:{ok:!1,reason:`unavailable`}:(i.reason===`out-of-claims`&&Ne(`out-of-claims`),{ok:!1,reason:i.reason})})},yt=e=>e.pageStatus===`ready`||(e.pageStatus===`inline`||e.pageStatus===`unused`||e.pageStatus===`out-of-claims`)&&e.status===`held`,bt=async e=>{if(!e.ok)return e;`roster`in e&&H(e);let t=await ct(!1).catch(()=>null);return t!==null&&yt(t)?{ok:!0}:{ok:!1,reason:`sync-failed`}},xt=async({outcome:t,dropped:n})=>{if(!t.ok)return t;H(t);let r=null;try{r=await ct(!1)}catch{r=null}finally{await qp(e.storage,n)}return r!==null&&yt(r)?{ok:!0}:{ok:!1,reason:`sync-failed`}},St={addText:t=>ke(async()=>bt(await Nm(e,t))),addArtwork:t=>ke(async()=>bt(await Pm(e,t))),updateText:(t,n)=>ke(async()=>bt(await Fm(e,t,n))),updateArtwork:(t,n)=>ke(async()=>bt(await Im(e,t,n))),move:(t,n)=>ke(async()=>bt(await Lm(e,t,n))),setLevel:(t,n)=>ke(async()=>xt(await Rm(e,t,n))),remove:t=>ke(async()=>xt(await zm(e,t))),fitArtwork:e=>cm(e,`artwork`,lm),addArtItem:(t,n,r)=>ke(async()=>bt(await Bm(e,t,n,r))),removeArtItem:(t,n)=>ke(async()=>xt(await Vm(e,t,n)))},Ct=e=>({keys:B,name:t.name,profile:Tf(e),inbox:He.current?null:gw(e)??null,chatRoom:Ye===`taken`?null:LC(e)??null}),wt=async()=>{let t=He.current&&ye.current!==null?gw(ye.current):void 0,n=await ke(()=>_w(e,typeof t==`string`?t:void 0));return n.roster!==void 0&&H({ok:!0,roster:n.roster}),n.ok&&(He.current=!1,Be({status:`ready`,waiting:ze?.waiting??[],accepted:ze?.accepted??[]}),await lt()),n},Tt=e=>Be(t=>t===null?t:{...t,waiting:t.waiting.filter(t=>!uk(t,e))}),Et=()=>{let e=Ue.current;return e===null?void 0:(t,n)=>e.delete(n)},Dt={answer:async(t,n)=>{if(ye.current===null)return{ok:!1,reason:`unreachable`};let r=await Dw(e,Ct(ye.current),t,n,Et());return r.roster!==void 0&&H({ok:!0,roster:r.roster}),r.ok&&Tt(t),r.ok&&n&&lt(),r},dismiss:async t=>{await kw(e,t,Et()),Tt(t)},approve:async t=>{let n=await ke(()=>jT(e,Re,t,Et()));return n&&Tt(t),n}},Ot=vu(t=>sS(e.rooms,t),[e]),kt=t=>ke(async()=>{let n=await cp(e);if(!n.ok)return n;let r=await Ew(e,Ct(n.roster),t);return Ee(),r}),At=e=>t=>e.friends[t]?.value.state===`active`,jt=e=>e.on(e=>{e.kind===`friends`&&Ee().then(lt)});q(()=>{if(s===null||v===null||ue.current===s)return;ue.current=s,c();let t=CE(e,Ct(v),s,At(v));V(t.decline),jt(t),D(t)});let Mt=async()=>{if(v===null||O||w.length>=3)return;k(!0);let t=await xE(e,Ct(v),At(v));if(k(!1),!t.ok)return x(t.reason===`no-writer`?nh[`no-writer`]:`No invite was made. Try again in a moment.`);if(!V(t.invite.close))return void t.invite.close();jt(t.invite),T(e=>[...e,t.invite])},Nt=t=>ke(async()=>await AT(e,Re,t)===`written`?null:ah),Pt={change:async(t,n)=>{if(`level`in n&&n.level===`friends`){let e=await Nt(e=>Gh(e,t));if(e!==null)return e}let r=await WT(e,t,n);return r.ok?(H(r),lt(),null):nh[r.reason]},remove:e=>Nt(t=>Wh(t,e))},Ft=J(null),[It,Lt]=K(!1);q(()=>{It&&(Ft.current?.focus(),Lt(!1))},[It]),q(()=>{f&&(N(`customize`),F(`layout`))},[f]),q(()=>{(s!==null||l!==void 0)&&N(`friends`)},[s,l]);let Rt=o()!==null,zt=_u(()=>v===null||!Rt?[]:lk(v),[v,Rt]),Bt=zt.filter(({grant:e})=>e.state===`asked`),Vt=zt.filter(({grant:e})=>e.state!==`asked`),[Ht,Ut]=K({}),Wt=J(new Set),Gt=J(0);q(()=>{Gt.current+=1,Wt.current.clear(),Ut({})},[g]),q(()=>{if(!g||!Rt||zt.length===0)return;let e=Gt.current;for(let{app:t}of zt)Yh(t)&&!Wt.current.has(t)&&(Wt.current.add(t),g(t).then(n=>{Gt.current===e&&ve.current&&Ut(e=>e[t]===n?e:{...e,[t]:n})}))},[g,Rt,zt]);let Kt=_u(()=>v===null?[]:Hf(v),[v]),qt=Kt.find(e=>e.fingerprint===S)??null,Jt=we&&dt&&ye.current!==null&&(M===`messages`||Kt.length>0||typeof rt==`string`);q(()=>{if(!Jt||ye.current===null){et.current=hk,$e.current=null;return}let n=LC(ye.current);if(n===null){et.current=null,$e.current=null,Xe(`none`);return}let r=!0;et.current=n??gk;let i=VC(e,B,t.name,()=>ye.current??Lf(),{onStatus:e=>{r&&Xe(e)},onRoster:e=>{if(!r)return;let t=ye.current===null?void 0:LC(ye.current),n=LC(e);et.current=n??gk,H({ok:!0,roster:e}),t!==n&&Ve.current&&lt()},onUpdate:e=>{r&&Qe(e)}});return $e.current=i,()=>{r=!1,$e.current===i&&($e.current=null),i.leave()}},[Jt,tt,e,B,t.name,H,lt]),q(()=>{if(!Jt||et.current===hk)return;let e=rt===void 0?gk:rt;et.current!==e&&nt(e=>e+1)},[Jt,rt]),q(()=>{if(m===null||m===ne.current)return;ne.current=m;let e=ae.current;if(m.tab===`apps`&&!Rt){R.current=null,ee.current=null,te.current=null,z.current=null,e.tab===`overview`&&e.viewing===null&&e.chatKey===null?(re.current=`push`,ie.current=`/overview`,o()?.navigate?.(`/overview`,!0)):(ie.current=FS(m),re.current=`replace`,N(`overview`),C(null),L(null));return}let t=FS(m),n=!1,r=!1,i=e.customizeTab,a=null,s=null;if(m.tab===`customize`&&(i=m.customizeTab),m.tab===`friends`){if(ee.current=null,z.current=null,m.friendName===void 0)R.current=null,te.current=null;else if(v!==null){let e=Hf(v).find(e=>e.name===m.friendName)??null;R.current=null,te.current=null,a=e?.fingerprint??null,e===null&&(n=!0)}else r=!0,R.current=m.friendName,te.current=null}else if(m.tab===`messages`){if(R.current=null,te.current=null,m.groupId!==void 0)ee.current=null,z.current=null,s={kind:`group`,groupId:m.groupId};else if(m.peerName!==void 0){if(v!==null){let e=Hf(v).find(e=>e.name===m.peerName)??null;ee.current=null,z.current=null,s=e===null?null:{kind:`dm`,fingerprint:e.fingerprint},e===null&&(n=!0)}else r=!0,ee.current=m.peerName,z.current=null}else ee.current=null,z.current=null}else R.current=null,ee.current=null,te.current=null,z.current=null;let c=s===null?null:$O(s),l=m.tab!==e.tab||i!==e.customizeTab||a!==e.viewing||c!==e.chatKey;if(n){if(ie.current=t,l)re.current=`replace`;else{let e=m.tab===`friends`?`/friends`:`/messages`;re.current=`push`,ie.current=e,o()?.navigate?.(e,!0)}}else!r&&ie.current!==null?(ie.current=t,re.current=`push`):re.current=l||ie.current===null?`suppress`:`push`;N(m.tab),m.tab===`customize`&&F(i),C(a),L(s)},[m,Rt,v,o]),q(()=>{if(v!==null){if(R.current!==null){let e=R.current;R.current=null;let t=(Hf(v).find(t=>t.name===e)??null)?.fingerprint??null;re.current=`replace`,S!==t&&(te.current={target:t},C(t))}if(ee.current!==null){let e=ee.current;ee.current=null;let t=Hf(v).find(t=>t.name===e)??null,n=t===null?null:{kind:`dm`,fingerprint:t.fingerprint};re.current=`replace`,(I===null?null:$O(I))!==(n===null?null:$O(n))&&(z.current={target:n},L(n))}}},[v,S,I]),q(()=>{if((R.current!==null||ee.current!==null)&&v===null)return;if(te.current!==null){if(S!==te.current.target)return;te.current=null}if(z.current!==null){let e=z.current.target===null?null:$O(z.current.target);if((I===null?null:$O(I))!==e)return;z.current=null}let e=M===`messages`&&I?.kind===`dm`?Kt.find(e=>e.fingerprint===I.fingerprint)?.name:void 0,t=M===`messages`&&I?.kind===`group`?I.groupId:void 0,n=FS(M===`customize`?{tab:`customize`,customizeTab:P}:M===`friends`?{tab:`friends`,...qt===null?{}:{friendName:qt.name}}:M===`messages`?{tab:`messages`,...t===void 0?e===void 0?{}:{peerName:e}:{groupId:t}}:{tab:M}),r=re.current;if(re.current=`push`,ie.current===null){ie.current=n,r!==`suppress`&&o()?.navigate?.(n,!0);return}if(r===`suppress`){ie.current=n;return}n!==ie.current&&(ie.current=n,o()?.navigate?.(n,r===`replace`))},[M,P,qt,Kt,I,v,S,o]),q(()=>{if(M!==`messages`||I===null)return;let e=(I.kind===`dm`?Ze.directMessages[I.fingerprint]??[]:Ze.groups.find(e=>e.id===I.groupId)?.messages??[]).at(-1)?.seq??0,t=$O(I);e>(at[t]??0)&&ot(n=>{if((n[t]??0)>=e)return n;let r={...n,[t]:e};return sk(it,r),r})},[M,I,Ze,at,it]),q(()=>{if(v===null||M!==`friends`&&M!==`inbox`&&M!==`messages`)return;for(let e of Kt)me.current.has(e.fingerprint)||(me.current.add(e.fingerprint),he.current.push(e));let t=pe.current,n=()=>{for(;pe.current===t&&ge.current<4;){let r=he.current.shift();if(r===void 0)return;ge.current+=1,_T(e.rooms,B,r).catch(()=>null).then(e=>{pe.current===t&&(--ge.current,fe(t=>({...t,[r.fingerprint]:e})),n())})}};n()},[v,M,Kt,e,B]);let Yt=_u(()=>{let e={};for(let t of Kt){let n=de[t.fingerprint];e[t.fingerprint]=n==null?t.profile.avatar??null:n.avatar}return e},[Kt,de]),Xt=J(void 0),Zt=e=>t=>{t!==null&&Xt.current===e&&(Xt.current=void 0,t.focus())},Qt=e=>{Xt.current=e,C(null)},$t=async()=>{let t=await cT(e);return t.ok&&(Xt.current=null,N(`friends`),await Ee().then(lt)),t},en=e=>{e!==null&&f&&(e.focus(),p())},tn=Bt.length+(ze?.waiting.length??0)+(ze?.accepted.length??0),nn=_u(()=>ek(Kt,Ze.directMessages,Ze.groups,at),[Kt,Ze,at]),rn=e=>{if(e===void 0)return;let t=ye.current===null?void 0:LC(ye.current);H({ok:!0,roster:e}),t!==LC(e)&&Ve.current&&lt()},an={makeRoom:()=>ke(async()=>{let t=await RC(e,ye.current!==null&&(Ye===`taken`||Ye===`not-kept`)?LC(ye.current)??void 0:void 0);return rn(t.roster),t.ok?(nt(e=>e+1),{ok:!0,roster:t.roster}):(t.reason===`out-of-claims`&&Xe(`out-of-claims`),t)}),sendDirect:async(n,r)=>{let i=await GC(e,{keys:B,name:t.name},n,r);return i.ok&&rn(i.roster),i},createGroup:async(n,r)=>{let i=await JC(e,{keys:B,name:t.name},n,r);return i.ok&&rn(i.roster),i},sendGroup:async(n,r)=>{let i=$e.current?.groupState(n);if(i==null)return{ok:!1,reason:`unavailable`};let a=await XC(e,{keys:B,name:t.name},i,r);return a.ok&&rn(a.roster),a},addToGroup:async(n,r)=>{let i=$e.current?.groupState(n);if(i==null)return{ok:!1,reason:`unavailable`};let a=await ZC(e,{keys:B,name:t.name},i,r);return a.ok&&rn(a.roster),a},leaveGroup:async n=>{let r=$e.current?.groupState(n);if(r==null)return{ok:!1,reason:`unavailable`};let i=await QC(e,{keys:B,name:t.name},r);return i.ok&&rn(i.roster),i}},on=AS(Vu,t.name),sn=v===null?null:wf(v),cn=v===null?`friends`:bf(v).level,ln=v?.profile.avatar?.value??null,un=_h(e.storage,ln,wp.avatar),dn=[{id:`overview`,label:`Overview`},{id:`customize`,label:`Customize`},{id:`friends`,label:`Friends`,...Kt.length>0?{badge:Kt.length}:{}},{id:`messages`,label:`Messages`,...nn>0?{badge:nn,accentBadge:!0}:{}},{id:`inbox`,label:`Inbox`,...tn>0?{badge:tn,accentBadge:!0}:{}},...Rt?[{id:`apps`,label:`Apps`,...Vt.length>0?{badge:Vt.length}:{}}]:[],{id:`account`,label:`Account`}],fn=v!==null&&M===`customize`&&P===`layout`?ce??fb(v):null;return Q(`div`,{className:`social-workspace`,"data-social-state":`ready`,"data-social-theme":fn?.theme,"data-social-accent":fn?.accent,children:[Q(`aside`,{className:`social-sidebar`,children:[Q(`div`,{className:`social-sidebar-head`,children:Q(`span`,{className:`social-brand`,children:[Q(Wm,{size:16}),Q(`span`,{children:`FKN Social`})]})}),Q(`div`,{className:`social-sidebar-user`,"data-social-claim":Ae??`unknown`,children:[Q(vh,{signKey:B.signKey,src:un,url:ln?.url,avatarAlt:`${t.name}'s avatar`,small:!0}),Q(`div`,{children:[Q(`span`,{className:`social-brand-name`,"data-social-name":!0,children:t.name}),Q(`span`,{className:`social-muted`,children:mk[cn]})]})]}),Q(`nav`,{className:`social-nav`,"aria-label":`App pages`,children:dn.map(e=>Q(`button`,{type:`button`,className:`social-nav-btn`,"data-social-nav":e.id,"aria-current":M===e.id?`page`:void 0,onClick:()=>N(e.id),children:[Q(`span`,{className:`social-nav-label`,children:[Q(Gm,{id:e.id}),Q(`span`,{children:e.label})]}),e.badge!==void 0&&Q(`span`,{className:e.accentBadge?`social-nav-badge social-nav-badge-accent`:`social-nav-badge`,children:e.badge})]},e.id))})]}),Q(`main`,{className:`social-main`,"data-social-tab":M,children:[i&&Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}),Q(BO,{notice:Ie,page:on}),M!==`account`&&Q(VE,{status:Ae??`unknown`,onClaimAgain:gt.claimAgain,onRename:()=>{se(!0),N(`account`)}}),Q(uh,{children:b}),v===null&&b!==null&&Q(`div`,{className:`social-card-box`,children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>void Ee(),children:`Try again`})}),Se&&Q(vk,{onReset:$t})]}),M===`account`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Account`})}),Q(`div`,{className:`social-card-box`,children:Q(UE,{identity:t,fresh:r,status:Ae??`unknown`,actions:gt,avatar:un,avatarUrl:ln?.url,openRename:oe,onRenameOpened:()=>se(!1)})})]}),v!==null&&M!==`account`&&Q(G,{children:[M===`overview`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Overview`})}),Q(`div`,{className:`social-overview-grid`,children:[Q(`div`,{className:`social-card-box`,children:[Q(`div`,{className:`social-card`,children:[Q(vh,{signKey:B.signKey,src:un,url:ln?.url,avatarAlt:`${t.name}'s avatar`}),Q(`div`,{children:[Q(`div`,{className:`social-name`,style:ch(sn?.displayName||t.name),children:sn?.displayName||t.name}),sn?.displayName&&sn.displayName!==t.name&&Q(`div`,{className:`social-muted`,children:t.name}),Q(`div`,{className:`social-muted`,children:mk[cn]})]})]}),sn?.bio&&Q(`p`,{className:`social-bio`,children:sn.bio}),Q(Ch,{url:on,site:o})]}),Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Shortcuts`}),Q(`div`,{className:`social-stats-strip`,children:[Q(`div`,{className:`social-stat-cell`,children:[Q(`span`,{className:`social-stat-label`,children:`Friends`}),Q(`strong`,{className:`social-stat-value`,children:Kt.length})]}),Q(`div`,{className:`social-stat-cell`,children:[Q(`span`,{className:`social-stat-label`,children:`Inbox`}),Q(`strong`,{className:`social-stat-value`,children:tn})]})]}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>N(`customize`),children:`Customize`}),Q(`button`,{type:`button`,onClick:()=>N(`friends`),children:[`Friends (`,Kt.length,`)`]}),tn>0&&Q(`button`,{type:`button`,onClick:()=>N(`inbox`),children:[`Inbox (`,tn,`)`]})]}),ze!==null&&ze.status!==`ready`&&Q(`p`,{className:`social-warn-text`,children:`Check your inbox status under Inbox.`})]})]})]}),M===`customize`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Customize`})}),Q(`nav`,{className:`social-subtabs`,"aria-label":`Customize sections`,children:[[`general`,`General`],[`panels`,`Panels`],[`layout`,`Page layout`],[`visibility`,`Privacy`]].map(([e,t])=>Q(`button`,{type:`button`,className:`social-subtab`,"data-social-subtab":e,"aria-current":P===e?`page`:void 0,onClick:()=>F(e),children:t},e))}),P===`general`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Profile`}),Q(RO,{profile:wf(v),onSave:async(t,n)=>{let r=await dp(e,t,n);return r.ok&&(H(r),lt()),r}})]}),P===`panels`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Custom panels`}),Q(PO,{panels:Dm(v),actions:St,storage:e.storage})]}),P===`layout`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{tabIndex:-1,ref:en,"data-social-layout":!0,children:`Page layout`}),Q(pO,{layout:fb(v),onPreview:le,onSave:async(t,n)=>{let r=await xb(e,t,n);return r.ok&&(H(r),lt()),r}})]}),P===`visibility`&&Q(`div`,{className:`social-card-box`,children:[Q(`h2`,{children:`Who sees your profile`}),Q(qO,{visibility:bf(v),page:on,status:Ae,pageRoomStatus:Me,oldPage:ST(v)!==null,site:o,actions:vt,pictures:{avatar:(v.profile.avatar?.value??null)!==null,background:(v.profile.background?.value??null)!==null}})]})]}),M===`friends`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h2`,{tabIndex:-1,ref:Zt(null),children:`Friends`})}),E!==null&&Q(pk,{invite:E,storage:e.storage,site:o,onDismiss:()=>D(null)}),l!==void 0&&Q(oD,{name:l,own:B.signKey,isFriend:e=>At(v)(cf(e)),read:Ot,send:kt,onMake:wt,onClose:u,storage:e.storage},l),w.map(e=>Q(fk,{invite:e,onDismiss:()=>T(t=>t.filter(t=>t!==e))},e.link)),qt===null?Q(`div`,{className:`social-friends-grid`,children:[Q(`div`,{className:`social-card-box`,children:Q(uD,{friends:Kt,onOpen:C,focusRef:Zt,storage:e.storage,profiles:de})}),Q(`div`,{className:`social-card-box`,children:[Q(aD,{onAdd:d}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,"data-new-invite":!0,"aria-disabled":O||w.length>=3,onClick:()=>void Mt(),children:O?`Making a link...`:`Invite a friend`})}),w.length>=3&&Q(`p`,{className:`social-muted`,children:`Close an invite, or press Done, to make another.`})]})]}):Q(`div`,{className:`social-card-box`,children:Q(mD,{friend:qt,site:o,storage:e.storage,live:de[qt.fingerprint],onBack:()=>Qt(qt.fingerprint),onMessage:()=>{L({kind:`dm`,fingerprint:qt.fingerprint}),C(null),N(`messages`)},onInvite:async t=>Ow(e,Ct(v),qt,t),onNickname:async t=>H(await hp(e,qt.fingerprint,t)),onRemove:async()=>{let t=Kt[Kt.indexOf(qt)+1]?.fingerprint??null,n=H(await _p(e,qt.fingerprint));return n.ok&&(Qt(t),lt()),n}},qt.fingerprint)})]}),M===`inbox`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Inbox`})}),Q(`div`,{className:`social-card-box`,children:[Q(kE,{asks:Bt,actions:Pt,names:Ht,onAnswered:()=>{N(`apps`),Lt(!0)}}),Q(rD,{status:ze?.status??null,waiting:ze?.waiting??[],accepted:ze?.accepted??[],site:o,actions:Dt,onMake:wt,storage:e.storage,friendAvatars:Yt}),Bt.length===0&&ze?.status===`ready`&&ze.waiting.length===0&&ze.accepted.length===0&&Q(`p`,{className:`social-muted`,children:`Nothing waiting.`})]})]}),M===`messages`&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h1`,{children:`Messages`})}),Q(tk,{status:Ye,friends:Kt,friendProfiles:de,storage:e.storage,directMessages:Ze.directMessages,groups:Ze.groups,selected:I,onSelect:L,readCursors:at,actions:an})]}),M===`apps`&&Rt&&Q(G,{children:[Q(`div`,{className:`social-main-head`,children:Q(`h2`,{ref:Ft,tabIndex:-1,children:`Apps`})}),Q(`div`,{className:`social-card-box`,children:Vt.length>0?Q(NE,{apps:Vt,actions:Pt,names:Ht}):Q(`p`,{className:`social-muted`,children:`No connected apps yet.`})})]})]})]})]})},vk=({onReset:e})=>{let[t,n]=K(!1),[r,i]=K(!1),[a,o]=K(null),s=J(null),c=()=>{r||(n(!1),o(null),s.current?.focus())},l=async()=>{if(r)return;i(!0),o(null);let t=await e();i(!1),t.ok||o(t.reason)};return Q(G,{children:[Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,ref:s,"data-social-reset":!0,onClick:()=>n(!0),children:`Reset Social`})}),t&&Q(`div`,{className:`social-warn`,"data-social-reset-ask":!0,children:[Q(`p`,{children:`Your friend list, profile, page layout, favourites and app permissions will be deleted for good.`}),Q(eh,{reason:a}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-danger`,ref:lh,"data-social-reset-confirm":!0,"aria-disabled":r,onClick:()=>void l(),children:r?`Resetting...`:`Reset`}),Q(`button`,{type:`button`,"aria-disabled":r,onClick:c,children:`Cancel`})]})]})]})},yk=({title:e,children:t,onRetry:n})=>Q(G,{children:[Q(`h1`,{children:e}),Q(`p`,{children:t}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:n,children:`Try again`})})]}),bk=({services:e,onChanged:t})=>{let[n,r]=K(!1),[i,a]=K(!1),[o,s]=K(null),c=async e=>(e.ok&&await t(),e),l=async()=>{if(i)return;a(!0),s(null);let t=await c(await sT(e));a(!1),t.ok||s(t.reason)};return Q(G,{children:[Q(`h1`,{children:`Your saved identity will not open`}),Q(`p`,{children:`Enter your recovery key to bring it back.`}),Q(LE,{onRestore:async t=>c(await oT(e,t))}),Q(`h2`,{children:`No recovery key?`}),Q(`p`,{className:`social-muted`,children:`You can start over with a new key, which nothing links to the old one.`}),Q(eh,{reason:o}),Q(`div`,{className:`social-row`,children:n?Q(`button`,{type:`button`,"aria-disabled":i,onClick:()=>void l(),children:`Start over with a new key`}):Q(`button`,{type:`button`,onClick:()=>r(!0),children:`Start over`})})]})},xk=({services:e,canRestore:t,inviteWaiting:n,onPicked:r,onChanged:i})=>{let[a,o]=K(!1);return Q(G,{children:[Q(`h1`,{children:`Pick your name`}),n&&Q(`p`,{className:`social-warn`,"data-social-invite-waiting":!0,children:`Pick your name first, then the invite opens.`}),Q(IE,{label:`Claim name`,onPick:async t=>{let n=await rT(e,t);return n.ok&&await r(),n}}),t&&(a?Q(G,{children:[Q(`h2`,{children:`Restore from a recovery key`}),Q(LE,{onRestore:async t=>{let n=await oT(e,t);return n.ok&&await i(),n}})]}):Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,onClick:()=>o(!0),children:`I have a recovery key`})}))]})},Sk=({state:e,props:t,listed:n=null,reload:r,fresh:i,setFresh:a,cutShort:o=!1,staged:s=null,onStagedTaken:c=()=>{},adding:l,onAddDone:u=()=>{},onAdd:d=()=>{},editing:f=!1,onEditDone:p=()=>{},route:m=null})=>{let{services:h}=t,g=()=>void r();switch(e.kind){case`unreachable`:return Q(yk,{title:`FKN cannot be reached`,onRetry:g,children:`Check your connection, then try again.`});case`signed-out`:return Q(G,{children:[Q(`h1`,{children:`Sign in to FKN`}),Q(`p`,{children:`Sign in to FKN, then come back here.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:g,children:`I signed in`})})]});case`no-keys`:return Q(yk,{title:`Set up encryption first`,onRetry:g,children:`Set up an encryption key in your FKN account, then try again.`});case`locked`:return Q(G,{children:[Q(`h1`,{children:`Unlock your FKN storage`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>void t.unlock().then(r),children:`Unlock`})})]});case`reset`:return Q(bk,{services:h,onChanged:r});case`newer`:return Q(yk,{title:`This needs a newer FKN Social`,onRetry:g,children:`Reload the page to update.`});case`no-identity`:return Q(xk,{services:h,canRestore:!0,inviteWaiting:s!==null,onPicked:async()=>{a(!0),await r()},onChanged:r});case`ready`:{let{identity:g}=e;return g.name===null?Q(xk,{services:h,canRestore:!1,inviteWaiting:s!==null,onPicked:async()=>{a(!0),await r()},onChanged:r}):Q(_k,{services:h,identity:{...g,name:g.name},listed:n,fresh:i,cutShort:o,onChanged:r,site:t.site??ck,staged:s,onStagedTaken:c,adding:l,onAddDone:u,onAdd:d,editing:f,onEditDone:p,route:m,onRosterChange:t.onRosterChange,resolveAppName:t.resolveAppName,pollIntervalMs:t.pollIntervalMs})}}},Ck=e=>{let[t,n]=K(null),[r,i]=K(null),[a,o]=K(!1),[s,c]=K(null),[l,u]=K(!1),[d,f]=K(void 0),[p,m]=K(!1),[h,g]=K(null),_=vu(()=>m(!1),[]),v=J(0),[y,b]=K(0),x=_u(()=>({...eT(e.services,()=>v.current===y),compact:e.services.compact??`background`}),[e.services,y]),S=vu(async()=>{let e=null,t=await nT(x,()=>{e=cp(x)});v.current===y&&(i(e),n(t))},[x,y]);q(()=>{S()},[S]);let{onAccountChange:C,invites:w,adds:T,edits:E,paths:D}=e;q(()=>{let e=C(e=>{e?.switched!==!1&&(v.current+=1,b(v.current),n(null),o(!1))});return()=>{e.then(e=>e())}},[C]),q(()=>w?.(e=>{u(e===null),e!==null&&c(e)}),[w]),q(()=>T?.(f),[T]),q(()=>E?.(()=>m(!0)),[E]),q(()=>D?.(g),[D]);let O=t?.kind===`ready`&&t.identity.name!==null;if(q(()=>{p&&t!==null&&!O&&m(!1)},[p,t,O]),t===null)return Q(Xm,{state:`loading`,label:`Loading...`,error:l?Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}):void 0});let k=Q(Sk,{state:t,props:{...e,services:x},listed:r,reload:S,fresh:a,setFresh:o,cutShort:l,staged:s,onStagedTaken:()=>c(null),adding:d,onAddDone:()=>f(void 0),onAdd:f,editing:p,onEditDone:_,route:h});return O?k:Q(Ym,{children:[l&&Q(`p`,{className:`social-error`,role:`alert`,"data-social-cut-link":!0,children:`This invite link is incomplete. Ask for the link again.`}),Q(`div`,{"data-social-state":t.kind,children:k})]})},{blue:wk}=Xy,Tk=e=>Zy.map(t=>`[data-social-accent="${t}"] { --accent: ${Xy[t][e].accent}; --accent-text: ${Xy[t][e].text}; }`).join(`
18
+ `),Ek=$y.map(e=>{let t=Qy[e],n=t.light?tb.light:tb.dark,r=t.light?`#e3e7ef`:t.head,i=t.light?`#d5dbe6`:`color-mix(in srgb, ${t.head} 82%, #ffffff)`,a=t.light?`#9fa8b9`:`color-mix(in srgb, ${t.border} 72%, #ffffff)`,o=t.light?`color-mix(in srgb, ${t.accent} 86%, #000000)`:`color-mix(in srgb, ${t.accent} 86%, #ffffff)`;return`[data-social-theme="${e}"] {
19
19
  color-scheme: ${t.light?`light`:`dark`};
20
20
  --p-bg: ${t.bg};
21
21
  --p-sheet: ${t.sheet};
@@ -47,7 +47,7 @@ This browser reports limited detail, so the cause above is a best guess.`:``)))}
47
47
  --warn-line: ${n.warnLine};
48
48
  --error: ${n.error};
49
49
  }`}).join(`
50
- `),xk=`
50
+ `),Dk=`
51
51
  :root {
52
52
  color-scheme: light dark;
53
53
  --bg: #f4f5f7;
@@ -63,11 +63,11 @@ This browser reports limited detail, so the cause above is a best guess.`:``)))}
63
63
  --btn: #14161a;
64
64
  --btn-ink: #ffffff;
65
65
  --btn-hover: #2b2f38;
66
- --accent: ${vk.light.accent};
67
- --accent-text: ${vk.light.text};
68
- --warn-bg: ${$y.light.warnBg};
69
- --warn-line: ${$y.light.warnLine};
70
- --error: ${$y.light.error};
66
+ --accent: ${wk.light.accent};
67
+ --accent-text: ${wk.light.text};
68
+ --warn-bg: ${tb.light.warnBg};
69
+ --warn-line: ${tb.light.warnLine};
70
+ --error: ${tb.light.error};
71
71
  font: 15px/1.55 system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
72
72
  -webkit-font-smoothing: antialiased;
73
73
  }
@@ -86,21 +86,21 @@ This browser reports limited detail, so the cause above is a best guess.`:``)))}
86
86
  --btn: #f2f3f5;
87
87
  --btn-ink: #0f1012;
88
88
  --btn-hover: #d6d9df;
89
- --accent: ${vk.dark.accent};
90
- --accent-text: ${vk.dark.text};
91
- --warn-bg: ${$y.dark.warnBg};
92
- --warn-line: ${$y.dark.warnLine};
93
- --error: ${$y.dark.error};
89
+ --accent: ${wk.dark.accent};
90
+ --accent-text: ${wk.dark.text};
91
+ --warn-bg: ${tb.dark.warnBg};
92
+ --warn-line: ${tb.dark.warnLine};
93
+ --error: ${tb.dark.error};
94
94
  }
95
95
  }
96
- ${yk(`light`)}
96
+ ${Tk(`light`)}
97
97
  @media (prefers-color-scheme: dark) {
98
- ${yk(`dark`)}
98
+ ${Tk(`dark`)}
99
99
  }
100
- ${bk}
101
- ${Yy.filter(e=>e!==`blue`).map(e=>`[data-social-theme][data-social-accent="${e}"]:not([data-social-theme="daylight"]) { --accent: ${Jy[e].dark.accent}; --accent-text: ${Jy[e].dark.text}; --btn: ${Jy[e].dark.accent}; --btn-ink: ${Jy[e].dark.text}; --btn-hover: color-mix(in srgb, ${Jy[e].dark.accent} 86%, #ffffff); }`).join(`
100
+ ${Ek}
101
+ ${Zy.filter(e=>e!==`blue`).map(e=>`[data-social-theme][data-social-accent="${e}"]:not([data-social-theme="daylight"]) { --accent: ${Xy[e].dark.accent}; --accent-text: ${Xy[e].dark.text}; --btn: ${Xy[e].dark.accent}; --btn-ink: ${Xy[e].dark.text}; --btn-hover: color-mix(in srgb, ${Xy[e].dark.accent} 86%, #ffffff); }`).join(`
102
102
  `)}
103
- ${Yy.map(e=>`[data-social-theme="daylight"][data-social-accent="${e}"] { --accent: ${Jy[e].light.accent}; --accent-text: ${Jy[e].light.text}; --btn: ${Jy[e].light.accent}; --btn-ink: ${Jy[e].light.text}; --btn-hover: color-mix(in srgb, ${Jy[e].light.accent} 86%, #000000); }`).join(`
103
+ ${Zy.map(e=>`[data-social-theme="daylight"][data-social-accent="${e}"] { --accent: ${Xy[e].light.accent}; --accent-text: ${Xy[e].light.text}; --btn: ${Xy[e].light.accent}; --btn-ink: ${Xy[e].light.text}; --btn-hover: color-mix(in srgb, ${Xy[e].light.accent} 86%, #000000); }`).join(`
104
104
  `)}
105
105
  *, *::before, *::after { box-sizing: border-box; }
106
106
  html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--text); }
@@ -449,4 +449,4 @@ html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--te
449
449
  *, *::before, *::after { animation: none !important; transition: none !important; }
450
450
  .social-loader-bar { left: 29%; width: 42%; transform: none; }
451
451
  }
452
- `,Sk=()=>{let e=document.createElement(`style`);e.textContent=xk,document.head.append(e)},Ck=(e,t)=>Object.assign(Error(t),{code:e}),wk=e=>2<e.min?{usable:!1,reason:`outdated`}:{usable:!0,level:Math.min(2,e.protocol)},Tk=(e,t)=>e.usable&&e.level>=t,Ek={available:1,me:1,attach:1,friends:1,openInvite:1,openAdd:1,publishing:2,allowPublishing:2,publish:2,stopPublishing:2,findByHandle:3,beFindable:3},Dk=e=>{try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return!1;let n=t.t;return typeof n==`string`&&n.startsWith(`social.`)}catch{return!1}},Ok=(e,t)=>({memberId:e,status:`silent`,identity:null,self:e===t}),kk=e=>{let t=new Set([e]),n=new Set;return{participants:()=>[...t].sort().map(t=>Ok(t,e)),of:t=>Ok(t,e),on:e=>(n.add(e),()=>n.delete(e)),ingest:()=>!1,memberJoined:e=>{t.add(e)},memberLeft:e=>{t.delete(e)},announce:async()=>{},detach:async()=>{}}},Ak=e=>{let t=null,n=null,r=!1,i=async()=>{if(r)return`outdated`;try{if(t===null||n===null){let i=await e(),a=wk(await i.hello());if(!a.usable)return r=!0,`outdated`;t=i,n=a}return await t.state()}catch{return t=null,n=null,`unavailable`}},a=async()=>i(),o=async e=>{let r=await i();if(r===`unavailable`||r===`outdated`||r===`app-not-connected`||t===null||n===null||!Tk(n,Ek.attach))return kk(e.selfMemberId);try{let n=[],r=new Set,i=!1,a=0,o=0,s=e=>{if(!i){n=e;for(let e of r)e(n)}},c=await t.attach({roomId:e.roomId,selfMemberId:e.selfMemberId,observe:e.observe,send:async t=>{await e.send(t)},onParticipants:e=>{a+=1,o=a,s(e)}}),l=async()=>{let e=++a;try{let t=await c.participants();if(i||e<o||e<a)return;s(t)}catch{}};return l(),{participants:()=>n,of:t=>n.find(e=>e.memberId===t)??Ok(t,e.selfMemberId),on:e=>i?()=>{}:(r.add(e),()=>r.delete(e)),ingest:(e,t,n,r)=>i||!Dk(t)?!1:(c.ingest(e,t,n,r).then(l,()=>{}),!0),memberJoined:e=>{i||c.memberJoined(e).then(l,()=>{})},memberLeft:e=>{i||c.memberLeft(e).then(l,()=>{})},announce:()=>i?Promise.resolve():c.announce(),detach:async()=>{i||(i=!0,r.clear(),await c.detach().catch(()=>{}))}}}catch{return kk(e.selfMemberId)}},s=e=>Ck(`unsupported`,`social: ${e} needs a newer social package than this one`);return{available:a,attach:o,findByHandle:async()=>{throw await i(),s(`handle search`)}}},jk=({connect:e,install:t})=>{let n=null,r=()=>{let t=n??=(async()=>{let t=await e();if(t===null)return`none`;let n=wk(await t.hello());return n.usable?Tk(n,Ek.publish)?{hub:t}:{refused:`unsupported`}:{refused:`outdated`}})();return t.then(e=>{e===`none`&&n===t&&(n=null)},()=>{n===t&&(n=null)}),t},i=async(e,i,a,o=!1)=>{try{let n=await r();if(n===`none`&&o){if(!await t())return i(`unavailable`);n=await r()}return n===`none`?o?i(`unavailable`):e:`refused`in n?i(n.refused):await a(n.hub)}catch{return n=null,i(`unavailable`)}},a={state:`off`},o=e=>({state:e});return{publishing:()=>i(a,o,e=>e.publishing()),allowPublishing:e=>i(a,o,t=>t.allowPublishing(e),!0),publish:e=>i({ok:!1,reason:`not-allowed`},e=>({ok:!1,reason:e}),t=>t.publish(e)),stopPublishing:()=>i(a,o,e=>e.stopPublishing())}},Mk=`https:social.fkn.app`,Nk=`social@1`,Pk=(e=Mk,t)=>async()=>{let n=await Zs(e,{noConfirm:!0});if(n===null)throw Ck(`unavailable`,`social: the package was not installed`);let{remote:r}=await sc(n.uri,{protocol:Nk,payload:t});return r},Fk=(e=Mk)=>({connect:async()=>{try{let{remote:t}=await sc(e,{protocol:Nk});return t}catch(e){if(e?.code===`not-installed`)return null;throw e}},install:async()=>await Zs(e,{noConfirm:!0})!==null});({...Ak(Pk()),...jk(Fk())});var Ik=100,Lk=e=>Array.isArray(e)&&e.length>0&&e.length<=Ik&&e.every(e=>typeof e==`string`)?e:null,Rk=[`not-friend`,`invalid`,`closed`,`full`],zk=e=>Rk.includes(e),Bk=(e,t)=>{let n=async()=>{let t=await Xw(e);return t.kind===`ready`?t.identity.name===null?`none`:{keys:lx(t.identity.seed),name:t.identity.name}:`unavailable`},r=async e=>{let t=await n();return typeof t==`string`||t.name===e?t:`none`};return{deleteEntries:async t=>{let{name:n,ids:i}=t??{},a=Lk(i);if(a===null)return{ok:!1,reason:`none`};let o=await r(n);return typeof o==`string`?{ok:!1,reason:o}:await wT(e,o,e=>Uh(e,a))===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}},deleteComments:async t=>{let{name:n,ids:i}=t??{},a=Lk(i);if(a===null)return{ok:!1,reason:`none`};let o=await r(n);return typeof o==`string`?{ok:!1,reason:o}:await wT(e,o,e=>vy(e,a))===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}},sendComment:async t=>{let{name:r,text:i}=t??{};if(typeof r!=`string`||!sf(r))return{ok:!1,reason:`not-friend`};let a=await n();if(typeof a==`string`)return{ok:!1,reason:a};let o=await ww(e,a,r,i);return o.ok?o:{ok:!1,reason:zk(o.reason)?o.reason:`unavailable`}},setFavourite:async n=>{let{name:i,favourite:a,on:o}=n??{};if(typeof o!=`boolean`)return{ok:!1,reason:`none`};let s=await r(i);if(typeof s==`string`)return{ok:!1,reason:s};let c=await Cy(e,a,o);return c.ok?(t?.onRosterChange?.(),await wT(e,s,e=>e)===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}):{ok:!1,reason:c.reason===`full`?`full`:c.reason===`invalid`?`none`:`unavailable`}}}},Vk=3e3,Hk=2e3,Uk=6e4,Wk=.2,Gk=()=>({dueAt:null,unanswered:new Set,lastAnnouncedAt:null,heartbeatAt:null}),Kk=(e,t)=>e===null?t:Math.min(e,t),qk=(e,t)=>e+Uk*(1+Wk*(t()*2-1)),Jk=(e,t,n,r)=>{let i={...e,unanswered:new Set(e.unanswered)};return t.kind===`attach`?(i.dueAt=Kk(i.dueAt,n+r()*400),i.heartbeatAt=qk(n,r),i):t.kind===`joined`?i.unanswered.has(t.memberId)?i:(i.unanswered.add(t.memberId),i.dueAt=Kk(i.dueAt,n+Vk+r()*Hk),i):t.kind===`whois`?(i.dueAt=Kk(i.dueAt,n+Vk+r()*Hk),i):(i.dueAt=Kk(i.dueAt,n),i)},Yk=(e,t)=>e.dueAt!==null&&t>=e.dueAt||e.heartbeatAt!==null&&t>=e.heartbeatAt,Xk=(e,t,n)=>({dueAt:null,unanswered:new Set,lastAnnouncedAt:t,heartbeatAt:qk(t,n)}),Zk=256,Qk=64,$k=16777216,eA=()=>({participants:async()=>[],ingest:async()=>!1,memberJoined:async()=>{},memberLeft:async()=>{},announce:async()=>{},detach:async()=>{}}),tA=e=>typeof e==`string`&&e.length>0&&e.length<=Zk&&!e.includes(`\0`),nA={friendByFingerprint:()=>null,friendNamed:()=>!1},rA=e=>{let t=Hf(e),n=new Map(t.map(e=>[e.fingerprint,{nickname:e.nickname,name:e.name}])),r=new Set(t.map(e=>e.name)),i=bf(e).level!==`me`,a=i?e.profile.displayName?.value??``:``,o=i?e.profile.avatar?.value??null:null;return{roster:{friendByFingerprint:e=>n.get(e)??null,friendNamed:e=>r.has(e)},displayName:a,avatarUrl:o===null?``:$p(o)}},iA=async e=>{let t=await Xw(e);switch(t.kind){case`unreachable`:return{availability:`unavailable`};case`signed-out`:return{availability:`signed-out`};case`no-keys`:return{availability:`no-keys`};case`locked`:return{availability:`locked`};case`reset`:return{availability:`reset`};case`newer`:return{availability:`outdated`};case`no-identity`:return{availability:`no-identity`};case`ready`:return t.identity.name===null?{availability:`no-identity`}:{availability:`ready`,name:t.identity.name,keys:lx(t.identity.seed)}}},aA=(e,t)=>{let n=t?.now??Date.now,r=t?.jitter??Math.random,i=t?.setTimeout??((e,t)=>globalThis.setTimeout(e,t)),a=t?.clearTimeout??(e=>globalThis.clearTimeout(e)),o=new Set,s=new Map,c=new Map,l=(e,t)=>{s.delete(e),s.set(e,t);let n=0;for(let e of s.values())n+=e.length;for(let[t,r]of s){if(s.size<=Qk&&n<=$k)break;t!==e&&(s.delete(t),n-=r.length)}},u=e=>{let t=em(e);return t===null?null:{cacheKey:`${t.url}\0${t.key}`,...t}};return{state:async()=>(await iA(e)).availability,attach:async d=>{if(typeof d!=`object`||!d)return eA();let f=d,p=f.roomId,m=f.selfMemberId;if(!tA(p)||!tA(m))return eA();let h=typeof f.send==`function`?f.send:null,g=typeof f.onParticipants==`function`?f.onParticipants:null,_=!1,v=null,y=KT(p,m),b=Gk(),x=nA,S=null,C=()=>{v!==null&&(a(v),v=null)},w=t=>{if(t.identity===null)return null;let n=u(t.identity.avatar);if(n===null)return null;let r=s.get(n.cacheKey);if(r!==void 0)return l(n.cacheKey,r),r;if(!c.has(n.cacheKey)){let t=nm(e.storage,{url:n.url,key:n.key},wp.avatar).then(e=>(c.get(n.cacheKey)===t&&c.delete(n.cacheKey),e===null?null:(l(n.cacheKey,e),!_&&eE(y).some(e=>(e.identity===null?null:u(e.identity.avatar))?.cacheKey===n.cacheKey)&&E(),e)),()=>(c.get(n.cacheKey)===t&&c.delete(n.cacheKey),null));c.set(n.cacheKey,t)}return null},T=()=>eE(y).map(e=>{if(e.identity===null)return{memberId:e.memberId,status:e.status,identity:null,self:e.self};let t=X(e.identity.signKey),n=t?.length===32?pf(t):void 0,r=w(e);return{memberId:e.memberId,status:e.status,identity:{handle:e.identity.handle,name:e.identity.name,displayName:e.identity.displayName,avatar:r,...n===void 0?{}:{identicon:n},signKey:e.identity.signKey,...e.status===`friend`?{nickname:e.nickname}:{}},self:e.self}}),E=()=>{if(!(_||g===null))try{let e=g(T());e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}},D=async()=>{if(_||S===null)return;let e=n(),t=UT({roomId:p,memberId:m,at:e,signKey:S.keys.signKey,dhKey:S.keys.dhKey,name:S.name,displayName:S.displayName,avatarUrl:S.avatarUrl},S.keys.signSeed);$T(y,m,t,e,x),b=Xk(b,e,r),O(),E(),h!==null&&await Promise.resolve(h(JSON.stringify(t))).catch(()=>{})},O=()=>{if(C(),_||S===null)return;let e=b.dueAt,t=b.heartbeatAt,r=e===null?t:t===null?e:Math.min(e,t);if(r===null)return;let a=Math.ceil(Math.max(0,r-n()));v=i(()=>{v=null,!(_||S===null)&&(Yk(b,n())?D():O())},a)},k=async()=>{_||(_=!0,C(),o.delete(k))};o.add(k);let A=await iA(e);if(_)return eA();if(A.availability===`ready`){let i=await cp(e);if(_)return eA();let a=t?.appId,o=i.ok&&a!==void 0?jT(i.roster,a):null;if(i.ok&&a!==void 0&&o===null&&e.writerId!==void 0&&e.exclusive!==void 0)try{let r=await LT({cloud:e.cloud,writerId:e.writerId,exclusive:e.exclusive},a,n());r.outcome.ok&&r.wrote&&t?.onRosterChange?.()}catch{}if(_)return eA();if(o?.presence===`blocked`||a!==void 0&&!i.ok)JT(y,m);else{let e=i.ok?rA(i.roster):{roster:nA,displayName:``,avatarUrl:``};x=e.roster,S={name:A.name,displayName:e.displayName,avatarUrl:e.avatarUrl,keys:A.keys};let t=n();$T(y,m,UT({roomId:p,memberId:m,at:t,signKey:S.keys.signKey,dhKey:S.keys.dhKey,name:S.name,displayName:S.displayName,avatarUrl:S.avatarUrl},S.keys.signSeed),t,x),b=Jk(b,{kind:`attach`},t,r),O(),S.avatarUrl!==``&&T()}}else JT(y,m);return{participants:async()=>_?[]:T(),ingest:async(e,t,i,a)=>{if(_||!tA(e)||typeof t!=`string`||typeof i!=`number`||!Number.isFinite(i))return!1;let o;try{o=JSON.parse(t)}catch{return!1}if(typeof o!=`object`||!o)return!1;if(o.t===`social.whois`)return S!==null&&(b=Jk(b,{kind:`whois`},n(),r),O()),!0;let s=$T(y,e,o,i,x);return s&&E(),s},memberJoined:async e=>{!_&&tA(e)&&(JT(y,e),S!==null&&e!==m&&(b=Jk(b,{kind:`joined`,memberId:e},n(),r),O()),E())},memberLeft:async e=>{!_&&tA(e)&&(YT(y,e),E())},announce:async()=>{await D()},detach:k}},detachAll:async()=>{for(let e of Array.from(o))await e()}}},oA=e=>e.brokered===!0&&(e.from===Vu||e.from===Wu),sA=e=>e.brokered===!0&&Nh(e.from)?e.from:null,cA={state:`not-here`},lA=async(e,t,n)=>{let r=sA(e);return r===null?t:n(r)},uA=e=>oA(e)?e.remote:null,dA=(e,t,n={protocol:2,min:1})=>({hello:async()=>n,openInvite:async n=>{if(!oA(e))return{ok:!1,reason:`not-here`};let r=typeof n==`string`?iE(n):null;return t.onInvite(r),r===null?{ok:!1,reason:`malformed`}:{ok:!0}},openAdd:async n=>{if(!oA(e))return{ok:!1,reason:`not-here`};let r=typeof n==`string`?of(n):null,i=r?.ok===!0?r.name:null;return t.onAdd(i),i===null?{ok:!1,reason:`malformed`}:{ok:!0}},openEdit:async()=>oA(e)?(t.onEdit(),{ok:!0}):{ok:!1,reason:`not-here`},openPath:async n=>{if(!oA(e))return{ok:!1,reason:`not-here`};if(!MS(n))return{ok:!1,reason:`malformed`};let r=AS(n);return r===null?{ok:!1,reason:`malformed`}:(t.onPath?.(r),{ok:!0})},ownKey:async()=>oA(e)?t.own():null,openFriends:async n=>oA(e)?oT(n)?t.friends(n):{ok:!1,reason:`none`}:{ok:!1,reason:`not-here`},deleteEntries:async n=>oA(e)?t.page.deleteEntries(n):{ok:!1,reason:`not-here`},setFavourite:async n=>oA(e)?t.page.setFavourite(n):{ok:!1,reason:`not-here`},deleteComments:async n=>oA(e)?t.page.deleteComments(n):{ok:!1,reason:`not-here`},sendComment:async n=>oA(e)?t.page.sendComment(n):{ok:!1,reason:`not-here`},publishing:()=>lA(e,cA,e=>t.apps.publishing(e)),allowPublishing:n=>lA(e,cA,e=>t.apps.allow(e,n)),publish:n=>lA(e,{ok:!1,reason:`not-here`},e=>t.apps.publish(e,n)),stopPublishing:()=>lA(e,cA,e=>t.apps.stop(e)),state:async()=>e.brokered===!0&&t.presence!==void 0?t.presence.state():`unavailable`,attach:async n=>e.brokered===!0&&t.presence!==void 0?t.presence.attach(n):eA()}),fA=`social.writer`,pA=e=>{try{let t=e(),n=t.getItem(fA);if(n!==null&&/^[A-Za-z0-9_-]{22}$/.test(n))return n;let r=Y(crypto.getRandomValues(new Uint8Array(16)));return t.setItem(fA,r),t.getItem(`social.writer`)===r?r:null}catch{return null}},mA=`social.roster`,hA=Promise.resolve(),gA=e=>{let t=globalThis.navigator?.locks;if(t)return t.request(mA,e);let n=hA.then(e,e);return hA=n.catch(()=>{}),n},_A={open:async e=>{typeof e==`string`&&new URL(e).protocol===`https:`&&window.open(e,`_blank`,`noopener,noreferrer`)}},vA=e=>{if(typeof e!=`object`||!e)return!1;let{code:t,message:n}=e;return t===`denied`&&typeof n==`string`&&n.includes(`own frame`)},yA=async()=>{if(typeof window>`u`||window.parent===window||window.parent!==window.top)return!1;let e=ao(`shell.isAppTab`).then(e=>e.shell?.isAppTab?.()).then(e=>e===!0,()=>!1);return Promise.race([e,new Promise(e=>setTimeout(e,$a,!1))])},bA=()=>{let e=[],t=new Set;return{hand:n=>{t.size===0&&e.push(n);for(let e of t)e(n)},take:n=>{t.add(n);for(let t of e.splice(0))n(t);return()=>{t.delete(n)}}}},xA=({services:e,invites:t,adds:n,edits:r,resolveAppName:i})=>{let[a,o]=K(`checking`),s=J(null),c=vu(async()=>{if(await So().catch(()=>null)===null){oc(Hu).catch(()=>{}),o(`signed-out`);return}o(e=>e===`open`||e===`direct`?e:`opening`)},[]);return q(()=>{c();let e=Co(()=>void c());return()=>{e.then(e=>e())}},[c]),q(()=>{if(a!==`opening`||s.current===null)return;let e=s.current,t=!1;return(async()=>{let n=await Pk(Hu,_A)();if(!t){if(!wk(await n.hello()).usable){t||o(`outdated`);return}if(await ac(Hu,{element:e}),t){oc(Hu).catch(()=>{});return}o(`open`)}})().catch(e=>{t||o(vA(e)?`direct`:`failed`)}),()=>{t=!0}},[a]),a===`direct`?Q(_k,{services:e,unlock:ss,onAccountChange:Co,invites:t,adds:n,edits:r,resolveAppName:i,site:()=>_A}):Q(G,{children:[Q(`div`,{className:`social-frame`,ref:s}),a!==`open`&&(a===`checking`||a===`opening`?Q(Xm,{state:`opening`,label:`Opening...`}):Q(Ym,{children:[Q(`h1`,{children:`FKN Social`}),a===`signed-out`?Q(G,{children:[Q(`p`,{children:`Sign in to FKN to manage your identity and friends.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>void xo().then(c),children:`Sign in`})})]}):a===`outdated`?Q(`p`,{children:`This page is older than FKN Social. Reload it to update.`}):Q(G,{children:[Q(`p`,{children:`FKN Social could not open. Try again or open it at social.fkn.app.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>o(`opening`),children:`Try again`}),Q(`a`,{className:`social-action`,href:Vu,target:`_blank`,rel:`noopener noreferrer`,children:`Open social.fkn.app`})]})]})]}))]})};(e=>{let t=bA(),n=bA(),r=bA(),i=bA(),a=new Set,o=()=>{for(let e of a)e()},s=e=>(a.add(e),()=>{a.delete(e)}),c=null,l={account:{availability:Qo,encryption:os},cloud:kf({list:Hs,readFileSealed:Us,writeFile:(e,t)=>Vs.writeFile(e,new TextEncoder().encode(t)),unlink:e=>Vs.unlink(e),isNotFound:Ao}),rooms:{open:Gc,create:Kc,join:qc},storage:{put:e=>sl(e),get:(e,t)=>ll(e,t),delete:dl,list:()=>ul()},sleep:e=>new Promise(t=>setTimeout(t,e)),writerId:pA(()=>localStorage),exclusive:gA},u=IT(l,{onRosterChange:o}),d=Bk(l,{onRosterChange:o}),f=Zh(),p=new Map,m=e=>`${e.from}\0${e.protocol??``}`;bc(e=>{let a=e.brokered===!0?aA(l,{appId:oA(e)?void 0:sA(e)??void 0,onRosterChange:o}):void 0;if(a!==void 0){let t=m(e),n=p.get(t);n===void 0?p.set(t,[a]):n.push(a)}return dA(e,{onInvite:t.hand,onAdd:n.hand,onEdit:()=>r.hand(!0),onPath:i.hand,...pT(l),apps:u,page:d,presence:a})},e=>{if(c=uA(e)??c,e.brokered===!0){let t=m(e),n=p.get(t),r=n?.shift();n!==void 0&&n.length===0&&p.delete(t),r!==void 0&&e.closed.then(()=>void r.detachAll())}}),Sk();let h=!1;xc(e=>{e&&!h&&(h=!0,zu(document.body.appendChild(document.createElement(`div`))).render(Q(_k,{services:l,unlock:ss,onAccountChange:Co,invites:t.take,adds:n.take,edits:r.take,paths:i.take,onRosterChange:s,resolveAppName:f,site:()=>c})))}),(e?.isAppTab??yA)().then(e=>{e&&!h&&(h=!0,zu(document.body.appendChild(document.createElement(`div`))).render(Q(xA,{services:l,invites:t.take,adds:n.take,edits:r.take,resolveAppName:f})))})})();
452
+ `,Ok=()=>{let e=document.createElement(`style`);e.textContent=Dk,document.head.append(e)},kk=(e,t)=>Object.assign(Error(t),{code:e}),Ak=e=>2<e.min?{usable:!1,reason:`outdated`}:{usable:!0,level:Math.min(2,e.protocol)},jk=(e,t)=>e.usable&&e.level>=t,Mk={available:1,me:1,attach:1,friends:1,openInvite:1,openAdd:1,publishing:2,allowPublishing:2,publish:2,stopPublishing:2,findByHandle:3,beFindable:3},Nk=e=>{try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return!1;let n=t.t;return typeof n==`string`&&n.startsWith(`social.`)}catch{return!1}},Pk=(e,t)=>({memberId:e,status:`silent`,identity:null,self:e===t}),Fk=e=>{let t=new Set([e]),n=new Set;return{participants:()=>[...t].sort().map(t=>Pk(t,e)),of:t=>Pk(t,e),on:e=>(n.add(e),()=>n.delete(e)),ingest:()=>!1,memberJoined:e=>{t.add(e)},memberLeft:e=>{t.delete(e)},announce:async()=>{},detach:async()=>{}}},Ik=e=>{let t=null,n=null,r=!1,i=async()=>{if(r)return`outdated`;try{if(t===null||n===null){let i=await e(),a=Ak(await i.hello());if(!a.usable)return r=!0,`outdated`;t=i,n=a}return await t.state()}catch{return t=null,n=null,`unavailable`}},a=async()=>i(),o=async e=>{let r=await i();if(r===`unavailable`||r===`outdated`||r===`app-not-connected`||t===null||n===null||!jk(n,Mk.attach))return Fk(e.selfMemberId);try{let n=[],r=new Set,i=!1,a=0,o=0,s=e=>{if(!i){n=e;for(let e of r)e(n)}},c=await t.attach({roomId:e.roomId,selfMemberId:e.selfMemberId,observe:e.observe,send:async t=>{await e.send(t)},onParticipants:e=>{a+=1,o=a,s(e)}}),l=async()=>{let e=++a;try{let t=await c.participants();if(i||e<o||e<a)return;s(t)}catch{}};return l(),{participants:()=>n,of:t=>n.find(e=>e.memberId===t)??Pk(t,e.selfMemberId),on:e=>i?()=>{}:(r.add(e),()=>r.delete(e)),ingest:(e,t,n,r)=>i||!Nk(t)?!1:(c.ingest(e,t,n,r).then(l,()=>{}),!0),memberJoined:e=>{i||c.memberJoined(e).then(l,()=>{})},memberLeft:e=>{i||c.memberLeft(e).then(l,()=>{})},announce:()=>i?Promise.resolve():c.announce(),detach:async()=>{i||(i=!0,r.clear(),await c.detach().catch(()=>{}))}}}catch{return Fk(e.selfMemberId)}},s=e=>kk(`unsupported`,`social: ${e} needs a newer social package than this one`);return{available:a,attach:o,findByHandle:async()=>{throw await i(),s(`handle search`)}}},Lk=({connect:e,install:t})=>{let n=null,r=()=>{let t=n??=(async()=>{let t=await e();if(t===null)return`none`;let n=Ak(await t.hello());return n.usable?jk(n,Mk.publish)?{hub:t}:{refused:`unsupported`}:{refused:`outdated`}})();return t.then(e=>{e===`none`&&n===t&&(n=null)},()=>{n===t&&(n=null)}),t},i=async(e,i,a,o=!1)=>{try{let n=await r();if(n===`none`&&o){if(!await t())return i(`unavailable`);n=await r()}return n===`none`?o?i(`unavailable`):e:`refused`in n?i(n.refused):await a(n.hub)}catch{return n=null,i(`unavailable`)}},a={state:`off`},o=e=>({state:e});return{publishing:()=>i(a,o,e=>e.publishing()),allowPublishing:e=>i(a,o,t=>t.allowPublishing(e),!0),publish:e=>i({ok:!1,reason:`not-allowed`},e=>({ok:!1,reason:e}),t=>t.publish(e)),stopPublishing:()=>i(a,o,e=>e.stopPublishing())}},Rk=`https:social.fkn.app`,zk=`social@1`,Bk=(e=Rk,t)=>async()=>{let n=await Zs(e,{noConfirm:!0});if(n===null)throw kk(`unavailable`,`social: the package was not installed`);let{remote:r}=await sc(n.uri,{protocol:zk,payload:t});return r},Vk=(e=Rk)=>({connect:async()=>{try{let{remote:t}=await sc(e,{protocol:zk});return t}catch(e){if(e?.code===`not-installed`)return null;throw e}},install:async()=>await Zs(e,{noConfirm:!0})!==null});({...Ik(Bk()),...Lk(Vk())});var Hk=100,Uk=e=>Array.isArray(e)&&e.length>0&&e.length<=Hk&&e.every(e=>typeof e==`string`)?e:null,Wk=[`not-friend`,`invalid`,`closed`,`full`],Gk=e=>Wk.includes(e),Kk=(e,t)=>{let n=async()=>{let t=await nT(e);return t.kind===`ready`?t.identity.name===null?`none`:{keys:dx(t.identity.seed),name:t.identity.name}:`unavailable`},r=async e=>{let t=await n();return typeof t==`string`||t.name===e?t:`none`};return{deleteEntries:async t=>{let{name:n,ids:i}=t??{},a=Uk(i);if(a===null)return{ok:!1,reason:`none`};let o=await r(n);return typeof o==`string`?{ok:!1,reason:o}:await AT(e,o,e=>Uh(e,a))===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}},deleteComments:async t=>{let{name:n,ids:i}=t??{},a=Uk(i);if(a===null)return{ok:!1,reason:`none`};let o=await r(n);return typeof o==`string`?{ok:!1,reason:o}:await AT(e,o,e=>vy(e,a))===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}},sendComment:async t=>{let{name:r,text:i}=t??{};if(typeof r!=`string`||!sf(r))return{ok:!1,reason:`not-friend`};let a=await n();if(typeof a==`string`)return{ok:!1,reason:a};let o=await Aw(e,a,r,i);return o.ok?o:{ok:!1,reason:Gk(o.reason)?o.reason:`unavailable`}},setFavourite:async n=>{let{name:i,favourite:a,on:o}=n??{};if(typeof o!=`boolean`)return{ok:!1,reason:`none`};let s=await r(i);if(typeof s==`string`)return{ok:!1,reason:s};let c=await Cy(e,a,o);return c.ok?(t?.onRosterChange?.(),await AT(e,s,e=>e)===`written`?{ok:!0}:{ok:!1,reason:`unavailable`}):{ok:!1,reason:c.reason===`full`?`full`:c.reason===`invalid`?`none`:`unavailable`}}}},qk=3e3,Jk=2e3,Yk=6e4,Xk=.2,Zk=()=>({dueAt:null,unanswered:new Set,lastAnnouncedAt:null,heartbeatAt:null}),Qk=(e,t)=>e===null?t:Math.min(e,t),$k=(e,t)=>e+Yk*(1+Xk*(t()*2-1)),eA=(e,t,n,r)=>{let i={...e,unanswered:new Set(e.unanswered)};return t.kind===`attach`?(i.dueAt=Qk(i.dueAt,n+r()*400),i.heartbeatAt=$k(n,r),i):t.kind===`joined`?i.unanswered.has(t.memberId)?i:(i.unanswered.add(t.memberId),i.dueAt=Qk(i.dueAt,n+qk+r()*Jk),i):t.kind===`whois`?(i.dueAt=Qk(i.dueAt,n+qk+r()*Jk),i):(i.dueAt=Qk(i.dueAt,n),i)},tA=(e,t)=>e.dueAt!==null&&t>=e.dueAt||e.heartbeatAt!==null&&t>=e.heartbeatAt,nA=(e,t,n)=>({dueAt:null,unanswered:new Set,lastAnnouncedAt:t,heartbeatAt:$k(t,n)}),rA=256,iA=64,aA=16777216,oA=()=>({participants:async()=>[],ingest:async()=>!1,memberJoined:async()=>{},memberLeft:async()=>{},announce:async()=>{},detach:async()=>{}}),sA=e=>typeof e==`string`&&e.length>0&&e.length<=rA&&!e.includes(`\0`),cA={friendByFingerprint:()=>null,friendNamed:()=>!1},lA=e=>{let t=Hf(e),n=new Map(t.map(e=>[e.fingerprint,{nickname:e.nickname,name:e.name}])),r=new Set(t.map(e=>e.name)),i=bf(e).level!==`me`,a=i?e.profile.displayName?.value??``:``,o=i?e.profile.avatar?.value??null:null;return{roster:{friendByFingerprint:e=>n.get(e)??null,friendNamed:e=>r.has(e)},displayName:a,avatarUrl:o===null?``:$p(o)}},uA=async e=>{let t=await nT(e);switch(t.kind){case`unreachable`:return{availability:`unavailable`};case`signed-out`:return{availability:`signed-out`};case`no-keys`:return{availability:`no-keys`};case`locked`:return{availability:`locked`};case`reset`:return{availability:`reset`};case`newer`:return{availability:`outdated`};case`no-identity`:return{availability:`no-identity`};case`ready`:return t.identity.name===null?{availability:`no-identity`}:{availability:`ready`,name:t.identity.name,keys:dx(t.identity.seed)}}},dA=(e,t)=>{let n=t?.now??Date.now,r=t?.jitter??Math.random,i=t?.setTimeout??((e,t)=>globalThis.setTimeout(e,t)),a=t?.clearTimeout??(e=>globalThis.clearTimeout(e)),o=new Set,s=new Map,c=new Map,l=(e,t)=>{s.delete(e),s.set(e,t);let n=0;for(let e of s.values())n+=e.length;for(let[t,r]of s){if(s.size<=iA&&n<=aA)break;t!==e&&(s.delete(t),n-=r.length)}},u=e=>{let t=em(e);return t===null?null:{cacheKey:`${t.url}\0${t.key}`,...t}};return{state:async()=>(await uA(e)).availability,attach:async d=>{if(typeof d!=`object`||!d)return oA();let f=d,p=f.roomId,m=f.selfMemberId;if(!sA(p)||!sA(m))return oA();let h=typeof f.send==`function`?f.send:null,g=typeof f.onParticipants==`function`?f.onParticipants:null,_=!1,v=null,y=QT(p,m),b=Zk(),x=cA,S=null,C=()=>{v!==null&&(a(v),v=null)},w=t=>{if(t.identity===null)return null;let n=u(t.identity.avatar);if(n===null)return null;let r=s.get(n.cacheKey);if(r!==void 0)return l(n.cacheKey,r),r;if(!c.has(n.cacheKey)){let t=nm(e.storage,{url:n.url,key:n.key},wp.avatar).then(e=>(c.get(n.cacheKey)===t&&c.delete(n.cacheKey),e===null?null:(l(n.cacheKey,e),!_&&oE(y).some(e=>(e.identity===null?null:u(e.identity.avatar))?.cacheKey===n.cacheKey)&&E(),e)),()=>(c.get(n.cacheKey)===t&&c.delete(n.cacheKey),null));c.set(n.cacheKey,t)}return null},T=()=>oE(y).map(e=>{if(e.identity===null)return{memberId:e.memberId,status:e.status,identity:null,self:e.self};let t=X(e.identity.signKey),n=t?.length===32?pf(t):void 0,r=w(e);return{memberId:e.memberId,status:e.status,identity:{handle:e.identity.handle,name:e.identity.name,displayName:e.identity.displayName,avatar:r,...n===void 0?{}:{identicon:n},signKey:e.identity.signKey,...e.status===`friend`?{nickname:e.nickname}:{}},self:e.self}}),E=()=>{if(!(_||g===null))try{let e=g(T());e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}},D=async()=>{if(_||S===null)return;let e=n(),t=YT({roomId:p,memberId:m,at:e,signKey:S.keys.signKey,dhKey:S.keys.dhKey,name:S.name,displayName:S.displayName,avatarUrl:S.avatarUrl},S.keys.signSeed);aE(y,m,t,e,x),b=nA(b,e,r),O(),E(),h!==null&&await Promise.resolve(h(JSON.stringify(t))).catch(()=>{})},O=()=>{if(C(),_||S===null)return;let e=b.dueAt,t=b.heartbeatAt,r=e===null?t:t===null?e:Math.min(e,t);if(r===null)return;let a=Math.ceil(Math.max(0,r-n()));v=i(()=>{v=null,!(_||S===null)&&(tA(b,n())?D():O())},a)},k=async()=>{_||(_=!0,C(),o.delete(k))};o.add(k);let A=await uA(e);if(_)return oA();if(A.availability===`ready`){let i=await cp(e);if(_)return oA();let a=t?.appId,o=i.ok&&a!==void 0?LT(i.roster,a):null;if(i.ok&&a!==void 0&&o===null&&e.writerId!==void 0&&e.exclusive!==void 0)try{let r=await UT({cloud:e.cloud,writerId:e.writerId,exclusive:e.exclusive},a,n());r.outcome.ok&&r.wrote&&t?.onRosterChange?.()}catch{}if(_)return oA();if(o?.presence===`blocked`||a!==void 0&&!i.ok)eE(y,m);else{let e=i.ok?lA(i.roster):{roster:cA,displayName:``,avatarUrl:``};x=e.roster,S={name:A.name,displayName:e.displayName,avatarUrl:e.avatarUrl,keys:A.keys};let t=n();aE(y,m,YT({roomId:p,memberId:m,at:t,signKey:S.keys.signKey,dhKey:S.keys.dhKey,name:S.name,displayName:S.displayName,avatarUrl:S.avatarUrl},S.keys.signSeed),t,x),b=eA(b,{kind:`attach`},t,r),O(),S.avatarUrl!==``&&T()}}else eE(y,m);return{participants:async()=>_?[]:T(),ingest:async(e,t,i,a)=>{if(_||!sA(e)||typeof t!=`string`||typeof i!=`number`||!Number.isFinite(i))return!1;let o;try{o=JSON.parse(t)}catch{return!1}if(typeof o!=`object`||!o)return!1;if(o.t===`social.whois`)return S!==null&&(b=eA(b,{kind:`whois`},n(),r),O()),!0;let s=aE(y,e,o,i,x);return s&&E(),s},memberJoined:async e=>{!_&&sA(e)&&(eE(y,e),S!==null&&e!==m&&(b=eA(b,{kind:`joined`,memberId:e},n(),r),O()),E())},memberLeft:async e=>{!_&&sA(e)&&(tE(y,e),E())},announce:async()=>{await D()},detach:k}},detachAll:async()=>{for(let e of Array.from(o))await e()}}},fA=e=>e.brokered===!0&&(e.from===Vu||e.from===Wu),pA=e=>e.brokered===!0&&Nh(e.from)?e.from:null,mA={state:`not-here`},hA=async(e,t,n)=>{let r=pA(e);return r===null?t:n(r)},gA=e=>fA(e)?e.remote:null,_A=(e,t,n={protocol:2,min:1})=>({hello:async()=>n,openInvite:async n=>{if(!fA(e))return{ok:!1,reason:`not-here`};let r=typeof n==`string`?uE(n):null;return t.onInvite(r),r===null?{ok:!1,reason:`malformed`}:{ok:!0}},openAdd:async n=>{if(!fA(e))return{ok:!1,reason:`not-here`};let r=typeof n==`string`?of(n):null,i=r?.ok===!0?r.name:null;return t.onAdd(i),i===null?{ok:!1,reason:`malformed`}:{ok:!0}},openEdit:async()=>fA(e)?(t.onEdit(),{ok:!0}):{ok:!1,reason:`not-here`},openPath:async n=>{if(!fA(e))return{ok:!1,reason:`not-here`};if(!IS(n))return{ok:!1,reason:`malformed`};let r=PS(n);return r===null?{ok:!1,reason:`malformed`}:(t.onPath?.(r),{ok:!0})},ownKey:async()=>fA(e)?t.own():null,openFriends:async n=>fA(e)?fT(n)?t.friends(n):{ok:!1,reason:`none`}:{ok:!1,reason:`not-here`},deleteEntries:async n=>fA(e)?t.page.deleteEntries(n):{ok:!1,reason:`not-here`},setFavourite:async n=>fA(e)?t.page.setFavourite(n):{ok:!1,reason:`not-here`},deleteComments:async n=>fA(e)?t.page.deleteComments(n):{ok:!1,reason:`not-here`},sendComment:async n=>fA(e)?t.page.sendComment(n):{ok:!1,reason:`not-here`},publishing:()=>hA(e,mA,e=>t.apps.publishing(e)),allowPublishing:n=>hA(e,mA,e=>t.apps.allow(e,n)),publish:n=>hA(e,{ok:!1,reason:`not-here`},e=>t.apps.publish(e,n)),stopPublishing:()=>hA(e,mA,e=>t.apps.stop(e)),state:async()=>e.brokered===!0&&t.presence!==void 0?t.presence.state():`unavailable`,attach:async n=>e.brokered===!0&&t.presence!==void 0?t.presence.attach(n):oA()}),vA=`social.writer`,yA=e=>{try{let t=e(),n=t.getItem(vA);if(n!==null&&/^[A-Za-z0-9_-]{22}$/.test(n))return n;let r=Y(crypto.getRandomValues(new Uint8Array(16)));return t.setItem(vA,r),t.getItem(`social.writer`)===r?r:null}catch{return null}},bA=`social.roster`,xA=Promise.resolve(),SA=e=>{let t=globalThis.navigator?.locks;if(t)return t.request(bA,e);let n=xA.then(e,e);return xA=n.catch(()=>{}),n},CA={open:async e=>{typeof e==`string`&&new URL(e).protocol===`https:`&&window.open(e,`_blank`,`noopener,noreferrer`)}},wA=e=>{if(typeof e!=`object`||!e)return!1;let{code:t,message:n}=e;return t===`denied`&&typeof n==`string`&&n.includes(`own frame`)},TA=async()=>{if(typeof window>`u`||window.parent===window||window.parent!==window.top)return!1;let e=ao(`shell.isAppTab`).then(e=>e.shell?.isAppTab?.()).then(e=>e===!0,()=>!1);return Promise.race([e,new Promise(e=>setTimeout(e,$a,!1))])},EA=()=>{let e=[],t=new Set;return{hand:n=>{t.size===0&&e.push(n);for(let e of t)e(n)},take:n=>{t.add(n);for(let t of e.splice(0))n(t);return()=>{t.delete(n)}}}},DA=({services:e,invites:t,adds:n,edits:r,resolveAppName:i})=>{let[a,o]=K(`checking`),s=J(null),c=vu(async()=>{if(await So().catch(()=>null)===null){oc(Hu).catch(()=>{}),o(`signed-out`);return}o(e=>e===`open`||e===`direct`?e:`opening`)},[]);return q(()=>{c();let e=Co(()=>void c());return()=>{e.then(e=>e())}},[c]),q(()=>{if(a!==`opening`||s.current===null)return;let e=s.current,t=!1;return(async()=>{let n=await Bk(Hu,CA)();if(!t){if(!Ak(await n.hello()).usable){t||o(`outdated`);return}if(await ac(Hu,{element:e}),t){oc(Hu).catch(()=>{});return}o(`open`)}})().catch(e=>{t||o(wA(e)?`direct`:`failed`)}),()=>{t=!0}},[a]),a===`direct`?Q(Ck,{services:e,unlock:ss,onAccountChange:Co,invites:t,adds:n,edits:r,resolveAppName:i,site:()=>CA}):Q(G,{children:[Q(`div`,{className:`social-frame`,ref:s}),a!==`open`&&(a===`checking`||a===`opening`?Q(Xm,{state:`opening`,label:`Opening...`}):Q(Ym,{children:[Q(`h1`,{children:`FKN Social`}),a===`signed-out`?Q(G,{children:[Q(`p`,{children:`Sign in to FKN to manage your identity and friends.`}),Q(`div`,{className:`social-row`,children:Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>void xo().then(c),children:`Sign in`})})]}):a===`outdated`?Q(`p`,{children:`This page is older than FKN Social. Reload it to update.`}):Q(G,{children:[Q(`p`,{children:`FKN Social could not open. Try again or open it at social.fkn.app.`}),Q(`div`,{className:`social-row`,children:[Q(`button`,{type:`button`,className:`social-primary`,onClick:()=>o(`opening`),children:`Try again`}),Q(`a`,{className:`social-action`,href:Vu,target:`_blank`,rel:`noopener noreferrer`,children:`Open social.fkn.app`})]})]})]}))]})};(e=>{let t=EA(),n=EA(),r=EA(),i=EA(),a=new Set,o=()=>{for(let e of a)e()},s=e=>(a.add(e),()=>{a.delete(e)}),c=null,l={account:{availability:Qo,encryption:os},cloud:kf({list:Hs,readFileSealed:Us,writeFile:(e,t)=>Vs.writeFile(e,new TextEncoder().encode(t)),unlink:e=>Vs.unlink(e),isNotFound:Ao}),rooms:{open:Gc,create:Kc,join:qc},storage:{put:e=>sl(e),get:(e,t)=>ll(e,t),delete:dl,list:()=>ul()},sleep:e=>new Promise(t=>setTimeout(t,e)),writerId:yA(()=>localStorage),exclusive:SA},u=HT(l,{onRosterChange:o}),d=Kk(l,{onRosterChange:o}),f=Zh(),p=new Map,m=e=>`${e.from}\0${e.protocol??``}`;bc(e=>{let a=e.brokered===!0?dA(l,{appId:fA(e)?void 0:pA(e)??void 0,onRosterChange:o}):void 0;if(a!==void 0){let t=m(e),n=p.get(t);n===void 0?p.set(t,[a]):n.push(a)}return _A(e,{onInvite:t.hand,onAdd:n.hand,onEdit:()=>r.hand(!0),onPath:i.hand,...yT(l),apps:u,page:d,presence:a})},e=>{if(c=gA(e)??c,e.brokered===!0){let t=m(e),n=p.get(t),r=n?.shift();n!==void 0&&n.length===0&&p.delete(t),r!==void 0&&e.closed.then(()=>void r.detachAll())}}),Ok();let h=!1;xc(e=>{e&&!h&&(h=!0,zu(document.body.appendChild(document.createElement(`div`))).render(Q(Ck,{services:l,unlock:ss,onAccountChange:Co,invites:t.take,adds:n.take,edits:r.take,paths:i.take,onRosterChange:s,resolveAppName:f,site:()=>c})))}),(e?.isAppTab??TA)().then(e=>{e&&!h&&(h=!0,zu(document.body.appendChild(document.createElement(`div`))).render(Q(DA,{services:l,invites:t.take,adds:n.take,edits:r.take,resolveAppName:f})))})})();