wire-mesh 3.6.3 → 3.6.4
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.
|
@@ -77,4 +77,4 @@ ${Vg.repeat(a.depth)}}`:a.close=`}`;break}case W.TAG:o+=String(c),o+=Wg(W.POS_IN
|
|
|
77
77
|
|
|
78
78
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function IC(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;IC(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var LC=new Set([`type`,`properties`,`required`,`additionalProperties`]),RC=[`oneOf`,`anyOf`];function zC(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function BC(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!LC.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??zC(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}av(n,r,e.length===1?e[0]:BC(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=zC(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function VC(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of LC)if(t in e)return;let n=t.filter(e=>RC.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=BC(t);else{let e=n[0],i=RC.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>BC([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,AC(e,r))}function HC(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):AC(i,s),AC(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())IC(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])VC(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}AC(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,av(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:GC(t,`input`,e.processors),output:GC(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function UC(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return UC(r.element,n);if(r.type===`set`)return UC(r.valueType,n);if(r.type===`lazy`)return UC(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return UC(r.innerType,n);if(r.type===`intersection`)return UC(r.left,n)||UC(r.right,n);if(r.type===`record`||r.type===`map`)return UC(r.keyType,n)||UC(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:UC(r.in,n)||UC(r.out,n);if(r.type===`object`){for(let e in r.shape)if(UC(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(UC(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(UC(e,n))return!0;return!!(r.rest&&UC(r.rest,n))}return!1}var WC=(e,t={})=>n=>{let r=jC({...n,processors:t});return NC(e,r),FC(r,e),HC(r,e)},GC=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=jC({...i??{},target:a,io:t,processors:n});return NC(e,o),FC(o,e),HC(o,e)},KC={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},qC=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=KC[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},JC=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):MC(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},YC=(e,t,n,r)=>{n.type=`boolean`},XC=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ZC=(e,t,n,r)=>{n.not={}},QC=(e,t,n,r)=>{let i=e._zod.def,a=X_(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},$C=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(MC(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(MC(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ew=(e,t,n,r)=>{MC(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},tw=(e,t,n,r)=>{MC(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},nw=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=NC(a.element,t,{...r,path:[...r.path,`items`]})};function rw(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rw(t.out):t.type===`catch`?rw(t.innerType):e._zod.optin}var iw=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&MC(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)av(i.properties,e,NC(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?rw(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=NC(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},aw=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>NC(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ow=(e,t,n,r)=>{let i=e._zod.def,a=NC(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=NC(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},sw=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>NC(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?NC(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rw(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=e._zod.bag;typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cw(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cw(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cw(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?ob:ab).source),p):p}var lw=new WeakMap;function uw(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of lw.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cw(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var dw=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=NC(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)av(i.patternProperties,t.source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=NC(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=lw.get(t);n||(n=[],lw.set(t,n),t.deferred.push(()=>uw(t))),n.push(e)}i.additionalProperties=NC(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rw(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fw=(e,t,n,r)=>{let i=e._zod.def,a=NC(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pw=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},mw=Symbol();function hw(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(MC(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),mw):JSON.parse(o)}var gw=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hw(i.defaultValue,e,t,n,r);o!==mw&&(n.default=o)},_w=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hw(i.defaultValue,e,t,n,r);o!==mw&&(n._prefault=o)},vw=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{MC(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},yw=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;NC(o,t,r);let s=t.seen.get(e);s.ref=o},bw=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xw=(e,t,n,r)=>{let i=e._zod.def;NC(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Sw=(e,t,n,r)=>{let i=e._zod.innerType;NC(i,t,r);let a=t.seen.get(e);a.ref=i},Cw=new WeakSet([Object.prototype,Error.prototype]);function ww(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Tw=K(`ZodError`,(e,t)=>{dy.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Cw.has(n)||(Cw.add(n),ww(n,`format`,e=>t=>hy(e,t)),ww(n,`flatten`,e=>t=>my(e,t)),ww(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Q_,2)}),ww(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Q_,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Ew=_y(Tw),Dw=vy(Tw),Ow=yy(Tw),kw=xy(Tw),Aw=Cy(Tw),jw=wy(Tw),Mw=Ty(Tw),Nw=Ey(Tw),Pw=Dy(Tw),Fw=Oy(Tw),Iw=ky(Tw),Lw=Ay(Tw);function Rw(){ny.localeError||ry(SS())}function zw(){ny.memoizer||ry({memoizer:yS()})}var Bw=K(`ZodType`,(e,t)=>(Rw(),jb.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ov(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return gv(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(lE(e,t))},superRefine(e,t){return this.check(uE(e,t))},overwrite(e){return this.check(bC(e))},optional(){return WT(this)},exactOptional(){return KT(this)},nullable(){return JT(this)},nullish(){return WT(JT(this))},nonoptional(e){return eE(this,e)},array(){return TT(this)},or(e){return kT([this,e])},and(e){return NT(this,e)},transform(e){return iE(this,HT(e))},default(e){return XT(this,e)},prefault(e){return QT(this,e)},catch(e){return nE(this,e)},pipe(e){return iE(this,e)},readonly(){return oE(this)},describe(e){let t=this.clone();return ES.add(t,{description:e}),t},meta(...e){if(e.length===0)return ES.get(this);let t=this.clone();return ES.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Bv(this,`~standard`,{...Nb(this),jsonSchema:{input:GC(this,`input`),output:GC(this,`output`)}})},set"~standard"(e){zv(this,`~standard`,e)},parse:function e(t,n){return Ew(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Dw(this,t,n,{callee:e})},safeParse(e,t){return Ow(this,e,t)},async safeParseAsync(e,t){return kw(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){zv(this,`spa`,e)},encode:function e(t,n){return Aw(this,t,n,{callee:e})},decode:function e(t,n){return jw(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Mw(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Nw(this,t,n,{callee:e})},safeEncode(e,t){return Pw(this,e,t)},safeDecode(e,t){return Fw(this,e,t)},async safeEncodeAsync(e,t){return Iw(this,e,t)},async safeDecodeAsync(e,t){return Lw(this,e,t)},toJSONSchema(e){return WC(this,{})(e)},get description(){return ES.get(this)?.description},get _def(){return this._zod.def}}),Vw=K(`_ZodString`,(e,t)=>{Pb.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qC(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(mC(...e))},includes(...e){return this.check(_C(...e))},startsWith(...e){return this.check(vC(...e))},endsWith(...e){return this.check(yC(...e))},min(...e){return this.check(fC(...e))},max(...e){return this.check(dC(...e))},length(...e){return this.check(pC(...e))},nonempty(...e){return this.check(fC(1,...e))},lowercase(e){return this.check(hC(e))},uppercase(e){return this.check(gC(e))},trim(){return this.check(SC())},normalize(...e){return this.check(xC(...e))},toLowerCase(){return this.check(CC())},toUpperCase(){return this.check(wC())},slugify(){return this.check(TC())}}),Hw=K(`ZodString`,(e,t)=>{Pb.init(e,t),Vw.init(e,t)},{email(e){return this.check(OS(Jw,e))},url(e){return this.check(PS(Zw,e))},jwt(e){return this.check(YS(fT,e))},emoji(e){return this.check(FS(Qw,e))},guid(e){return this.check(kS(Yw,e))},uuid(e){return this.check(AS(Xw,e))},uuidv4(e){return this.check(jS(Xw,e))},uuidv6(e){return this.check(MS(Xw,e))},uuidv7(e){return this.check(NS(Xw,e))},nanoid(e){return this.check(IS($w,e))},cuid(e){return this.check(LS(eT,e))},cuid2(e){return this.check(RS(tT,e))},ulid(e){return this.check(zS(nT,e))},base64(e){return this.check(KS(lT,e))},base64url(e){return this.check(qS(uT,e))},xid(e){return this.check(BS(rT,e))},ksuid(e){return this.check(VS(iT,e))},ipv4(e){return this.check(HS(aT,e))},ipv6(e){return this.check(US(oT,e))},cidrv4(e){return this.check(WS(sT,e))},cidrv6(e){return this.check(GS(cT,e))},e164(e){return this.check(JS(dT,e))},datetime(e){return this.check(XS(Ww,e))},date(e){return this.check(ZS(Gw,e))},time(e){return this.check(QS(Kw,e))},duration(e){return this.check($S(qw,e))}});function q(e){return DS(Hw,e)}var Uw=K(`ZodStringFormat`,(e,t)=>{Fb.init(e,t),Vw.init(e,t)}),Ww=K(`ZodISODateTime`,(e,t)=>{Qb.init(e,t),Uw.init(e,t)}),Gw=K(`ZodISODate`,(e,t)=>{$b.init(e,t),Uw.init(e,t)}),Kw=K(`ZodISOTime`,(e,t)=>{ex.init(e,t),Uw.init(e,t)}),qw=K(`ZodISODuration`,(e,t)=>{tx.init(e,t),Uw.init(e,t)}),Jw=K(`ZodEmail`,(e,t)=>{Rb.init(e,t),Uw.init(e,t)}),Yw=K(`ZodGUID`,(e,t)=>{Ib.init(e,t),Uw.init(e,t)}),Xw=K(`ZodUUID`,(e,t)=>{Lb.init(e,t),Uw.init(e,t)}),Zw=K(`ZodURL`,(e,t)=>{Wb.init(e,t),Uw.init(e,t)}),Qw=K(`ZodEmoji`,(e,t)=>{Gb.init(e,t),Uw.init(e,t)}),$w=K(`ZodNanoID`,(e,t)=>{Kb.init(e,t),Uw.init(e,t)}),eT=K(`ZodCUID`,(e,t)=>{qb.init(e,t),Uw.init(e,t)}),tT=K(`ZodCUID2`,(e,t)=>{Jb.init(e,t),Uw.init(e,t)}),nT=K(`ZodULID`,(e,t)=>{Yb.init(e,t),Uw.init(e,t)}),rT=K(`ZodXID`,(e,t)=>{Xb.init(e,t),Uw.init(e,t)}),iT=K(`ZodKSUID`,(e,t)=>{Zb.init(e,t),Uw.init(e,t)}),aT=K(`ZodIPv4`,(e,t)=>{nx.init(e,t),Uw.init(e,t)}),oT=K(`ZodIPv6`,(e,t)=>{ax.init(e,t),Uw.init(e,t)}),sT=K(`ZodCIDRv4`,(e,t)=>{ox.init(e,t),Uw.init(e,t)}),cT=K(`ZodCIDRv6`,(e,t)=>{cx.init(e,t),Uw.init(e,t)}),lT=K(`ZodBase64`,(e,t)=>{ux.init(e,t),Uw.init(e,t)}),uT=K(`ZodBase64URL`,(e,t)=>{fx.init(e,t),Uw.init(e,t)}),dT=K(`ZodE164`,(e,t)=>{px.init(e,t),Uw.init(e,t)}),fT=K(`ZodJWT`,(e,t)=>{hx.init(e,t),Uw.init(e,t)}),pT=K(`ZodNumber`,(e,t)=>{gx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>JC(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(cC(e,t))},gte(e,t){return this.check(lC(e,t))},min(e,t){return this.check(lC(e,t))},lt(e,t){return this.check(oC(e,t))},lte(e,t){return this.check(sC(e,t))},max(e,t){return this.check(sC(e,t))},int(e){return this.check(hT(e))},safe(e){return this.check(hT(e))},positive(e){return this.check(cC(0,e))},nonnegative(e){return this.check(lC(0,e))},negative(e){return this.check(oC(0,e))},nonpositive(e){return this.check(sC(0,e))},multipleOf(e,t){return this.check(uC(e,t))},step(e,t){return this.check(uC(e,t))},finite(){return this}});function J(e){return eC(pT,e)}var mT=K(`ZodNumberFormat`,(e,t)=>{_x.init(e,t),pT.init(e,t)});function hT(e){return tC(mT,e)}var gT=K(`ZodBoolean`,(e,t)=>{vx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>YC(e,t,n,r)});function _T(e){return nC(gT,e)}var vT=K(`ZodNull`,(e,t)=>{yx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>XC(e,t,n,r)});function yT(e){return rC(vT,e)}var bT=K(`ZodUnknown`,(e,t)=>{bx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function xT(){return iC(bT)}var ST=K(`ZodNever`,(e,t)=>{xx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ZC(e,t,n,r)});function CT(e){return aC(ST,e)}var wT=K(`ZodArray`,(e,t)=>{zw(),Cx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nw(e,t,n,r),e.element=t.element},{min(e,t){return this.check(fC(e,t))},nonempty(e){return this.check(fC(1,e))},max(e,t){return this.check(dC(e,t))},length(e,t){return this.check(pC(e,t))},unwrap(){return this.element}});function TT(e,t){return EC(wT,e,t)}var ET=K(`ZodObject`,(e,t)=>{zw(),Ax.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iw(e,t,n,r),qv(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return zT(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:xT()})},loose(){return this.clone({...this._zod.def,catchall:xT()})},strict(){return this.clone({...this._zod.def,catchall:CT()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Sv(this,e)},safeExtend(e){return Cv(this,e)},merge(e){return wv(this,e)},pick(e){return bv(this,e)},omit(e){return xv(this,e)},partial(...e){return Tv(UT,this,e[0])},exactPartial(...e){return Tv(GT,this,e[0],`exactPartial`)},required(...e){return Ev($T,this,e[0])}});function Y(e,t){return new ET({type:`object`,shape:e??{},...G(t)})}function DT(e,t){return new ET({type:`object`,shape:e,catchall:CT(),...G(t)})}var OT=K(`ZodUnion`,(e,t)=>{Mx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aw(e,t,n,r),e.options=t.options});function kT(e,t){return new OT({type:`union`,options:e,...G(t)})}var AT=K(`ZodDiscriminatedUnion`,(e,t)=>{OT.init(e,t),Nx.init(e,t)});function jT(e,t,n){return new AT({type:`union`,options:t,discriminator:e,...G(n)})}var MT=K(`ZodIntersection`,(e,t)=>{Px.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ow(e,t,n,r)});function NT(e,t){return new MT({type:`intersection`,left:e,right:t})}var PT=K(`ZodTuple`,(e,t)=>{zw(),Lx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sw(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new UT({type:`optional`,innerType:e}))})}});function FT(e,t,n){let r=t instanceof jb;return new PT({type:`tuple`,items:e,rest:r?t:null,...G(r?n:t)})}var IT=K(`ZodRecord`,(e,t)=>{zw(),Vx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dw(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function LT(e,t,n){return!t||!t._zod?new IT({type:`record`,keyType:q(),valueType:e,...G(t)}):new IT({type:`record`,keyType:e,valueType:t,...G(n)})}var RT=K(`ZodEnum`,(e,t)=>{Hx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>QC(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new RT({...t,checks:[],...G(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new RT({...t,checks:[],...G(r),entries:i})}});function zT(e,t){return new RT({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...G(t)})}var BT=K(`ZodLiteral`,(e,t)=>{Ux.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$C(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function X(e,t){return new BT({type:`literal`,values:Array.isArray(e)?e:[e],...G(t)})}var VT=K(`ZodTransform`,(e,t)=>{zw(),Wx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tw(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ty(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Lv(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Lv(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function HT(e){return new VT({type:`transform`,transform:e})}var UT=K(`ZodOptional`,(e,t)=>{Kx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function WT(e){return new UT({type:`optional`,innerType:e})}var GT=K(`ZodExactOptional`,(e,t)=>{qx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function KT(e){return new GT({type:`optional`,innerType:e})}var qT=K(`ZodNullable`,(e,t)=>{Jx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function JT(e){return new qT({type:`nullable`,innerType:e})}var YT=K(`ZodDefault`,(e,t)=>{Yx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function XT(e,t){return new YT({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():pv(t)}})}var ZT=K(`ZodPrefault`,(e,t)=>{Zx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_w(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function QT(e,t){return new ZT({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():pv(t)}})}var $T=K(`ZodNonOptional`,(e,t)=>{Qx.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function eE(e,t){return new $T({type:`nonoptional`,innerType:e,...G(t)})}var tE=K(`ZodCatch`,(e,t)=>{tS.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nE(e,t){return new tE({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Yv(t)})}var rE=K(`ZodPipe`,(e,t)=>{nS.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yw(e,t,n,r),e.in=t.in,e.out=t.out});function iE(e,t){return new rE({type:`pipe`,in:e,out:t})}var aE=K(`ZodReadonly`,(e,t)=>{iS.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bw(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function oE(e){return new aE({type:`readonly`,innerType:e})}var sE=K(`ZodLazy`,(e,t)=>{oS.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sw(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Z(e){return new sE({type:`lazy`,getter:e})}var cE=K(`ZodCustom`,(e,t)=>{sS.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ew(e,t,n,r)});function lE(e,t={}){return DC(cE,e,t)}function uE(e,t){return OC(e,t)}function dE(e,t={}){let n=new cE({type:`custom`,check:`custom`,fn:t=>t instanceof e,abort:!0,...G(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:`invalid_type`,expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}var fE=Z(()=>dE(Uint8Array).refine(e=>e.length===16,{message:`expected exactly 16 bytes`})),pE=Z(()=>Y({verb:X(`bulk.open`),"transfer-id":Z(()=>fE),"total-size":J().int().nonnegative().optional(),"content-type":q().optional()}).catchall(xT())),mE=Z(()=>Y({verb:X(`bulk.resume`),"transfer-id":Z(()=>fE),"ack-seq":J().int().nonnegative()}).catchall(xT())),hE=Z(()=>Y({verb:X(`bulk.cancel`),"transfer-id":Z(()=>fE),reason:q().optional()}).catchall(xT())),gE=Z(()=>kT([kT([Z(()=>pE),Z(()=>mE),Z(()=>hE)]),kT([Z(()=>CE),Z(()=>wE),Z(()=>TE),Z(()=>EE),Z(()=>DE),Z(()=>OE),Z(()=>kE),Z(()=>AE)]),Y({}).catchall(xT()),Z(()=>KE),Z(()=>JE),Z(()=>QE),Z(()=>$E),kT([Z(()=>rD),Z(()=>iD),Z(()=>aD),Z(()=>oD)]),kT([Z(()=>cD),Z(()=>lD)]),Z(()=>uD),kT([Z(()=>wD),Z(()=>TD),Z(()=>ED)]),kT([Z(()=>DD),Z(()=>OD),Z(()=>kD)]),Z(()=>eO),kT([Z(()=>rO),Z(()=>iO),Z(()=>aO),Z(()=>tO)])])),_E=Z(()=>Y({type:X(`bulk-data`),"transfer-id":Z(()=>fE),seq:J().int().nonnegative(),bytes:dE(Uint8Array)})),vE=Z(()=>Y({type:X(`bulk-ack`),"transfer-id":Z(()=>fE),"ack-seq":J().int().nonnegative(),window:J().int().nonnegative()})),yE=Z(()=>Y({type:X(`bulk-end`),"transfer-id":Z(()=>fE),digest:dE(Uint8Array)})),bE=Z(()=>Y({type:X(`data-have`),peer:Z(()=>BE),"head-seq":J().int().nonnegative()})),xE=Z(()=>Y({type:X(`data-request`),peer:Z(()=>BE),"from-seq":J().int().nonnegative()})),SE=Z(()=>Y({type:X(`data-entries`),peer:Z(()=>BE),"from-seq":J().int().nonnegative(),entries:TT(dE(Uint8Array))}));Z(()=>Y({handle:q(),"device-id":Z(()=>BE),"identity-key":Z(()=>zE),candidates:TT(Z(()=>GD)).optional(),mailboxes:TT(Z(()=>BE)).optional(),issued:J().int().nonnegative(),expires:J().int().nonnegative()})),Z(()=>Z(()=>ID));var CE=Z(()=>Y({verb:X(`pty.spawn`),shell:q().optional(),argv:TT(q()),cwd:q().optional(),env:Y({}).catchall(q()),cols:J().int().nonnegative(),rows:J().int().nonnegative()})),wE=Z(()=>Y({verb:X(`pty.write`),session:Z(()=>_D),bytes:dE(Uint8Array)})),TE=Z(()=>Y({verb:X(`pty.resize`),session:Z(()=>_D),cols:J().int().nonnegative(),rows:J().int().nonnegative()})),EE=Z(()=>Y({verb:X(`pty.kill`),session:Z(()=>_D),signal:J().int()})),DE=Z(()=>Y({verb:X(`proc.spawn`),argv:TT(q()),cwd:q().optional(),env:Y({}).catchall(q())})),OE=Z(()=>Y({verb:X(`proc.signal`),session:Z(()=>_D),signal:J().int()})),kE=Z(()=>Y({verb:X(`proc.kill`),session:Z(()=>_D)})),AE=Z(()=>Y({verb:X(`exec.list`)}));Z(()=>Y({session:Z(()=>_D),kind:kT([X(`pty`),X(`proc`)]),argv:TT(q()).optional(),cwd:q().optional()}));var jE=Z(()=>kT([Z(()=>RE),Z(()=>zD),Z(()=>BD),Z(()=>VD),Z(()=>UD),Z(()=>KD),Z(()=>qD),Z(()=>JD),Z(()=>YD),Z(()=>XD),Z(()=>ZD),Z(()=>QD),Z(()=>$D),Z(()=>HE),Z(()=>GE),Z(()=>ZE),Z(()=>vD),Z(()=>yD),Z(()=>bD),Z(()=>bE),Z(()=>xE),Z(()=>SE),Z(()=>_E),Z(()=>vE),Z(()=>yE),Z(()=>hD),Z(()=>gD)])),ME=Z(()=>Z(()=>jE)),NE=Z(()=>J().int().nonnegative()),PE=Z(()=>kT([Z(()=>FE),Z(()=>IE),Z(()=>LE)])),FE=Z(()=>kT([X(`core/management`),X(`core/exec`),X(`core/data`),X(`core/federation`),X(`core/webrtc`),X(`core/room`),X(`core/bulk`),X(`core/version`)])),IE=Z(()=>q().regex(RegExp(`[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+/[A-Za-z0-9_.-]+`))),LE=Z(()=>q().regex(RegExp(`x-[A-Za-z0-9_.-]+`))),RE=Z(()=>Y({type:X(`handshake`),version:Z(()=>NE),domains:TT(Z(()=>PE)),params:Y({}).catchall(xT()).optional()})),zE=Z(()=>Y({alg:J().int(),"public-key":dE(Uint8Array)})),BE=Z(()=>dE(Uint8Array).refine(e=>e.length===32,{message:`expected exactly 32 bytes`}));Z(()=>Y({"device-id":Z(()=>BE),"identity-key":Z(()=>zE),certificate:dE(Uint8Array).optional()}));var VE=Z(()=>Y({verb:Z(()=>AD),params:Z(()=>gE)})),HE=Z(()=>Y({type:X(`manage-request`),"request-id":J().int().nonnegative(),command:Z(()=>VE),scope:Z(()=>PD),token:Z(()=>LD).optional()})),UE=Z(()=>Y({result:X(`ok`)}).catchall(xT())),WE=Z(()=>Y({result:X(`error`),code:q(),message:q().optional()})),GE=Z(()=>Y({type:X(`manage-response`),"request-id":J().int().nonnegative(),outcome:kT([Z(()=>UE),Z(()=>WE)])})),KE=Z(()=>Y({verb:X(`capability.request`),capability:q(),"valid-until":J().int().nonnegative().optional()}).catchall(xT())),qE=Z(()=>Y({result:X(`ok`),"granted-token":Z(()=>LD)}).catchall(xT())),JE=Z(()=>Y({verb:X(`capability.grant`),"granted-token":Z(()=>LD)}).catchall(xT())),YE=Z(()=>Y({"token-id":dE(Uint8Array),issuer:Z(()=>BE),"issuer-key":Z(()=>zE),"revoked-at":J().int().nonnegative(),authorization:dE(Uint8Array).optional()})),XE=Z(()=>Z(()=>ID)),ZE=Z(()=>Y({type:X(`revocation-announce`),entries:TT(Z(()=>XE))})),QE=Z(()=>Y({verb:X(`path.trace`)}));Z(()=>Y({result:X(`ok`),relayed:_T(),"hub-address":q().optional()}).catchall(xT())),Z(()=>Y({direct:TT(Z(()=>BE)),relayed:TT(Y({device:Z(()=>BE),via:Z(()=>BE).optional()}))}));var $E=Z(()=>Y({verb:X(`topology.get`)})),eD=Z(()=>kT([Z(()=>tD),Z(()=>nD)]));Z(()=>q().regex(RegExp(`[0-9a-f]{64}`)));var tD=Z(()=>q().regex(RegExp(`[0-9a-f]{64}/[A-Za-z0-9_-]+`))),nD=Z(()=>q().regex(RegExp(`[0-9a-f]{64}\\+[0-9a-f]{64}`))),rD=Z(()=>Y({verb:X(`room.send`),"message-id":dE(Uint8Array),"sent-at":J().int().nonnegative(),text:q(),"content-type":q().optional(),refs:TT(Z(()=>sD)).optional()}).catchall(xT())),iD=Z(()=>Y({verb:X(`room.read`),messages:TT(dE(Uint8Array)),at:J().int().nonnegative()}).catchall(xT())),aD=Z(()=>Y({verb:X(`room.leave`)}).catchall(xT())),oD=Z(()=>Y({verb:X(`room.members`)}).catchall(xT())),sD=Z(()=>Y({id:dE(Uint8Array),relation:q()})),cD=Z(()=>Y({verb:X(`room.join`)}).catchall(xT())),lD=Z(()=>Y({verb:X(`room.invite`),invitee:Z(()=>BE),token:Z(()=>LD)}).catchall(xT())),uD=Z(()=>Y({verb:X(`room.rekey`),"key-epoch":J().int().nonnegative(),"wrapped-key":kT([dE(Uint8Array),TT(dE(Uint8Array))])}).catchall(xT())),dD=Z(()=>Y({device:Z(()=>BE)}).catchall(xT())),fD=Z(()=>Y({result:X(`ok`),"granted-token":Z(()=>LD),members:TT(Z(()=>dD))}).catchall(xT()));Z(()=>Y({result:X(`ok`),members:TT(Z(()=>dD))}).catchall(xT()));var pD=Z(()=>Z(()=>ID)),mD=Z(()=>Y({room:Z(()=>eD),poster:Z(()=>BE),"poster-key":Z(()=>zE),token:Z(()=>LD),"notice-id":dE(Uint8Array),"posted-at":J().int().nonnegative(),"content-type":q(),content:dE(Uint8Array),refs:TT(Z(()=>sD)).optional(),"valid-until":J().int().nonnegative().optional(),"key-epoch":J().int().nonnegative().optional()}).catchall(xT())),hD=Z(()=>Y({type:X(`secure-hello`),"ephemeral-key":dE(Uint8Array).refine(e=>e.length===65,{message:`expected exactly 65 bytes`}),nonce:dE(Uint8Array).refine(e=>e.length===16,{message:`expected exactly 16 bytes`}),"identity-key":Z(()=>zE),"to-device":Z(()=>BE),signature:dE(Uint8Array)})),gD=Z(()=>Y({type:X(`secure-data`),counter:J().int().nonnegative(),ciphertext:dE(Uint8Array)})),_D=Z(()=>J().int().nonnegative()),vD=Z(()=>Y({type:X(`stream-data`),session:Z(()=>_D),seq:J().int().nonnegative(),channel:q(),bytes:dE(Uint8Array)})),yD=Z(()=>Y({type:X(`stream-ack`),session:Z(()=>_D),"ack-seq":J().int().nonnegative(),window:J().int().nonnegative()})),bD=Z(()=>Y({type:X(`stream-end`),session:Z(()=>_D),"exit-code":J().int().optional(),"exit-signal":J().int().optional()})),xD=Z(()=>J().int().nonnegative()),SD=Z(()=>Y({kind:kT([X(`capability-token`),X(`revocation-entry`),X(`handle-record`),X(`room-notice`),q()]),protected:dE(Uint8Array),payload:dE(Uint8Array)})),CD=Z(()=>Y({participant:Z(()=>BE),hiding:dE(Uint8Array),binding:dE(Uint8Array)})),wD=Z(()=>Y({verb:X(`threshold.commit`),"session-id":Z(()=>xD),group:Z(()=>BE),subject:Z(()=>SD),deadline:J().int().nonnegative()})),TD=Z(()=>Y({verb:X(`threshold.sign`),"session-id":Z(()=>xD),commitments:TT(Z(()=>CD))}));Z(()=>Y({"session-id":Z(()=>xD),group:Z(()=>BE),share:dE(Uint8Array),issuer:Z(()=>BE),"issuer-key":Z(()=>zE)})),Z(()=>Z(()=>ID));var ED=Z(()=>Y({verb:X(`threshold.abort`),"session-id":Z(()=>xD),reason:q().optional()})),DD=Z(()=>Y({verb:X(`threshold.keygen-round1`),"session-id":Z(()=>xD),threshold:J().int().nonnegative(),participants:TT(Z(()=>BE)),commitment:TT(dE(Uint8Array)),"proof-of-knowledge":dE(Uint8Array).optional(),"existing-group-key":dE(Uint8Array).optional()})),OD=Z(()=>Y({verb:X(`threshold.keygen-round2`),"session-id":Z(()=>xD),share:dE(Uint8Array)})),kD=Z(()=>Y({verb:X(`threshold.keygen-confirm`),"session-id":Z(()=>xD),"transcript-digest":dE(Uint8Array),"group-key":dE(Uint8Array)})),AD=Z(()=>kT([Z(()=>jD),Z(()=>MD),Z(()=>ND)])),jD=Z(()=>q().regex(RegExp(`[a-z][a-z0-9-]*:[a-z][a-z0-9-]*`))),MD=Z(()=>q().regex(RegExp(`[a-z0-9.-]+/[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+`))),ND=Z(()=>q().regex(RegExp(`x-[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+`))),PD=Z(()=>Y({kind:q(),path:q().optional()}));Z(()=>X(1)),Z(()=>X(4)),Z(()=>kT([J().int(),q()]));var FD=Z(()=>Y({1:J().int().optional(),4:dE(Uint8Array).optional()}).catchall(xT())),ID=Z(()=>FT([dE(Uint8Array),Z(()=>FD),kT([dE(Uint8Array),yT()]),dE(Uint8Array)])),LD=Z(()=>Z(()=>ID)),RD=Z(()=>Y({"token-id":dE(Uint8Array),issuer:Z(()=>BE),"issuer-key":Z(()=>zE),bearer:Z(()=>BE),capability:Z(()=>AD),scope:Z(()=>PD),expires:J().int().nonnegative(),"not-before":J().int().nonnegative().optional(),parent:dE(Uint8Array).optional(),"authorised-by":dE(Uint8Array).optional(),"delegations-remaining":J().int().nonnegative().optional(),"valid-until":J().int().nonnegative().optional(),conditions:dE(Uint8Array).optional(),"grants-capability":Z(()=>AD).optional(),"requests-capability":Z(()=>AD).optional()}).catchall(xT())),zD=Z(()=>Y({type:X(`ping`)})),BD=Z(()=>Y({type:X(`pong`)})),VD=Z(()=>Y({type:X(`close`),reason:q().optional()})),HD=Z(()=>Y({device:Z(()=>BE),addresses:TT(q()),"snapshot-seconds":J().int(),"identity-key":Z(()=>zE),signature:dE(Uint8Array)}).catchall(xT())),UD=Z(()=>Y({type:X(`gossip`),peers:TT(Z(()=>HD))})),WD=Z(()=>kT([X(`host`),X(`server-reflexive`),X(`relayed`)])),GD=Z(()=>Y({address:q(),kind:Z(()=>WD),priority:J().int().nonnegative()})),KD=Z(()=>Y({type:X(`candidates`),candidates:TT(Z(()=>GD))})),qD=Z(()=>Y({type:X(`sync-punch`),nonce:J().int().nonnegative(),"deadline-unix-ms":J().int().nonnegative()})),JD=Z(()=>Y({type:X(`observed-address`),address:q()})),YD=Z(()=>Y({type:X(`relay-offer`),addresses:TT(q())})),XD=Z(()=>Y({type:X(`relay-connect`),"target-device":Z(()=>BE),"source-device":Z(()=>BE).optional()})),ZD=Z(()=>Y({type:X(`relay-data`),payload:dE(Uint8Array),"to-device":Z(()=>BE).optional(),"from-device":Z(()=>BE).optional()})),QD=Z(()=>Y({type:X(`relay-inbound`),"source-device":Z(()=>BE),"target-device":Z(()=>BE).optional()})),$D=Z(()=>Y({type:X(`coordinator`),term:J().int().nonnegative(),coordinator:Z(()=>BE),"capacity-hint":J().int().nonnegative().optional()})),eO=Z(()=>Y({verb:X(`version.get`)})),tO=Z(()=>Y({verb:X(`webrtc.sfu-track-map`),"negotiation-id":J().int().nonnegative(),tracks:TT(Z(()=>nO))})),nO=Z(()=>Y({mid:q(),member:Z(()=>BE),kind:kT([X(`audio`),X(`video`)])})),rO=Z(()=>Y({verb:X(`webrtc.offer`),"negotiation-id":J().int().nonnegative(),sdp:q()})),iO=Z(()=>Y({verb:X(`webrtc.answer`),"negotiation-id":J().int().nonnegative(),sdp:q()})),aO=Z(()=>Y({verb:X(`webrtc.ice-candidate`),"negotiation-id":J().int().nonnegative(),candidate:Z(()=>oO).optional()})),oO=Z(()=>Y({candidate:q(),"sdp-mid":q().optional(),"sdp-m-line-index":J().int().nonnegative().optional(),"username-fragment":q().optional()})),sO=16,cO=2,lO=64;function uO(e){let t=``;for(let n of e)t+=n.toString(sO).padStart(cO,`0`);return t}function dO(e){return uO(e)}function fO(e){if(!/^([0-9a-f]{2})*$/.test(e))throw Error(`expected an even-length, lowercase hex string, got ${JSON.stringify(e)}`);let t=new Uint8Array(e.length/cO);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*cO,(n+1)*cO),sO);return t}function pO(e){if(e.length!==lO)throw Error(`expected a 64-character lowercase hex string, got ${JSON.stringify(e)}`);return BE.parse(fO(e))}var mO=`pinned-certificates/`;function hO(e){return{recall:async t=>{let n=await e.get(mO+t);return n===void 0?[]:K_(n)},remember:async(t,n)=>{let r=G_(n.map(e=>uO(e)));await e.set(mO+t,new Uint8Array(r))}}}var gO=`wire-mesh-console-identity`,_O=`ES256`,vO=16,yO=2,bO=4;function xO(e){let t=new Uint8Array(e.length/yO);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*yO,(n+1)*yO),vO);return t}function SO(e){try{let t=atob(e.replace(/-/g,`+`).replace(/_/g,`/`));return Uint8Array.from(t,e=>e.charCodeAt(0))}catch{throw Error(`the backup's key is not valid base64url`)}}function CO(e){let{kty:t,crv:n,x:r,y:i,d:a}=e;if(t!==`EC`||n!==`P-256`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)throw Error(`the backup does not hold a P-256 private key`);return{kty:t,crv:n,x:r,y:i,d:a}}function wO(e){return Uint8Array.from([bO,...SO(e.x),...SO(e.y)])}function TO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var EO=new TextEncoder().encode(`wire-mesh console identity backup key-pair check`);async function DO(e,t){let n;try{n=await P_({privateJwk:e,publicKeyRaw:t})}catch(e){throw Error(`the backup's private key cannot be loaded: ${e instanceof Error?e.message:String(e)}`,{cause:e})}let r=await n.sign(EO);if(!await n.verify(n.identityKey,EO,r))throw Error(`the private key does not belong to the backup's public key`)}async function OO(e){let t;try{t=JSON.parse(e)}catch{throw Error(`the file is not JSON`)}if(!TO(t)||t.format!==`wire-mesh-console-identity`||t.version!==1||t.alg!==_O||typeof t.deviceId!=`string`||typeof t.publicKey!=`string`||!TO(t.privateJwk))throw Error(`the file is not a wire-mesh console identity backup`);let n=CO(t.privateJwk),r=wO(n);if(uO(r)!==t.publicKey)throw Error(`the private key does not match the backup's public key`);if(dO(await A_(r))!==t.deviceId)throw Error(`the backup's device-id does not match its public key`);return await DO(n,r),{format:gO,version:1,alg:_O,deviceId:t.deviceId,publicKey:t.publicKey,privateJwk:n}}function kO(e){return{async export(){let t=await e.get(E_);if(t===void 0)throw Error(`no identity is stored on this device`);let n=b_(t,x_);if(!M_(n))throw Error(`stored identity envelope is malformed`);return{format:gO,version:1,alg:_O,deviceId:dO(await A_(n.publicKeyRaw)),publicKey:uO(n.publicKeyRaw),privateJwk:n.privateJwk}},async restore(t){await e.set(E_,new Uint8Array(Mg({privateJwk:t.privateJwk,publicKeyRaw:xO(t.publicKey)},hg)))}}}function AO(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function jO(e){return e.split(`/`).some(e=>e===`.`||e===`..`)}function MO(e,t){return jO(e)||jO(t)?!1:e===t?!0:e.startsWith(t)?t.endsWith(`/`)?!0:e.charAt(t.length)===`/`:!1}function NO(e,t){return e.kind===t.kind?e.path===void 0||t.path!==void 0&&MO(t.path,e.path):!1}var PO=(e,t,n)=>({kind:`complex`,re:e*Math.cos(t),im:e*Math.sin(t),unit:n}),FO=LT(q(),J()),IO=zT([`ms`,`s`,`min`,`h`,`d`]);jT(`kind`,[Y({kind:X(`number`),value:J(),unit:FO.optional()}),Y({kind:X(`text`),value:q()}),Y({kind:X(`boolean`),value:_T()}),Y({kind:X(`instant`),value:q()}),Y({kind:X(`duration`),value:J(),unit:IO}),Y({kind:X(`complex`),re:J(),im:J(),unit:FO.optional()})]);function LO(e){if(e===void 0)return{};let t={};for(let[n,r]of Object.entries(e))r!==0&&(t[n]=r);return t}function RO(e,t){let n=LO(e),r=LO(t),i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>n[e]===r[e])}function zO(e,t){let n=LO(e),r=LO(t),i={...n};for(let[e,t]of Object.entries(r))i[e]=(i[e]??0)+t;return LO(i)}function BO(e,t){let n=LO(e),r=LO(t),i={...n};for(let[e,t]of Object.entries(r))i[e]=(i[e]??0)-t;return LO(i)}Y({code:zT([`not-found`,`wrong-type`,`domain-error`]),message:q()});function Q(e){return{status:`definite`,value:e}}function $(e,t){return{status:`indeterminate`,reason:{code:e,message:t}}}function VO(...e){for(let t of e)if(t?.status===`indeterminate`)return t.reason}var HO=Z(()=>kT([q(),J(),_T(),yT(),TT(HO),LT(q(),HO)])),UO=zT([`gt`,`gte`,`lt`,`lte`,`eq`,`neq`]),WO=zT([`equals`,`notEquals`,`matches`,`notMatches`,`portableMatches`,`portableNotMatches`]),GO=zT([`in`,`notIn`]),KO=zT([`add`,`subtract`,`multiply`,`divide`,`power`,`modulo`]),qO=zT([`first`,`unique`]),JO=Y({kind:X(`not`),get operand(){return ok}}),YO=Y({kind:X(`and`),get left(){return ok},get right(){return ok}}),XO=Y({kind:X(`or`),get left(){return ok},get right(){return ok}}),ZO=Y({kind:X(`allOf`),get operands(){return TT(ok)}}),QO=Y({kind:X(`anyOf`),get operands(){return TT(ok)}}),$O=Y({kind:X(`compare`),op:UO,get left(){return xk},get right(){return xk}}),ek=Y({kind:X(`textCompare`),op:WO,get left(){return xk},get right(){return xk}}),tk=Y({kind:X(`memberOf`),op:GO,get operand(){return xk},get candidates(){return TT(xk)}}),nk=Y({kind:X(`exists`),get operand(){return xk}}),rk=Y({kind:X(`some`),collection:HO,get item(){return ok},get filter(){return ok.optional()}}),ik=Y({kind:X(`every`),collection:HO,get item(){return ok},get filter(){return ok.optional()}}),ak=Y({kind:X(`treeReference`),key:HO}),ok=jT(`kind`,[JO,YO,XO,ZO,QO,$O,ek,tk,nk,rk,ik,ak]),sk=Y({kind:X(`numberLiteral`),value:J(),unit:FO.optional()}),ck=Y({kind:X(`textLiteral`),value:q()}),lk=Y({kind:X(`booleanLiteral`),value:_T()}),uk=Y({kind:X(`instantLiteral`),value:q()}),dk=Y({kind:X(`durationLiteral`),value:J(),unit:IO}),fk=kT([DT({kind:X(`complexLiteral`),re:J(),im:J(),unit:FO.optional()}),DT({kind:X(`complexLiteral`),magnitude:J(),phase:J(),unit:FO.optional()})]),pk=Y({kind:X(`reference`),key:HO,unit:FO.optional()}),mk=Y({kind:X(`arithmetic`),op:KO,get left(){return xk},get right(){return xk}}),hk=Y({kind:X(`negate`),get operand(){return xk}}),gk=Y({kind:X(`call`),fn:q(),get args(){return TT(xk)}}),_k=Y({kind:X(`lookup`),table:HO,get keys(){return TT(xk)}}),vk=Y({get when(){return ok},get then(){return xk}}),yk=Y({kind:X(`conditional`),hitPolicy:qO.optional(),get cases(){return TT(vk)},get fallback(){return xk}}),bk=jT(`mode`,[Y({mode:X(`max`),get item(){return xk}}),Y({mode:X(`min`),get item(){return xk}}),Y({mode:X(`reduce`),get initial(){return xk},get combine(){return xk}})]),xk=kT([jT(`kind`,[sk,ck,lk,uk,dk,pk,mk,hk,gk,_k,yk,Y({kind:X(`fold`),collection:HO,get filter(){return ok.optional()},combiner:bk}),Y({kind:X(`accumulator`)}),Y({kind:X(`delegate`),system:q(),payload:HO}),ak]),fk]),Sk={},Ck=1e4;function wk(e,t){let n=0;return{checkNode(r){if(n+=1,n>e)return $(`domain-error`,`evaluation exceeded the maximum of ${e.toString()} nodes visited in a single call (resource exhausted)`);if(r>=t)return $(`domain-error`,`evaluation nesting depth exceeds the maximum of ${t.toString()} (resource exhausted)`)}}}async function Tk(e,t,n,r,i,a,o,s,c,l){let u=await i.resolveCollection(t,r);return Promise.all(u.map(async t=>{if(n===void 0)return{item:t,filterOutcome:`include`};let r=await e(n,t,i,void 0,a,o,s,c,l+1);return r.status===`indeterminate`?{item:t,filterOutcome:r}:{item:t,filterOutcome:r.value?`include`:`exclude`}}))}function Ek(e){for(let{filterOutcome:t}of e)if(t!==`include`&&t!==`exclude`&&t.status===`indeterminate`)return t.reason}function Dk(e,t){return t>=e.from&&t<=e.to}function Ok(e,t){let n=e.ranges.some(e=>Dk(e,t));return e.negated?!n:n}var kk=class extends Error{pattern;index;constructor(e,t,n){super(`invalid pattern at index ${String(t)}: ${n}\n ${e}\n ${` `.repeat(t)}^`),this.name=`RegexParseError`,this.pattern=e,this.index=t}};function Ak(e){return e.charCodeAt(0)}function jk(e,t){return{from:Ak(e),to:Ak(t)}}function Mk(e){let t=Ak(e);return{from:t,to:t}}var Nk=[jk(`0`,`9`)],Pk=[jk(`A`,`Z`),jk(`a`,`z`),jk(`0`,`9`),Mk(`_`)],Fk=[Mk(` `),Mk(` `),Mk(`
|
|
79
79
|
`),Mk(`\r`),Mk(`\f`),Mk(`\v`)];function Ik(e){switch(e){case`d`:return{kind:`charClass`,negated:!1,ranges:Nk};case`D`:return{kind:`charClass`,negated:!0,ranges:Nk};case`w`:return{kind:`charClass`,negated:!1,ranges:Pk};case`W`:return{kind:`charClass`,negated:!0,ranges:Pk};case`s`:return{kind:`charClass`,negated:!1,ranges:Fk};case`S`:return{kind:`charClass`,negated:!0,ranges:Fk};default:throw Error(`unreachable shorthand class letter`)}}var Lk=new Set([`|`,`)`]),Rk={".":`.`,"*":`*`,"+":`+`,"?":`?`,"(":`(`,")":`)`,"[":`[`,"]":`]`,"{":`{`,"}":`}`,"|":`|`,"^":`^`,$:`$`,"\\":`\\`,"/":`/`,n:`
|
|
80
|
-
`,t:` `,r:`\r`,f:`\f`,v:`\v`},zk=class{pattern;pos=0;constructor(e){this.pattern=e}get position(){return this.pos}atEnd(){return this.pos>=this.pattern.length}peek(e=0){return this.pattern[this.pos+e]}advance(){let e=this.pattern[this.pos];if(e===void 0)throw new kk(this.pattern,this.pos,`unexpected end of pattern`);return this.pos+=1,e}parseAlternation(){let e=this.parseSequence(),t=[];for(;this.peek()===`|`;)this.advance(),t.push(this.parseSequence());return t.length===0?e:{kind:`alternation`,branches:[e,...t]}}parseSequence(){if(this.atEnd()||Lk.has(this.peek()??``))return{kind:`concat`,operands:[]};let e=this.parseQuantified(),t=[];for(;!this.atEnd()&&!Lk.has(this.peek()??``);)t.push(this.parseQuantified());return t.length===0?e:{kind:`concat`,operands:[e,...t]}}parseQuantified(){let e=this.pos,t=this.parseAtom();if(t.kind===`anchorStart`||t.kind===`anchorEnd`){if(this.peekIsQuantifierStart())throw new kk(this.pattern,e,`an anchor ('${t.kind===`anchorStart`?`^`:`$`}') cannot be quantified`);return t}let n=this.tryParseQuantifier();if(n===void 0)return t;if(this.peekIsQuantifierStart())throw new kk(this.pattern,this.pos,`a quantifier cannot itself be quantified -- this grammar has no lazy or possessive modifiers, since a pattern that only ever answers a yes/no match question has no notion for either to change`);switch(n.kind){case`star`:return{kind:`star`,operand:t};case`plus`:return{kind:`plus`,operand:t};case`optional`:return{kind:`optional`,operand:t};case`repeat`:return{kind:`repeat`,operand:t,min:n.min,max:n.max};default:throw Error(`unreachable quantifier kind`)}}peekIsQuantifierStart(){let e=this.peek();if(e===`*`||e===`+`||e===`?`)return!0;if(e===`{`){let e=this.pos,t=this.tryParseBound();return this.pos=e,t!==void 0}return!1}tryParseQuantifier(){let e=this.peek();if(e===`*`)return this.advance(),{kind:`star`};if(e===`+`)return this.advance(),{kind:`plus`};if(e===`?`)return this.advance(),{kind:`optional`};if(e===`{`){let e=this.tryParseBound();return e===void 0?void 0:{kind:`repeat`,min:e.min,max:e.max}}}tryParseBound(){let e=this.pos;this.pos+=1;let t=this.readDigits();if(t===``){this.pos=e;return}let n,r=!1;if(this.peek()===`,`&&(r=!0,this.pos+=1,n=this.readDigits()),this.peek()!==`}`){this.pos=e;return}this.pos+=1;let i=Number.parseInt(t,10),a=r?n===``?void 0:Number.parseInt(n??``,10):i;if(a!==void 0&&a<i)throw new kk(this.pattern,e,`quantifier range is backwards: {${t}${r?`,`+(n??``):``}} would require between ${String(i)} and ${String(a)} repetitions`);return{min:i,max:a}}readDigits(){let e=``;for(;;){let t=this.peek();if(t===void 0||t<`0`||t>`9`)break;e+=t,this.pos+=1}return e}parseAtom(){let e=this.peek();if(e===void 0)throw new kk(this.pattern,this.pos,`unexpected end of pattern`);if(e===`^`)return this.advance(),{kind:`anchorStart`};if(e===`$`)return this.advance(),{kind:`anchorEnd`};if(e===`.`)return this.advance(),{kind:`anyChar`};if(e===`(`)return this.parseGroup();if(e===`[`)return this.parseCharClass();if(e===`\\`)return this.parseEscapedAtom();if(e===`*`||e===`+`||e===`?`)throw new kk(this.pattern,this.pos,`quantifier '${e}' with nothing to repeat`);return this.advance(),{kind:`literal`,codeUnit:e.charCodeAt(0)}}parseGroup(){let e=this.pos;if(this.advance(),this.peek()===`?`&&this.peek(1)===`:`)this.advance(),this.advance();else throw new kk(this.pattern,e,`capturing groups are not supported in this grammar -- there is nothing to capture, since a pattern only ever answers whether it matches. Use '(?:...)' for grouping.`);let t=this.parseAlternation();if(this.peek()!==`)`)throw new kk(this.pattern,this.pos,`expected ')' to close '(?:'`);return this.advance(),t}parseEscapedAtom(){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`D`||t===`w`||t===`W`||t===`s`||t===`S`)return Ik(t);let n=Rk[t];if(n!==void 0)return{kind:`literal`,codeUnit:n.charCodeAt(0)};throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`)}parseCharClass(){let e=this.pos;this.advance();let t=!1;this.peek()===`^`&&(this.advance(),t=!0);let n=[];for(;;){if(this.atEnd())throw new kk(this.pattern,e,`unterminated character class -- missing closing ']'`);if(this.peek()===`]`){if(n.length===0)throw new kk(this.pattern,this.pos,`a character class must contain at least one item -- ']' immediately, or immediately after '[^', is not the empty class here (escape it as '\\]' to match a literal ']')`);this.advance();break}n.push(...this.parseClassItem())}return{kind:`charClass`,negated:t,ranges:n}}parseClassItem(){let e=this.peek();if(e===`\\`){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`w`||t===`s`)return Ik(t).ranges;if(t===`D`||t===`W`||t===`S`)throw new kk(this.pattern,e,`the negated shorthand class '\\${t}' cannot be embedded inside a character class, because its complement cannot be represented as a set of ranges to union with the class's other members -- use it as its own atom instead of embedding it here`);let n=Rk[t];if(n===void 0)throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`);return this.parseOptionalRangeFrom(n.charCodeAt(0))}if(e===void 0)throw new kk(this.pattern,this.pos,`unterminated character class -- missing closing ']'`);return this.advance(),this.parseOptionalRangeFrom(e.charCodeAt(0))}parseOptionalRangeFrom(e){if(this.peek()===`-`&&this.peek(1)!==void 0&&this.peek(1)!==`]`){let t=this.pos;this.advance();let n=this.parseClassRangeEndpoint();if(n<e)throw new kk(this.pattern,t,`invalid range in character class: '${String.fromCharCode(e)}-${String.fromCharCode(n)}' is reversed`);return[{from:e,to:n}]}return[{from:e,to:e}]}parseClassRangeEndpoint(){let e=this.peek();if(e===`\\`){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`D`||t===`w`||t===`W`||t===`s`||t===`S`)throw new kk(this.pattern,e,`a shorthand class ('\\${t}') cannot be a range endpoint`);let n=Rk[t];if(n===void 0)throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`);return n.charCodeAt(0)}if(e===void 0)throw new kk(this.pattern,this.pos,`unterminated character class -- missing closing ']'`);return this.advance(),e.charCodeAt(0)}};function Bk(e){let t=new zk(e),n=t.parseAlternation();if(!t.atEnd())throw new kk(e,t.position,`unexpected character -- if this was meant literally, escape it with a backslash`);return n}var Vk=class{states=[];add(e){return this.states.push(e),this.states.length-1}patch(e,t){for(let n of e){let e=this.states[n.state];if(e!==void 0)switch(n.field){case`to`:(e.kind===`char`||e.kind===`anchorStart`||e.kind===`anchorEnd`)&&(e.to=t);break;case`to1`:e.kind===`split`&&(e.to1=t);break;case`to2`:e.kind===`split`&&(e.to2=t)}}}emptyFrag(){let e=this.add({kind:`split`,to1:-1,to2:-1});return{start:e,out:[{state:e,field:`to1`},{state:e,field:`to2`}]}}compileRepeat(e){let{operand:t,min:n,max:r}=e;if(r===void 0){if(n===0)return this.compileNode({kind:`star`,operand:t});let e=[];for(let r=0;r<n-1;r+=1)e.push(t);return e.push({kind:`plus`,operand:t}),this.compileNode({kind:`concat`,operands:e})}let i=[];for(let e=0;e<n;e+=1)i.push(t);for(let e=0;e<r-n;e+=1)i.push({kind:`optional`,operand:t});return i.length===0?this.emptyFrag():this.compileNode({kind:`concat`,operands:i})}compileNode(e){switch(e.kind){case`literal`:{let t=e.codeUnit,n=this.add({kind:`char`,test:e=>e===t,to:-1});return{start:n,out:[{state:n,field:`to`}]}}case`anyChar`:{let e=this.add({kind:`char`,test:()=>!0,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`charClass`:{let t=this.add({kind:`char`,test:t=>Ok(e,t),to:-1});return{start:t,out:[{state:t,field:`to`}]}}case`anchorStart`:{let e=this.add({kind:`anchorStart`,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`anchorEnd`:{let e=this.add({kind:`anchorEnd`,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`concat`:{if(e.operands.length===0)return this.emptyFrag();let[t,...n]=e.operands;if(t===void 0)throw Error(`unreachable: a non-empty operands array always has a first element`);let r=this.compileNode(t);for(let e of n){let t=this.compileNode(e);this.patch(r.out,t.start),r={start:r.start,out:t.out}}return r}case`alternation`:{let[t,...n]=e.branches;if(t===void 0)throw Error(`unreachable: AlternationNode always has at least two branches`);let r=this.compileNode(t);for(let e of n){let t=this.compileNode(e);r={start:this.add({kind:`split`,to1:r.start,to2:t.start}),out:[...r.out,...t.out]}}return r}case`star`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return this.patch(t.out,n),{start:n,out:[{state:n,field:`to2`}]}}case`plus`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return this.patch(t.out,n),{start:t.start,out:[{state:n,field:`to2`}]}}case`optional`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return{start:n,out:[...t.out,{state:n,field:`to2`}]}}case`repeat`:return this.compileRepeat(e);default:throw Error(`unreachable regex node kind`)}}build(e){let t=this.compileNode(e),n=this.add({kind:`match`});return this.patch(t.out,n),{states:this.states,start:t.start,matchState:n}}};function Hk(e){return new Vk().build(e)}function Uk(e,t,n,r){let i=new Set,a=new Set,o=[...t];for(;o.length>0;){let t=o.pop();if(t===void 0||a.has(t))continue;a.add(t);let s=e.states[t];if(s!==void 0)switch(s.kind){case`char`:case`match`:i.add(t);break;case`split`:o.push(s.to1,s.to2);break;case`anchorStart`:n===0&&o.push(s.to);break;case`anchorEnd`:n===r&&o.push(s.to)}}return i}function Wk(e,t,n){let r=new Set;for(let i of t){let t=e.states[i];t?.kind===`char`&&t.test(n)&&r.add(t.to)}return r}function Gk(e,t){let n=t.length,r=Uk(e,[e.start],0,n);if(r.has(e.matchState))return!0;for(let i=0;i<n;i+=1){let a=t.charCodeAt(i),o=Wk(e,r,a);if(o.add(e.start),r=Uk(e,[...o],i+1,n),r.has(e.matchState))return!0}return!1}function Kk(e){let t=Hk(Bk(e));return{test:e=>Gk(t,e)}}function qk(e,t){if(e.status===`definite`&&!e.value||t.status===`definite`&&!t.value)return Q(!1);let n=VO(e,t);return n===void 0?Q(!0):{status:`indeterminate`,reason:n}}function Jk(e,t){if(e.status===`definite`&&e.value||t.status===`definite`&&t.value)return Q(!0);let n=VO(e,t);return n===void 0?Q(!1):{status:`indeterminate`,reason:n}}function Yk(e,t,n){switch(e){case`gt`:return t>n;case`gte`:return t>=n;case`lt`:return t<n;case`lte`:return t<=n;case`eq`:return t===n;case`neq`:return t!==n;default:throw Error(`unreachable comparison operator`)}}var Xk={ms:1,s:1e3,min:6e4,h:36e5,d:864e5};function Zk(e,t){return e*Xk[t]}function Qk(e){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function $k(e){return $(`wrong-type`,`'${e}' is not a parseable ISO-8601 timestamp`)}function eA(e){let t=new Date(e);return Number.isNaN(t.getTime())?$(`domain-error`,`the resulting instant falls outside the representable timestamp range`):Q({kind:`instant`,value:t.toISOString()})}function tA(e,t,n){switch(t.kind){case`number`:return n.kind===`number`?RO(t.unit,n.unit)?Q(Yk(e,t.value,n.value)):$(`wrong-type`,`cannot compare numbers with incompatible units`):$(`wrong-type`,`cannot compare a 'number' value with a '${n.kind}' value`);case`text`:return $(`wrong-type`,`text values are not comparable via 'compare'; use 'textCompare'`);case`boolean`:return n.kind===`boolean`?e!==`eq`&&e!==`neq`?$(`wrong-type`,`booleans have no natural ordering; '${e}' is only defined for 'eq'/'neq'`):Q(e===`eq`?t.value===n.value:t.value!==n.value):$(`wrong-type`,`cannot compare a 'boolean' value with a '${n.kind}' value`);case`instant`:{if(n.kind!==`instant`)return $(`wrong-type`,`cannot compare an 'instant' value with a '${n.kind}' value`);let r=Qk(t.value);if(r===void 0)return $k(t.value);let i=Qk(n.value);return i===void 0?$k(n.value):Q(Yk(e,r,i))}case`duration`:return n.kind===`duration`?Q(Yk(e,Zk(t.value,t.unit),Zk(n.value,n.unit))):$(`wrong-type`,`cannot compare a 'duration' value with a '${n.kind}' value`);case`complex`:return e!==`eq`&&e!==`neq`?$(`wrong-type`,`ordering operator '${e}' is not defined for complex values; the complex plane has no total order`):n.kind===`complex`?RO(t.unit,n.unit)?Q(e===`eq`?t.re===n.re&&t.im===n.im:t.re!==n.re||t.im!==n.im):$(`wrong-type`,`cannot compare complex values with incompatible units`):$(`wrong-type`,`cannot compare a 'complex' value with a '${n.kind}' value`);default:throw Error(`unreachable computed-value kind`)}}function nA(e,t,n){if(t.kind!==`text`)return $(`wrong-type`,`'textCompare' requires 'text' operands; the left operand is '${t.kind}'`);if(n.kind!==`text`)return $(`wrong-type`,`'textCompare' requires 'text' operands; the right operand is '${n.kind}'`);switch(e){case`equals`:return Q(t.value===n.value);case`notEquals`:return Q(t.value!==n.value);case`matches`:case`notMatches`:{let r;try{r=new RegExp(n.value)}catch{return $(`wrong-type`,`'${n.value}' is not a valid regular expression pattern`)}let i=r.test(t.value);return Q(e===`matches`?i:!i)}case`portableMatches`:case`portableNotMatches`:{let r;try{r=Kk(n.value)}catch(e){let t=e instanceof kk?e.message:String(e);return $(`wrong-type`,`'${n.value}' is not a valid trilean-regex pattern: ${t}`)}let i=r.test(t.value);return Q(e===`portableMatches`?i:!i)}default:throw Error(`unreachable text comparison operator`)}}function rA(e,t){switch(e.kind){case`number`:return t.kind===`number`?RO(e.unit,t.unit)?Q(e.value===t.value):$(`wrong-type`,`cannot compare numbers with incompatible units for membership`):$(`wrong-type`,`cannot compare a 'number' value with a '${t.kind}' value for membership`);case`text`:return t.kind===`text`?Q(e.value===t.value):$(`wrong-type`,`cannot compare a 'text' value with a '${t.kind}' value for membership`);case`boolean`:return t.kind===`boolean`?Q(e.value===t.value):$(`wrong-type`,`cannot compare a 'boolean' value with a '${t.kind}' value for membership`);case`instant`:{if(t.kind!==`instant`)return $(`wrong-type`,`cannot compare an 'instant' value with a '${t.kind}' value for membership`);let n=Qk(e.value);if(n===void 0)return $k(e.value);let r=Qk(t.value);return r===void 0?$k(t.value):Q(n===r)}case`duration`:return t.kind===`duration`?Q(Zk(e.value,e.unit)===Zk(t.value,t.unit)):$(`wrong-type`,`cannot compare a 'duration' value with a '${t.kind}' value for membership`);case`complex`:return t.kind===`complex`?RO(e.unit,t.unit)?Q(e.re===t.re&&e.im===t.im):$(`wrong-type`,`cannot compare complex values with incompatible units for membership`):$(`wrong-type`,`cannot compare a 'complex' value with a '${t.kind}' value for membership`);default:throw Error(`unreachable computed-value kind`)}}function iA(e){return RO(e,void 0)}function aA(e){switch(e.kind){case`number`:return Q({kind:`number`,value:-e.value,unit:e.unit});case`duration`:return Q({kind:`duration`,value:-e.value,unit:e.unit});case`complex`:return Q({kind:`complex`,re:-e.re,im:-e.im,unit:e.unit});case`text`:case`instant`:case`boolean`:return $(`wrong-type`,`cannot negate a '${e.kind}' value`);default:throw Error(`unreachable computed-value kind`)}}function oA(e,t,n){switch(e){case`add`:return RO(t.unit,n.unit)?Q({kind:`number`,value:t.value+n.value,unit:t.unit}):$(`wrong-type`,`cannot add numbers with incompatible units`);case`subtract`:return RO(t.unit,n.unit)?Q({kind:`number`,value:t.value-n.value,unit:t.unit}):$(`wrong-type`,`cannot subtract numbers with incompatible units`);case`multiply`:return Q({kind:`number`,value:t.value*n.value,unit:zO(t.unit,n.unit)});case`divide`:return n.value===0?$(`domain-error`,`division by zero`):Q({kind:`number`,value:t.value/n.value,unit:BO(t.unit,n.unit)});case`power`:return!iA(t.unit)||!iA(n.unit)?$(`wrong-type`,`'power' requires dimensionless operands`):t.value<0&&!Number.isInteger(n.value)?$(`domain-error`,`a negative base raised to a non-integer power is not a real number`):t.value===0&&n.value<0?$(`domain-error`,`zero raised to a negative power is a division by zero`):Q({kind:`number`,value:t.value**n.value});case`modulo`:return!iA(t.unit)||!iA(n.unit)?$(`wrong-type`,`'modulo' requires dimensionless operands`):n.value===0?$(`domain-error`,`modulo by zero`):Q({kind:`number`,value:t.value%n.value});default:throw Error(`unreachable arithmetic operator`)}}function sA(e,t,n){switch(e){case`add`:return Q({kind:`duration`,value:Zk(t.value,t.unit)+Zk(n.value,n.unit),unit:`ms`});case`subtract`:return Q({kind:`duration`,value:Zk(t.value,t.unit)-Zk(n.value,n.unit),unit:`ms`});case`multiply`:case`divide`:case`power`:case`modulo`:return $(`wrong-type`,`arithmetic operator '${e}' is not defined between two 'duration' values`);default:throw Error(`unreachable arithmetic operator`)}}function cA(e){return e.kind===`complex`?e:{kind:`complex`,re:e.value,im:0,unit:e.unit}}function lA(e,t){return{kind:`complex`,re:e.re*t.re-e.im*t.im,im:e.re*t.im+e.im*t.re,unit:zO(e.unit,t.unit)}}function uA(e,t,n){switch(e){case`add`:return RO(t.unit,n.unit)?Q({kind:`complex`,re:t.re+n.re,im:t.im+n.im,unit:t.unit}):$(`wrong-type`,`cannot add complex values with incompatible units`);case`subtract`:return RO(t.unit,n.unit)?Q({kind:`complex`,re:t.re-n.re,im:t.im-n.im,unit:t.unit}):$(`wrong-type`,`cannot subtract complex values with incompatible units`);case`multiply`:return Q(lA(t,n));case`divide`:{let e=n.re*n.re+n.im*n.im;return e===0?$(`domain-error`,`division by zero`):Q({kind:`complex`,re:(t.re*n.re+t.im*n.im)/e,im:(t.im*n.re-t.re*n.im)/e,unit:BO(t.unit,n.unit)})}case`modulo`:return $(`domain-error`,`'modulo' is undefined for complex values`);default:throw Error(`unreachable arithmetic operator`)}}function dA(e,t){if(t.kind!==`number`||!Number.isInteger(t.value))return $(`wrong-type`,`'power' with a complex operand requires a real integer exponent`);if(!iA(e.unit)||!iA(t.unit))return $(`wrong-type`,`'power' requires dimensionless operands`);let n={kind:`complex`,re:1,im:0,unit:{}},r=cA(e),i=n;for(let e=0;e<Math.abs(t.value);e+=1)i=lA(i,r);return t.value>=0?Q(i):uA(`divide`,n,i)}function fA(e,t,n){if(t.kind===`instant`&&n.kind===`instant`&&e===`subtract`){let e=Qk(t.value);if(e===void 0)return $k(t.value);let r=Qk(n.value);return r===void 0?$k(n.value):Q({kind:`duration`,value:e-r,unit:`ms`})}if(t.kind===`instant`&&n.kind===`duration`&&e===`add`){let e=Qk(t.value);return e===void 0?$k(t.value):eA(e+Zk(n.value,n.unit))}if(t.kind===`duration`&&n.kind===`instant`&&e===`add`){let e=Qk(n.value);return e===void 0?$k(n.value):eA(e+Zk(t.value,t.unit))}return t.kind===`instant`||n.kind===`instant`?$(`wrong-type`,`arithmetic operator '${e}' is not defined between a '${t.kind}' and a '${n.kind}' value`):t.kind===`duration`&&n.kind===`duration`?sA(e,t,n):t.kind===`duration`||n.kind===`duration`?$(`wrong-type`,`arithmetic operator '${e}' is not defined between a '${t.kind}' and a '${n.kind}' value`):t.kind!==`number`&&t.kind!==`complex`?$(`wrong-type`,`arithmetic requires numeric operands; got a '${t.kind}' value`):n.kind!==`number`&&n.kind!==`complex`?$(`wrong-type`,`arithmetic requires numeric operands; got a '${n.kind}' value`):t.kind===`complex`||n.kind===`complex`?e===`power`?dA(t,n):uA(e,cA(t),cA(n)):oA(e,t,n)}function pA(e,t){if(e!==void 0){if(t.kind!==`number`&&t.kind!==`complex`)return $(`wrong-type`,`a unit was expected on a reference that resolved to a non-numeric value`);if(!RO(e,t.unit))return $(`wrong-type`,`the resolved value's unit does not match the reference's expected unit`)}}function mA(e,t,n){let r=Object.hasOwn(e,t)?e[t]:void 0;if(r===void 0)return $(`wrong-type`,`no function registered under the name '${t}'`);let i=r(n);return`domainError`in i?$(`domain-error`,i.domainError):Q(i)}async function hA(e,t,n,r,i,a,o,s,c){let l=s.checkNode(c);if(l!==void 0)return l;switch(e.kind){case`not`:{let l=await hA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`?l:Q(!l.value)}case`and`:{let[l,u]=await Promise.all([hA(e.left,t,n,r,i,a,o,s,c+1),hA(e.right,t,n,r,i,a,o,s,c+1)]);return qk(l,u)}case`or`:{let[l,u]=await Promise.all([hA(e.left,t,n,r,i,a,o,s,c+1),hA(e.right,t,n,r,i,a,o,s,c+1)]);return Jk(l,u)}case`allOf`:return(await Promise.all(e.operands.map(async e=>hA(e,t,n,r,i,a,o,s,c+1)))).reduce(qk,Q(!0));case`anyOf`:return(await Promise.all(e.operands.map(async e=>hA(e,t,n,r,i,a,o,s,c+1)))).reduce(Jk,Q(!1));case`compare`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:tA(e.op,l.value,u.value)}case`textCompare`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:nA(e.op,l.value,u.value)}case`memberOf`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);if(l.status===`indeterminate`)return l;let u=await Promise.all(e.candidates.map(async e=>{let u=await gA(e,t,n,r,i,a,o,s,c+1);return u.status===`indeterminate`?u:rA(l.value,u.value)}));for(let t of u)if(t.status===`definite`&&t.value)return Q(e.op===`in`);let d=VO(...u);return d===void 0?Q(e.op===`notIn`):{status:`indeterminate`,reason:d}}case`exists`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`&&l.reason.code===`not-found`?Q(!1):Q(!0)}case`some`:case`every`:{let r=await Tk(hA,e.collection,e.filter,t,n,i,a,o,s,c+1),l=(await Promise.all(r.map(async({item:t,filterOutcome:r})=>{if(r!==`exclude`)return r===`include`?hA(e.item,t,n,void 0,i,a,o,s,c+1):r}))).filter(e=>e!==void 0),u=e.kind===`some`?Jk:qk,d=e.kind===`some`?Q(!1):Q(!0);return l.reduce(u,d)}case`treeReference`:{if(n.resolveTree===void 0)return $(`wrong-type`,`no tree resolver registered for treeReference nodes`);let l=JSON.stringify(e.key);if(a.has(l))return $(`domain-error`,`circular treeReference detected`);if(o>=100)return $(`domain-error`,`treeReference chain exceeds the maximum depth of 100`);let u=await n.resolveTree(e.key,t);if(!u.found)return $(`not-found`,`treeReference key did not resolve to a tree`);let d=ok.safeParse(u.node);return d.success?hA(d.data,t,n,r,i,new Set([...a,l]),o+1,s,c+1):$(`wrong-type`,`the referenced tree is not a valid PredicateNode`)}default:throw Error(`unreachable predicate node kind`)}}async function gA(e,t,n,r,i,a,o,s,c){let l=s.checkNode(c);if(l!==void 0)return l;switch(e.kind){case`reference`:{let r=await n.resolveValue(e.key,t);if(!r.found)return $(`not-found`,`no value found for reference key ${JSON.stringify(e.key)}`);let i=pA(e.unit,r.value);return i===void 0?Q(r.value):i}case`accumulator`:return r===void 0?$(`wrong-type`,`accumulator used outside a reduce fold's combine expression`):Q(r);case`call`:{let l=await Promise.all(e.args.map(async e=>gA(e,t,n,r,i,a,o,s,c+1))),u=[];for(let e of l){if(e.status===`indeterminate`)return e;u.push(e.value)}return mA(i,e.fn,u)}case`numberLiteral`:return Q({kind:`number`,value:e.value,unit:e.unit});case`textLiteral`:return Q({kind:`text`,value:e.value});case`booleanLiteral`:return Q({kind:`boolean`,value:e.value});case`instantLiteral`:return Q({kind:`instant`,value:e.value});case`durationLiteral`:return Q({kind:`duration`,value:e.value,unit:e.unit});case`complexLiteral`:return`re`in e?Q({kind:`complex`,re:e.re,im:e.im,unit:e.unit}):Q(PO(e.magnitude,e.phase,e.unit));case`arithmetic`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:fA(e.op,l.value,u.value)}case`negate`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`?l:aA(l.value)}case`lookup`:{let l=await Promise.all(e.keys.map(async e=>gA(e,t,n,r,i,a,o,s,c+1))),u=[];for(let e of l){if(e.status===`indeterminate`)return e;u.push(e.value)}let d=await n.resolveLookup(e.table,u,t);return d.found?Q(d.value):$(`not-found`,`no match found in lookup table ${JSON.stringify(e.table)}`)}case`conditional`:{if((e.hitPolicy??`first`)===`first`){for(let{when:l,then:u}of e.cases){let e=await hA(l,t,n,r,i,a,o,s,c+1);if(e.status===`indeterminate`)return e;if(e.value)return gA(u,t,n,r,i,a,o,s,c+1)}return gA(e.fallback,t,n,r,i,a,o,s,c+1)}let l=await Promise.all(e.cases.map(async({when:e,then:l})=>({then:l,whenResult:await hA(e,t,n,r,i,a,o,s,c+1)}))),u=l.filter(({whenResult:e})=>e.status===`definite`&&e.value);if(u.length>=2)return $(`domain-error`,`more than one case matched under the 'unique' hit policy`);let d=VO(...l.map(({whenResult:e})=>e));if(d!==void 0)return{status:`indeterminate`,reason:d};let[f]=u;return gA(f===void 0?e.fallback:f.then,t,n,r,i,a,o,s,c+1)}case`fold`:{let r=await Tk(hA,e.collection,e.filter,t,n,i,a,o,s,c+1),l=Ek(r);if(l!==void 0)return{status:`indeterminate`,reason:l};let u=r.filter(({filterOutcome:e})=>e===`include`).map(({item:e})=>e);if(e.combiner.mode===`reduce`){let r=await gA(e.combiner.initial,t,n,void 0,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;let l=r.value;for(let t of u){let r=await gA(e.combiner.combine,t,n,l,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;l=r.value}return Q(l)}if(u.length===0)return $(`domain-error`,`'${e.combiner.mode}' has no participating items to seed a running result from`);let d=e.combiner.mode===`max`?`gt`:`lt`,f;for(let t of u){let r=await gA(e.combiner.item,t,n,void 0,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;if(f===void 0){f=r.value;continue}let l=tA(d,r.value,f);if(l.status===`indeterminate`)return l;l.value&&(f=r.value)}if(f===void 0)throw Error(`unreachable: max/min over a non-empty participating list produced no running result`);return Q(f)}case`delegate`:{if(n.resolveDelegate===void 0)return $(`wrong-type`,`no delegate handler registered for external system '${e.system}'`);let r=await n.resolveDelegate(e.system,e.payload,t);return r.found?Q(r.value):$(`not-found`,`delegate handler for external system '${e.system}' reported no value`)}case`treeReference`:{if(n.resolveTree===void 0)return $(`wrong-type`,`no tree resolver registered for treeReference nodes`);let l=JSON.stringify(e.key);if(a.has(l))return $(`domain-error`,`circular treeReference detected`);if(o>=100)return $(`domain-error`,`treeReference chain exceeds the maximum depth of 100`);let u=await n.resolveTree(e.key,t);if(!u.found)return $(`not-found`,`treeReference key did not resolve to a tree`);let d=xk.safeParse(u.node);return d.success?gA(d.data,t,n,r,i,new Set([...a,l]),o+1,s,c+1):$(`wrong-type`,`the referenced tree is not a valid ExpressionNode`)}default:throw Error(`unreachable expression node kind`)}}function _A({functions:e=Sk,maxNodes:t=Ck,maxNestingDepth:n=500}){return{evaluatePredicate:async(r,i,a)=>hA(r,i,a,void 0,e,new Set,0,wk(t,n),0),evaluateValue:async(r,i,a)=>gA(r,i,a,void 0,e,new Set,0,wk(t,n),0)}}var{evaluatePredicate:vA,evaluateValue:yA}=_A({}),bA=TT(ok),xA=`bearer-is`,SA=`expires-at`,CA=`scope-narrows`,wA=`capability-is`,TA=`depth-remaining`,EA=[xA,SA,CA,wA,TA];function DA(e){return e===`bearer-is`||e===`expires-at`||e===`scope-narrows`||e===`capability-is`||e===`depth-remaining`}var OA=`grantee-is`,kA=`granted-capability-is`;function AA(e){return e===`grantee-is`||e===`granted-capability-is`}var jA={[OA]:(e,t)=>t.subject===void 0||typeof e!=`string`?{found:!1}:NA(dO(t.subject.bearer)===e),[kA]:(e,t)=>t.subject===void 0||typeof e!=`string`?{found:!1}:NA(t.subject.capability===e)};function MA(e,t){return{kind:`not`,operand:{kind:`and`,left:FA(kA,e),right:FA(OA,dO(t))}}}function NA(e){return{found:!0,value:{kind:`boolean`,value:e}}}var PA={[xA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(AO(t.parentClaims.bearer,t.childIssuer)),[SA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(t.candidate.expires<=t.parentClaims.expires),[CA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(NO(t.parentClaims.scope,t.candidate.scope)),[wA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(t.parentClaims.capability===t.candidate.capability),[TA]:(e,t)=>{if(t.parentClaims===void 0)return NA(!1);let n=t.parentClaims[`delegations-remaining`];return NA(n===void 0||t.candidate.delegationsRemaining!==void 0&&t.candidate.delegationsRemaining<n)}};function FA(e,t=null){return{kind:`compare`,op:`eq`,left:{kind:`delegate`,system:e,payload:t},right:{kind:`booleanLiteral`,value:!0}}}var IA=async()=>Promise.resolve({found:!1}),LA=async()=>Promise.resolve({found:!1}),RA=async()=>Promise.resolve([]);async function zA(e,t,n){let r={childIssuer:t,candidate:n,parentClaims:e},i={resolveValue:IA,resolveLookup:LA,resolveCollection:RA,resolveDelegate:async(e,t)=>DA(e)?PA[e](t,r):{found:!1}};for(let e of EA){let t=await vA(FA(e),r,i);if(t.status!==`definite`||!t.value)return e}}async function BA(e,t,n,r={},i){let a=i===void 0?{clock:n,claims:t}:{clock:n,claims:t,subject:i},o={resolveValue:IA,resolveLookup:LA,resolveCollection:RA,resolveDelegate:async(e,t)=>{if(i!==void 0&&AA(e))try{return await jA[e](t,a)}catch{return{found:!1}}let n=Object.hasOwn(r,e)?r[e]:void 0;if(n===void 0)return{found:!1};try{return await n(t,a)}catch{return{found:!1}}}};for(let t of e){let e=await vA(t,a,o);if(e.status!==`definite`||!e.value)return{ok:!1,reason:`not_satisfied`}}return{ok:!0}}var VA=`manage:grant`,HA=64;function UA(e,t){return Mg([`Signature1`,e,new Uint8Array,t],hg)}function WA(e){return Uint8Array.from(e)}function GA(e){return WA(Mg(e,hg))}function KA(e){return GA({1:e.identityKey.alg,4:e.deviceId})}function qA(e){let[,,t]=e;if(t===null)return;let n;try{n=b_(t,x_)}catch{return}let r=RD.safeParse(n);return r.success?r.data:void 0}async function JA(e,t){let n=await XA(e,{identity:t.identity,clock:t.clock,revocation:t.revocation,...t.extraPredicateResolvers===void 0?{}:{extraPredicateResolvers:t.extraPredicateResolvers}});return n.ok&&t.expectedBearer!==void 0&&!AO(n.claims.bearer,t.expectedBearer)?{ok:!1,reason:`bearer_mismatch`}:n}async function YA(e,t,n){if(AO(e.issuer,t.issuer))return!0;if(e.authorization===void 0)return!1;let r;try{r=b_(e.authorization,x_)}catch{return!1}let i=LD.safeParse(r);if(!i.success)return!1;let a=await JA(i.data,{...n,expectedBearer:e.issuer});return a.ok&&a.claims.capability===`manage:revoke`&&NO(a.claims.scope,t.scope)}async function XA(e,t,n,r=0,i=new Set){let[a,,o,s]=e;if(o===null)return{ok:!1,reason:`malformed`};if(r>=HA)return{ok:!1,reason:`chain_too_deep`};let c=uO(o);if(i.has(c))return{ok:!1,reason:`chain_cycle`};let l=new Set(i).add(c),u;try{u=b_(o,x_)}catch{return{ok:!1,reason:`malformed`}}let d=RD.safeParse(u);if(!d.success)return{ok:!1,reason:`malformed`};let f=d.data;if(!await t.identity.verify(f[`issuer-key`],UA(a,o),s))return{ok:!1,reason:`bad_signature`};if(!AO(await t.identity.deriveDeviceId(f[`issuer-key`][`public-key`]),f.issuer))return{ok:!1,reason:`wrong_issuer`};let p=t.clock.now();if(f.expires<=p)return{ok:!1,reason:`expired`};if(f[`not-before`]!==void 0&&f[`not-before`]>p)return{ok:!1,reason:`not_yet_valid`};let m=f[`valid-until`];if(m!==void 0&&m<=p)return{ok:!1,reason:`content_expired`};let h=await t.revocation.entriesFor(f[`token-id`]);for(let e of h)if(await YA(e,f,t))return{ok:!1,reason:`revoked`};if(f.conditions!==void 0){let e;try{e=b_(f.conditions,x_)}catch{return{ok:!1,reason:`conditions_invalid`}}let r=bA.safeParse(e);if(!r.success)return{ok:!1,reason:`conditions_invalid`};if(!(await BA(r.data,f,t.clock,t.extraPredicateResolvers,n)).ok)return{ok:!1,reason:`conditions_not_satisfied`}}let g=f.parent,_=f[`authorised-by`];if(f.capability===`manage:grant`&&g!==void 0)return{ok:!1,reason:`authorisation_invalid`};if(g!==void 0&&_!==void 0)return{ok:!1,reason:`malformed`};if(g!==void 0){let e;try{e=b_(g,x_)}catch{return{ok:!1,reason:`parent_invalid`}}let n=LD.safeParse(e);if(!n.success)return{ok:!1,reason:`parent_invalid`};let i=await XA(n.data,t,void 0,r+1,l);if(!i.ok)return i.reason===`chain_too_deep`||i.reason===`chain_cycle`?{ok:!1,reason:i.reason}:{ok:!1,reason:`parent_invalid`};let a={capability:f.capability,scope:f.scope,expires:f.expires,...f[`delegations-remaining`]===void 0?{}:{delegationsRemaining:f[`delegations-remaining`]}};return await zA(i.claims,f.issuer,a)===void 0?{ok:!0,claims:f,rootIssuer:i.rootIssuer,rootIssuerKey:i.rootIssuerKey,depth:i.depth+1}:{ok:!1,reason:`delegation_exceeds_parent`}}if(_!==void 0){let e;try{e=b_(_,x_)}catch{return{ok:!1,reason:`authorisation_invalid`}}let n=LD.safeParse(e);if(!n.success)return{ok:!1,reason:`authorisation_invalid`};let i=await XA(n.data,t,f,r+1,l);if(!i.ok)return i.reason===`chain_too_deep`||i.reason===`chain_cycle`?{ok:!1,reason:i.reason}:{ok:!1,reason:`authorisation_invalid`};let a=i.claims,o=a[`grants-capability`];return AO(a.bearer,f.issuer)&&a.capability===`manage:grant`&&(o===void 0||o===f.capability)&&NO(a.scope,f.scope)&&f.expires<=a.expires&&(a[`delegations-remaining`]===void 0||f[`delegations-remaining`]!==void 0&&f[`delegations-remaining`]<a[`delegations-remaining`])?{ok:!0,claims:f,rootIssuer:i.rootIssuer,rootIssuerKey:i.rootIssuerKey,depth:i.depth+1}:{ok:!1,reason:`authorisation_invalid`}}return{ok:!0,claims:f,rootIssuer:f.issuer,rootIssuerKey:f[`issuer-key`],depth:0}}async function ZA(e,t){let[n,,r,i]=e;if(r===null)return{ok:!1,reason:`malformed`};let a;try{a=b_(r,x_)}catch{return{ok:!1,reason:`malformed`}}let o=YE.safeParse(a);if(!o.success)return{ok:!1,reason:`malformed`};let s=o.data;return await t.identity.verify(s[`issuer-key`],UA(n,r),i)?AO(await t.identity.deriveDeviceId(s[`issuer-key`][`public-key`]),s.issuer)?{ok:!0,claims:s}:{ok:!1,reason:`wrong_issuer`}:{ok:!1,reason:`bad_signature`}}var QA={"bearer-is":`parent_bearer_mismatch`,"expires-at":`expires_exceeds_parent`,"scope-narrows":`scope_does_not_narrow`,"capability-is":`capability_mismatch`,"depth-remaining":`delegation_exceeds_parent`};async function $A(e,t,n){let r=await zA(e,t,n);return r===void 0?void 0:QA[r]}async function ej(e,t,n){if(e.parent!==void 0)return`authorisation_parent_forbidden`;if(!AO(e.bearer,t))return`authorisation_bearer_mismatch`;let r=e[`grants-capability`];if(e.capability!==`manage:grant`||r!==void 0&&r!==n.capability)return`authorisation_capability_mismatch`;if(!NO(e.scope,n.scope))return`authorisation_scope_does_not_narrow`;if(n.expires>e.expires)return`authorisation_exceeds_authoriser`;let i=e[`delegations-remaining`];if(i!==void 0&&(n.delegationsRemaining===void 0||n.delegationsRemaining>=i))return`authorisation_delegation_exceeds`;if(e.conditions!==void 0){let t;try{t=b_(e.conditions,x_)}catch{return`authorisation_malformed`}let r=bA.safeParse(t);if(!r.success)return`authorisation_malformed`;if(!(await BA(r.data,e,{now:()=>0},{},n)).ok)return`authorisation_conditions_not_satisfied`}}async function tj(e){if(e.expires<=e.clock.now())return{ok:!1,reason:`already_expired`};if(e.parent!==void 0&&e.authorisedBy!==void 0)return{ok:!1,reason:`links_exclusive`};if(e.capability===`manage:grant`&&e.parent!==void 0)return{ok:!1,reason:`authorisation_parent_forbidden`};let t;if(e.parent!==void 0){let n=qA(e.parent);if(n===void 0)return{ok:!1,reason:`parent_malformed`};let r=await $A(n,e.identity.deviceId,{capability:e.capability,scope:e.scope,expires:e.expires,...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining}});if(r!==void 0)return{ok:!1,reason:r};t=GA(e.parent)}let n;if(e.authorisedBy!==void 0){let t=qA(e.authorisedBy);if(t===void 0)return{ok:!1,reason:`authorisation_malformed`};let r=await ej(t,e.identity.deviceId,{capability:e.capability,scope:e.scope,bearer:e.bearer,expires:e.expires,...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining}});if(r!==void 0)return{ok:!1,reason:r};n=GA(e.authorisedBy)}let r=GA({"token-id":e.tokenId,issuer:e.identity.deviceId,"issuer-key":e.identity.identityKey,bearer:e.bearer,capability:e.capability,scope:e.scope,expires:e.expires,...e.notBefore===void 0?{}:{"not-before":e.notBefore},...t===void 0?{}:{parent:t},...e.delegationsRemaining===void 0?{}:{"delegations-remaining":e.delegationsRemaining},...e.conditions===void 0?{}:{conditions:GA(e.conditions)},...n===void 0?{}:{"authorised-by":n},...e.grantsCapability===void 0?{}:{"grants-capability":e.grantsCapability},...e.requestsCapability===void 0?{}:{"requests-capability":e.requestsCapability}}),i=KA(e.identity);return{ok:!0,token:[i,{},r,await e.identity.sign(UA(i,r))]}}async function nj(e){let t=GA({"token-id":e.tokenId,issuer:e.identity.deviceId,"issuer-key":e.identity.identityKey,"revoked-at":e.revokedAt}),n=KA(e.identity);return[n,{},t,await e.identity.sign(UA(n,t))]}var rj=`wm-grant1.`;function ij(e){let t=e[2];if(t===null)return;let n;try{n=b_(t,x_)}catch{return}let r=RD.safeParse(n);return r.success?r.data:void 0}function aj(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function oj(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function sj(e){return rj+aj(Mg(e,hg))}function cj(e){let t=e.trim();if(!t.startsWith(`wm-grant1.`))throw Error(`a grant code starts with "${rj}"`);let n;try{n=b_(oj(t.slice(10)),x_)}catch{throw Error(`the grant code is damaged: it does not decode`)}let r=LD.safeParse(n);if(!r.success||ij(r.data)===void 0)throw Error(`the grant code does not carry a capability token`);return r.data}async function lj(e,t){let n=await JA(e,t);return n.ok?{kind:`valid`}:{kind:`invalid`,reason:n.reason}}var uj={malformed:`malformed`,bad_signature:`signature does not verify`,wrong_issuer:`issuer does not match its key`,bearer_mismatch:`names another bearer`,expired:`expired`,not_yet_valid:`not valid yet`,content_expired:`content expired`,revoked:`revoked`,delegation_exceeds_parent:`exceeds what its parent allows`,parent_invalid:`its parent grant is no longer valid`,conditions_invalid:`its conditions are invalid`,conditions_not_satisfied:`its conditions are not met`,authorisation_invalid:`exceeds what its authorising grant allows`,chain_too_deep:`its chain is deeper than allowed`,chain_cycle:`its chain revisits a token`};function dj(e){return e.kind===`valid`?`valid`:uj[e.reason]}var fj=`grant/`;function pj(e,t){return`${fj}${e}/${t}`}function mj(e){let t=e.slice(6).split(`/`)[0];if(t===`held`||t===`issued`)return t;throw Error(`stored grant key ${e} names no direction`)}function hj(e){return typeof e==`object`&&!!e&&`token`in e&&`recordedAt`in e&&typeof e.recordedAt==`number`}function gj(e){let t=new Set;return{async record(n,r,i){let a=ij(r);if(a===void 0)throw Error(`a grant must carry readable token claims`);let o=pj(n,uO(a[`token-id`]));if(await e.get(o)===void 0){await e.set(o,new Uint8Array(Mg({token:r,recordedAt:i},hg)));for(let e of t)e()}},async list(){let t=[];for(let n of await e.keys(fj)){let r=await e.get(n);if(r===void 0)continue;let i=b_(r,x_);if(!hj(i))throw Error(`stored grant at ${n} is malformed`);let a=LD.safeParse(i.token);if(!a.success)throw Error(`stored grant at ${n} is malformed`);let o=ij(a.data);if(o===void 0)throw Error(`stored grant at ${n} has unreadable claims`);t.push({tokenId:uO(o[`token-id`]),direction:mj(n),token:a.data,claims:o,recordedAt:i.recordedAt})}return t.sort((e,t)=>t.recordedAt-e.recordedAt)},subscribe(e){return t.add(e),()=>{t.delete(e)}}}}function _j(e){return uO(e)}function vj(){let e=new Map;return{async entriesFor(t){return Promise.resolve(e.get(_j(t))??[])},async record(t,n){let r=await ZA(t,n);if(r.ok){let t=_j(r.claims[`token-id`]),n=e.get(t);n===void 0?e.set(t,[r.claims]):n.push(r.claims)}return r}}}var yj=`revocation/`;async function bj(e,t,n){let r;try{r=b_(n,x_)}catch{return`it is not valid CBOR`}let i=XE.safeParse(r);if(!i.success)return`it is not a revocation entry`;let a=await e.record(i.data,{identity:t});return a.ok?void 0:`it no longer verifies (${a.reason})`}async function xj(e){let{storage:t,identity:n,clock:r}=e,i=vj(),a=new Set;async function o(e){let r=await i.record(e,{identity:n});if(r.ok){let n=`${yj}${uO(r.claims.issuer)}/${uO(r.claims[`token-id`])}`;await t.set(n,new Uint8Array(Mg(e,hg)));for(let e of a)e()}return r}let s=[];for(let e of await t.keys(yj)){let r=await t.get(e);if(r===void 0)continue;let a=await bj(i,n,r);a!==void 0&&(s=[...s,{key:e,reason:a}])}return{view:i,unreadable:()=>s,async discardUnreadable(e){await t.delete(e),s=s.filter(t=>t.key!==e);for(let e of a)e()},subscribe(e){return a.add(e),()=>{a.delete(e)}},ingest:o,async revoke(e){let t=await nj({identity:n,tokenId:e,revokedAt:r.now()}),i=await o(t);if(!i.ok)throw Error(`the revocation this device signed does not verify (${i.reason})`);return t}}}var Sj=`preferences/intro-dismissed`,Cj=new Uint8Array([1]);function wj(e){return{async introDismissed(){return await e.get(Sj)!==void 0},async setIntroDismissed(t){t?await e.set(Sj,new Uint8Array(Cj)):await e.delete(Sj)}}}var Tj=`agent/self`,Ej=`wire-mesh-console`;function Dj(e){return e.slice(0,12)}var Oj=/[\p{Cc}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;function kj(e){let t=e.replace(Oj,``).trim();if(t!==``)return Array.from(t).slice(0,64).join(``).trimEnd()}function Aj(e){let t=e[Tj];if(typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`)return kj(t.name)}function jj(e){return{[Tj]:{name:e,harness:Ej}}}function Mj(e,t,n,r){return t===void 0?n===void 0?{primary:Dj(e),secondary:void 0,source:`id`,matchesPetname:!1}:{primary:n,secondary:Dj(e),source:`self`,matchesPetname:r.has(n)}:{primary:t,secondary:n!==void 0&&n!==t?n:void 0,source:`petname`,matchesPetname:!1}}function Nj(e){return e.source===`self`&&e.secondary!==void 0?`${e.primary} (${e.secondary})`:e.primary}var Pj=`petname/`,Fj=`self-name`,Ij=new TextEncoder,Lj=new TextDecoder;function Rj(e){async function t(t,n){let r=kj(n);if(r===void 0){await e.delete(t);return}await e.set(t,new Uint8Array(Ij.encode(r)))}return{async petnames(){let t=new Map;for(let n of await e.keys(Pj)){let r=await e.get(n);r!==void 0&&t.set(n.slice(8),Lj.decode(r))}return t},async setPetname(e,n){await t(Pj+e,n)},async selfName(){let t=await e.get(Fj);return t===void 0?void 0:Lj.decode(t)},async setSelfName(e){await t(Fj,e)}}}var zj=String(2**53-1).length,Bj=`message`;function Vj(e,t){return`${Bj}/${e}/${String(t.sentAt).padStart(zj,`0`)}-${uO(t.messageId)}`}function Hj(e){let t=e.slice(`${Bj}/`.length);return t.slice(0,t.lastIndexOf(`/`))}function Uj(e){return e===`sent`||e===`received`}function Wj(e){return typeof e!=`object`||!e||!(`direction`in e)||!(`text`in e)||!(`messageId`in e)||!(`sentAt`in e)?!1:Uj(e.direction)&&typeof e.text==`string`&&e.messageId instanceof Uint8Array&&typeof e.sentAt==`number`}function Gj(e){return{async append(t,n){await e.set(Vj(t,n),new Uint8Array(Mg(n,hg)))},async roomPaths(){let t=await e.keys(`${Bj}/`);return[...new Set(t.map(Hj))]},async list(t){let n=(await e.keys(`${Bj}/${t}/`)).sort(),r=[];for(let t of n){let n=await e.get(t);if(n===void 0)continue;let i=b_(n,x_);if(!Wj(i))throw Error(`stored message at ${t} is malformed`);r.push(i)}return r}}}function Kj(e){return new Uint8Array(Mg(e,hg))}function qj(e,t){return{type:`relay-data`,payload:Kj(e),...t===void 0?{}:{"to-device":t}}}var Jj=class extends Error{constructor(e){super(e),this.name=`SchemaInvalidFrameError`}};function Yj(e){let t=b_(new Uint8Array(e),x_),n=ME.safeParse(t);if(!n.success)throw new Jj(n.error.message);return n.data}function Xj(e){let t;try{t=b_(e,x_)}catch{return null}let n=ME.safeParse(t);return n.success?n.data:null}var Zj=`signature`,Qj=`identity-key`,$j=new TextEncoder().encode(`wire-mesh/peer-advert/v1\0`);function eM(e){let t={};for(let[n,r]of Object.entries(e))n!==`signature`&&(t[n]=r);let n=Mg(t,hg),r=new Uint8Array($j.length+n.length);return r.set($j,0),r.set(n,$j.length),r}async function tM(e,t){let n=await e.sign(eM(t));return{...t,[Zj]:n}}async function nM(e,t){let n=t[Qj];try{return AO(await e.deriveDeviceId(n[`public-key`]),t.device)?await e.verify(n,eM(t),t[Zj]):!1}catch{return!1}}var rM={name:`wire-mesh-core`,version:`4.0.0`,dependencies:{cbor2:`2.3.0`,"cddl.js":`1.0.1`,trilean:`1.6.2`,zod:`4.5.4`},devDependencies:{"@arethetypeswrong/cli":`0.18.5`,"@exadev/eslint-config":`2.18.0`,"@stryker-mutator/api":`10.0.0`,"@stryker-mutator/core":`10.0.0`,"@stryker-mutator/typescript-checker":`10.0.0`,"@types/node":`26.4.1`,eslint:`10.10.0`,"eslint-config-prettier":`10.1.8`,"eslint-plugin-prettier":`5.5.6`,globals:`17.12.0`,jiti:`2.7.0`,prettier:`3.9.6`,tsdown:`0.23.0`,turbo:`2.10.12`,typescript:`6.0.3`,vitest:`5.0.0`},exports:{"./adapters/byte-stream-connection":{import:`./dist/adapters/byte-stream-connection.mjs`,require:`./dist/adapters/byte-stream-connection.cjs`},"./adapters/frame-codec":{import:`./dist/adapters/frame-codec.mjs`,require:`./dist/adapters/frame-codec.cjs`},"./adapters/memory-storage":{import:`./dist/adapters/memory-storage.mjs`,require:`./dist/adapters/memory-storage.cjs`},"./adapters/node-fs-storage":{import:`./dist/adapters/node-fs-storage.mjs`,require:`./dist/adapters/node-fs-storage.cjs`},"./adapters/node-identity":{import:`./dist/adapters/node-identity.mjs`,require:`./dist/adapters/node-identity.cjs`},"./adapters/system-clock":{import:`./dist/adapters/system-clock.mjs`,require:`./dist/adapters/system-clock.cjs`},"./adapters/tcp-transport":{import:`./dist/adapters/tcp-transport.mjs`,require:`./dist/adapters/tcp-transport.cjs`},"./adapters/threshold-identity":{import:`./dist/adapters/threshold-identity.mjs`,require:`./dist/adapters/threshold-identity.cjs`},"./adapters/threshold-wasm":{import:`./dist/adapters/threshold-wasm.mjs`,require:`./dist/adapters/threshold-wasm.cjs`},"./adapters/tls-transport":{import:`./dist/adapters/tls-transport.mjs`,require:`./dist/adapters/tls-transport.cjs`},"./domain/advert-extension-policy":{import:`./dist/domain/advert-extension-policy.mjs`,require:`./dist/domain/advert-extension-policy.cjs`},"./domain/async-queue":{import:`./dist/domain/async-queue.mjs`,require:`./dist/domain/async-queue.cjs`},"./domain/bulk":{import:`./dist/domain/bulk.mjs`,require:`./dist/domain/bulk.cjs`},"./domain/capability-grant":{import:`./dist/domain/capability-grant.mjs`,require:`./dist/domain/capability-grant.cjs`},"./domain/capability-request":{import:`./dist/domain/capability-request.mjs`,require:`./dist/domain/capability-request.cjs`},"./domain/coordinator-election":{import:`./dist/domain/coordinator-election.mjs`,require:`./dist/domain/coordinator-election.cjs`},"./domain/data-sync":{import:`./dist/domain/data-sync.mjs`,require:`./dist/domain/data-sync.cjs`},"./domain/device-id":{import:`./dist/domain/device-id.mjs`,require:`./dist/domain/device-id.cjs`},"./domain/direct-manage-request":{import:`./dist/domain/direct-manage-request.mjs`,require:`./dist/domain/direct-manage-request.cjs`},"./domain/erasure-coding":{import:`./dist/domain/erasure-coding.mjs`,require:`./dist/domain/erasure-coding.cjs`},"./domain/gossip-expansion":{import:`./dist/domain/gossip-expansion.mjs`,require:`./dist/domain/gossip-expansion.cjs`},"./domain/gossip-extensions":{import:`./dist/domain/gossip-extensions.mjs`,require:`./dist/domain/gossip-extensions.cjs`},"./domain/grant-candidates":{import:`./dist/domain/grant-candidates.mjs`,require:`./dist/domain/grant-candidates.cjs`},"./domain/group-key":{import:`./dist/domain/group-key.mjs`,require:`./dist/domain/group-key.cjs`},"./domain/handshake":{import:`./dist/domain/handshake.mjs`,require:`./dist/domain/handshake.cjs`},"./domain/hub-mailbox":{import:`./dist/domain/hub-mailbox.mjs`,require:`./dist/domain/hub-mailbox.cjs`},"./domain/mesh-session":{import:`./dist/domain/mesh-session.mjs`,require:`./dist/domain/mesh-session.cjs`},"./domain/notice-board":{import:`./dist/domain/notice-board.mjs`,require:`./dist/domain/notice-board.cjs`},"./domain/path-trace":{import:`./dist/domain/path-trace.mjs`,require:`./dist/domain/path-trace.cjs`},"./domain/peer-advert":{import:`./dist/domain/peer-advert.mjs`,require:`./dist/domain/peer-advert.cjs`},"./domain/ping-round-trips":{import:`./dist/domain/ping-round-trips.mjs`,require:`./dist/domain/ping-round-trips.cjs`},"./domain/pinned-address":{import:`./dist/domain/pinned-address.mjs`,require:`./dist/domain/pinned-address.cjs`},"./domain/relay-advert":{import:`./dist/domain/relay-advert.mjs`,require:`./dist/domain/relay-advert.cjs`},"./domain/relay-hub":{import:`./dist/domain/relay-hub.mjs`,require:`./dist/domain/relay-hub.cjs`},"./domain/relay-use-gate":{import:`./dist/domain/relay-use-gate.mjs`,require:`./dist/domain/relay-use-gate.cjs`},"./domain/revocation-view":{import:`./dist/domain/revocation-view.mjs`,require:`./dist/domain/revocation-view.cjs`},"./domain/room":{import:`./dist/domain/room.mjs`,require:`./dist/domain/room.cjs`},"./domain/room-path":{import:`./dist/domain/room-path.mjs`,require:`./dist/domain/room-path.cjs`},"./domain/room-rekey":{import:`./dist/domain/room-rekey.mjs`,require:`./dist/domain/room-rekey.cjs`},"./domain/room-token-verification":{import:`./dist/domain/room-token-verification.mjs`,require:`./dist/domain/room-token-verification.cjs`},"./domain/shard-manifest":{import:`./dist/domain/shard-manifest.mjs`,require:`./dist/domain/shard-manifest.cjs`},"./domain/threshold-subject":{import:`./dist/domain/threshold-subject.mjs`,require:`./dist/domain/threshold-subject.cjs`},"./domain/token-predicates":{import:`./dist/domain/token-predicates.mjs`,require:`./dist/domain/token-predicates.cjs`},"./domain/token-scope":{import:`./dist/domain/token-scope.mjs`,require:`./dist/domain/token-scope.cjs`},"./domain/tokens":{import:`./dist/domain/tokens.mjs`,require:`./dist/domain/tokens.cjs`},"./domain/topology":{import:`./dist/domain/topology.mjs`,require:`./dist/domain/topology.cjs`},"./domain/topology-snapshot":{import:`./dist/domain/topology-snapshot.mjs`,require:`./dist/domain/topology-snapshot.cjs`},"./domain/webrtc-signaling":{import:`./dist/domain/webrtc-signaling.mjs`,require:`./dist/domain/webrtc-signaling.cjs`},"./generated/protocol":{import:`./dist/generated/protocol.mjs`,require:`./dist/generated/protocol.cjs`},"./generated/runtime":{import:`./dist/generated/runtime.mjs`,require:`./dist/generated/runtime.cjs`},"./ports/clock":{import:`./dist/ports/clock.mjs`,require:`./dist/ports/clock.cjs`},"./ports/identity":{import:`./dist/ports/identity.mjs`,require:`./dist/ports/identity.cjs`},"./ports/storage":{import:`./dist/ports/storage.mjs`,require:`./dist/ports/storage.cjs`},"./ports/transport":{import:`./dist/ports/transport.mjs`,require:`./dist/ports/transport.cjs`},"./package.json":`./package.json`},files:[`dist`,`wasm-dist`],packageManager:`pnpm@12.4.1+sha512.2e81e399d73fe8390dab25e06aa788ab7a5908248d2f5a370f82b481147a6a7a367bf8048f9a6fdb6460f21a66f0542dedb8b94ca2c8723596741920b1656d4c`,publishConfig:{provenance:!0,access:`public`},repository:{type:`git`,url:`https://github.com/ExaDev/wire-mesh.git`,directory:`ts/packages/core`},scripts:{_build:`tsdown`,"_build-wasm":`./scripts/build-threshold-wasm.sh`,"_conformance-check":`vitest run test/conformance.unit.test.ts`,_generate:`node generate.ts`,_lint:`eslint . --fix --cache --max-warnings 0`,_mutation:`stryker run stryker.config.ts`,_test:`vitest run`,_typecheck:`tsc -p tsconfig.json --noEmit && tsc -p tsconfig.node.json --noEmit`,build:`turbo run _build`,"build-wasm":`turbo run _build-wasm`,"conformance-check":`turbo run _conformance-check`,generate:`turbo run _generate`,lint:`turbo run _lint`,mutation:`turbo run _mutation`,prepack:`node scripts/assert-wasm-dist.ts`,test:`turbo run _test`,typecheck:`turbo run _typecheck`},type:`module`}.version,iM=`wire-mesh/version`,aM=`version.get`;function oM(e){return`verb`in e&&e.verb===aM}function sM(){return{result:`ok`,version:rM}}var cM=new Set([`device`,`addresses`,`snapshot-seconds`,Qj,Zj]),lM=`topology/peers`,uM=/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;function dM(e){for(let t of Object.keys(e)){if(cM.has(t))throw Error(`sendGossipUpdate extension key "${t}" collides with a mandatory peer-advert field`);if(t===`topology/peers`)throw Error(`sendGossipUpdate extension key "${t}" collides with a session-managed gossip field`);if(t===`wire-mesh/version`)throw Error(`sendGossipUpdate extension key "${t}" is reserved for wire-mesh-core's own self-reported version`);if(!uM.test(t))throw Error(`sendGossipUpdate extension key "${t}" must be domain-qualified as "<domain>/<field>" (e.g. "presence/status")`)}}function fM(){let e=[],t=[];return{push(n){let r=e.shift();r===void 0?t.push(n):r(n)},stream:{[Symbol.asyncIterator](){return{next:async()=>new Promise(n=>{let r=t.shift();r===void 0?e.push(e=>{n({value:e,done:!1})}):n({value:r,done:!1})})}}}}}var pM=[`core/federation`];function mM(e,t){let n=Math.min(e.version,t.version),r=e.domains.filter(e=>!pM.includes(e)&&t.domains.includes(e));return{ok:n>=1&&r.length>0,version:n,sharedDomains:r}}function hM(e){return`data/${dO(e)}/head`}function gM(e,t){return`data/${dO(e)}/entry/${String(t)}`}async function _M(e,t){let n=await e.get(hM(t));return n===void 0?0:Number(new TextDecoder().decode(n))}async function vM(e,t,n){await e.set(hM(t),new TextEncoder().encode(String(n)))}async function yM(e,t){return _M(e,t)}async function bM(e,t){let n=await _M(e.storage,e.identity.deviceId)+1;return await e.storage.set(gM(e.identity.deviceId,n),t),await vM(e.storage,e.identity.deviceId,n),{seq:n,haveFrame:{type:`data-have`,peer:e.identity.deviceId,"head-seq":n}}}async function xM(e,t,n){let r=await _M(e,t.peer);if(r<=t[`from-seq`])return null;let i=Math.min(r,t[`from-seq`]+n),a=[];for(let n=t[`from-seq`]+1;n<=i;n+=1){let r=await e.get(gM(t.peer,n));if(r===void 0)break;a.push(r)}return a.length===0?null:{type:`data-entries`,peer:t.peer,"from-seq":t[`from-seq`],entries:a}}async function SM(e,t){let n=await _M(e,t.peer);if(t[`from-seq`]!==n)return{ok:!1,reason:`gap`};let r=t[`from-seq`];for(let n of t.entries)r+=1,await e.set(gM(t.peer,r),n);return await vM(e,t.peer,r),{ok:!0}}async function CM(e,t,n){let r=await _M(e,t),i=[];for(let a=n+1;a<=r;a+=1){let n=await e.get(gM(t,a));if(n===void 0)break;i.push(n)}return i}function wM(e){return e.type===`data-have`||e.type===`data-request`||e.type===`data-entries`}var TM=class extends Error{constructor(){super(`timed out waiting for pong`),this.name=`PingTimeoutError`}};function EM(){let e=[];function t(t){let n=e.findIndex(e=>e.sentAt===t);return n!==-1&&(e.splice(n,1),!0)}return{resolveOldest(t){let n=e.shift();n!==void 0&&n.resolve(t-n.sentAt)},rejectAll(t){for(let n of e.splice(0))n.reject(Error(t))},async sendAndAwait(n,r,i){let a=new Promise((t,r)=>{e.push({sentAt:n,resolve:t,reject:r})});return await r(),i===void 0?a:Promise.race([a,new Promise((e,r)=>{setTimeout(()=>{t(n)&&r(new TM)},i)})])}}}function DM(e){return e.authenticatedPeer===void 0?e.isAccepted?e.firstAdvertisedPeer??void 0:void 0:e.authenticatedPeer}function OM(e){let t=DM(e);return{direct:t===void 0?[]:[t],relayed:e.relayedDevices.map(e=>({device:e,...t===void 0?{}:{via:t}}))}}function kM(e){let t=null;return{recordAdvert:e=>{t??=e},compute:()=>{let n=e.getAuthenticatedPeer();return OM({...n===void 0?{}:{authenticatedPeer:n},firstAdvertisedPeer:t,isAccepted:e.isAccepted,relayedDevices:e.getRelayedDevices()})}}}function AM(){let e=new Map;return{has:t=>e.has(dO(t)),add:t=>{e.set(dO(t),t)},remove:t=>{e.delete(dO(t))},clear:()=>{e.clear()},list:()=>[...e.values()]}}var jM=16,MM=256,NM=256,PM=12,FM=4,IM=8,LM=new TextEncoder,RM=LM.encode(`wire-mesh/secure-hello/v1\0`),zM=LM.encode(`wire-mesh/secure-channel/v1\0`),BM=LM.encode(`wire-mesh/secure-data/v1\0`),VM=LM.encode(`lo-to-hi`),HM=LM.encode(`hi-to-lo`),UM={name:`ECDH`,namedCurve:`P-256`};function WM(...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}function GM(e,t){for(let n=0;n<Math.min(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return e.length-t.length}function KM(e){let t=new Uint8Array(IM);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function qM(e,t,n,r){return WM(RM,e,t,n,r)}async function JM(e,t){let n=await crypto.subtle.generateKey(UM,!1,[`deriveBits`]),r=new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)),i=crypto.getRandomValues(new Uint8Array(jM)),a=await e.sign(qM(r,i,e.deviceId,t));return{peer:t,privateKey:n.privateKey,hello:{type:`secure-hello`,"ephemeral-key":r,nonce:i,"identity-key":e.identityKey,"to-device":t,signature:a}}}async function YM(e,t){let n=t[`identity-key`];try{let r=await e.deriveDeviceId(n[`public-key`]);return AO(t[`to-device`],e.deviceId)?await e.verify(n,qM(t[`ephemeral-key`],t.nonce,r,e.deviceId),t.signature)?{ok:!0,peer:{deviceId:r,identityKey:n}}:{ok:!1,reason:`bad_signature`}:{ok:!1,reason:`wrong_recipient`}}catch{return{ok:!1,reason:`identity_mismatch`}}}function XM(e){let t=new Uint8Array(PM);return t.set(KM(e),FM),t}function ZM(e,t,n){return WM(BM,e,t,KM(n))}async function QM(e,t,n,r,i){let a=await crypto.subtle.importKey(`raw`,Uint8Array.from(e),`HKDF`,!1,[`deriveKey`]);return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:Uint8Array.from(t),info:WM(zM,n,r,i)},a,{name:`AES-GCM`,length:MM},!1,[`encrypt`,`decrypt`])}async function $M(e,t,n,r){let i;try{let e=await crypto.subtle.importKey(`raw`,Uint8Array.from(n[`ephemeral-key`]),UM,!1,[]);i=new Uint8Array(await crypto.subtle.deriveBits({name:`ECDH`,public:e},t.privateKey,NM))}catch{return}let a=GM(e.deviceId,r.deviceId)<0,o=a?e.deviceId:r.deviceId,s=a?r.deviceId:e.deviceId,c=WM(a?t.hello.nonce:n.nonce,a?n.nonce:t.hello.nonce),l=await QM(i,c,o,s,VM),u=await QM(i,c,o,s,HM),d=a?l:u,f=a?u:l,p=0,m=-1,h=Promise.resolve(),g=Promise.resolve();async function _(t,n){return{type:`secure-data`,counter:n,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:XM(n),additionalData:ZM(e.deviceId,r.deviceId,n)},d,Kj(t)))}}async function v(t){if(t.counter<=m)return;let n;try{n=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:XM(t.counter),additionalData:ZM(r.deviceId,e.deviceId,t.counter)},f,Uint8Array.from(t.ciphertext)))}catch{return}return m=t.counter,Xj(n)??void 0}return{peer:r,seal:async e=>{let t=p;p+=1;let n=h.then(async()=>_(e,t));return h=n.catch(()=>void 0),n},open:async e=>{let t=g.then(async()=>v(e));return g=t.catch(()=>void 0),t}}}function eN(e,t){let n=new Map;function r(r){let i=dO(r),a=Promise.withResolvers(),o=JM(e,r),s={status:`awaiting`,pending:o,settle:a};return n.set(i,s),o.then(async({hello:e})=>t(r,e)).catch(e=>{a.reject(e instanceof Error?e:Error(String(e))),n.get(i)===s&&n.delete(i)}),s}return{ensure:async e=>{let t=n.get(dO(e));return t?.status===`established`?t.channel:(t??r(e)).settle.promise},applyHello:async t=>{let i=await YM(e,t);if(!i.ok)return;let a=dO(i.peer.deviceId),o=n.get(a),s=o?.status===`awaiting`?o:r(i.peer.deviceId),c=await $M(e,await s.pending,t,i.peer);if(c===void 0){s.settle.reject(Error(`the peer sent an unusable ephemeral key`)),n.get(a)===s&&n.delete(a);return}n.set(a,{status:`established`,channel:c}),s.settle.resolve(c)},open:async(e,t)=>{if(t===void 0)return;let r=n.get(dO(t));if(r?.status!==`established`)return;let i=await r.channel.open(e);return i===void 0?void 0:{frame:i,from:r.channel.peer.deviceId}},reset:e=>{for(let t of n.values())t.status===`awaiting`&&t.settle.reject(Error(e));n.clear()},forget:e=>{let t=dO(e),r=n.get(t);r?.status===`awaiting`&&r.settle.reject(Error(`the relay pairing was lost`)),n.delete(t)}}}var tN=1e3,nN=3e3;function rN(e){return{type:`handshake`,version:1,domains:[...e]}}function iN(e,t,n,r,i,a=[],o,s){let c=null,l={status:`idle`},u={status:`pending`},d=new Map,f=[];function p(e){f.push(e),f.length>256&&f.splice(0,f.length-256)}let m=!1,h=fM(),g=null,_=null,v=0,y=null,b=0,x=AM(),S=kM({getAuthenticatedPeer:()=>c?.peerDeviceId,isAccepted:r===null,getRelayedDevices:()=>x.list()}),C=new Map,w=eN(e,async(e,t)=>{if(c===null)throw Error(`not connected`);p({direction:`sent`,frame:t}),await c.send(qj(t,e)),j()}),T=fM(),E=fM(),D=fM(),O=fM(),k=EM();function A(){return{state:l,directory:[...d.values()],frameLog:[...f]}}function j(){h.push(A())}function M(e){for(let t of C.values())t.reject(Error(e));C.clear()}function N(e,t,n){let r=b;b+=1;let i=n??y;return{type:`manage-request`,"request-id":r,command:e,scope:t,...i===null?{}:{token:i}}}function ee(){if(c===null||l.status!==`connected`)throw Error(`not connected`);return c}async function P(e,t,n){if(c===null)throw Error(`not connected`);if(!t){await c.send(e);return}if(n===void 0)throw Error(`a relayed frame needs the device it is for`);let r=await(await w.ensure(n)).seal(e);await c.send(qj(r,n))}function F(e,t){let n=e[`request-id`],r=C.get(n);if(r===void 0)return;let i=r.expectedFrom;(i===void 0?t===void 0:t!==void 0&&dO(t)===dO(i))&&(C.delete(n),r.resolve(e.outcome))}function I(e,t){let n=e[`request-id`],r=t?.fromDevice,i=t?.toDevice,a={requestId:n,command:e.command,scope:e.scope,...e.token===void 0?{}:{token:e.token},...r===void 0?{}:{fromDevice:r},...i===void 0?{}:{toDevice:i},respond:async e=>{let i={type:`manage-response`,"request-id":n,outcome:e};p({direction:`sent`,frame:i}),await P(i,t!==void 0,r),j()}};if(oM(e.command.params)){a.respond(sM());return}T.push(a)}async function te(n){if(n.type===`relay-data`){let e=Xj(n.payload);if(e?.type===`secure-hello`){p({direction:`received`,frame:e}),await w.applyHello(e);return}if(e?.type===`secure-data`){let t=await w.open(e,n[`from-device`]);t?.frame.type===`manage-response`?(p({direction:`received`,frame:t.frame}),F(t.frame,t.from)):t!==void 0&&wM(t.frame)?(p({direction:`received`,frame:t.frame}),O.push({frame:t.frame,fromDevice:t.from,...n[`to-device`]===void 0?{}:{toDevice:n[`to-device`]}})):t?.frame.type===`manage-request`&&(p({direction:`received`,frame:t.frame}),I(t.frame,{fromDevice:t.from,...n[`to-device`]===void 0?{}:{toDevice:n[`to-device`]}}));return}p({direction:`received`,frame:n});return}if(p({direction:`received`,frame:n}),n.type===`handshake`)ie(n);else if(n.type===`gossip`)for(let t of n.peers)await nM(e,t)&&(d.set(dO(t.device),{device:t.device,advert:t}),S.recordAdvert(t.device),i?.(t));else if(n.type===`relay-inbound`)x.add(n[`source-device`]);else if(n.type===`manage-response`)F(n);else if(n.type===`manage-request`)I(n);else if(n.type===`pong`)k.resolveOldest(t.now());else if(n.type===`revocation-announce`)for(let e of n.entries)E.push(e);else wM(n)?O.push({frame:n}):n.type===`coordinator`&&D.push(n)}async function ne(e){if(c===null)throw Error(`not connected`);if(x.has(e))return;let t={type:`relay-connect`,"target-device":e};p({direction:`sent`,frame:t}),await c.send(t),x.add(e),j()}let re=rN([]);function ie(e){if(u.status!==`pending`)return;g!==null&&(clearTimeout(g),g=null);let t=mM(re,e);u=t.ok?{status:`negotiated`,version:t.version,sharedDomains:t.sharedDomains}:{status:`rejected`,reason:`no shared domains or version`},l.status===`connected`&&(l={...l,handshake:u})}function L(e,t){return e.redialAddress?.()??t}function R(e,t,r){if(!m){if(M(`disconnected before a response arrived`),k.rejectAll(`disconnected before a pong arrived`),n!==null&&v<n.maxAttempts){v+=1;let i=v;l={status:`reconnecting`,address:t,attempt:i,reason:e},j(),_=setTimeout(()=>{_=null,ce(t,r).catch(e=>{R(e instanceof Error?e.message:String(e),t,r)})},n.delayMs(i));return}l={status:`closed`,address:t,reason:e},j()}}async function ae(e,t,n){let r=!1;for await(let t of e.receive()){if(m)return;r||(r=!0,v=0),await te(t),await o?.(e,t),j()}s?.(e),l.status===`connected`&&R(`node closed the connection`,L(e,t),n)}async function oe(n){return n!==void 0&&dM(n),{type:`gossip`,peers:[await tM(e,{...n,[iM]:rM,[lM]:S.compute(),device:e.deviceId,addresses:[...a],"snapshot-seconds":Math.floor(t.now()/tN),"identity-key":e.identityKey})]}}async function se(e,t,n){c=e,w.reset(`the connection changed before the channel was ready`),x.clear(),re=rN(n),u={status:`pending`},l={status:`connected`,address:t,handshake:u},p({direction:`sent`,frame:re}),await c.send(re),j();let r=await oe();p({direction:`sent`,frame:r}),await c.send(r),j(),g=setTimeout(()=>{g=null,u.status===`pending`&&(u={status:`unanswered`},l.status===`connected`&&(l={...l,handshake:u}),j())},nN),ae(c,t,n).catch(r=>{l.status===`connected`&&R(r instanceof Error?r.message:String(r),L(e,t),n)})}async function ce(e,t){if(r===null)throw Error(`this session is already connected; there is nothing to dial`);g!==null&&(clearTimeout(g),g=null),l={status:`connecting`,address:e},j();let n=await r(e);if(m){await n.close();return}await se(n,e,t)}return{wireUpConnection:se,session:{events:h.stream,incomingManageRequests:T.stream,revocationAnnouncements:E.stream,coordinatorFrames:D.stream,incomingDataFrames:O.stream,async connect(e,t){if(c!==null)throw Error(`a session connects once; create a new one to reconnect`);v=0,await ce(e,t).catch(n=>{throw R(n instanceof Error?n.message:String(n),e,t),n})},async sendPing(){let e=ee(),t={type:`ping`};p({direction:`sent`,frame:t}),await e.send(t),j()},async sendPingMeasureRtt(e){let n=ee();return k.sendAndAwait(t.now(),async()=>{let e={type:`ping`};p({direction:`sent`,frame:e}),await n.send(e),j()},e)},setToken(e){y=e},async sendManageRequest(e,t,n,r,i){ee(),n!==void 0&&await ne(n);let a=N(e,t,r),o=a[`request-id`],s=new Promise((e,t)=>{C.set(o,{resolve:e,reject:t,expectedFrom:n})});p({direction:`sent`,frame:a});let c=(async()=>{try{await P(a,n!==void 0,n)}catch(e){throw C.delete(o),s.catch(()=>void 0),e}return j(),s})();return i===void 0?c:Promise.race([c,new Promise(e=>{setTimeout(()=>{C.delete(o)&&(n!==void 0&&(x.remove(n),w.forget(n)),e({result:`error`,code:`timeout`}))},i)})])},async sendRevocationAnnounce(e){ee();let t={type:`revocation-announce`,entries:[...e]};p({direction:`sent`,frame:t}),await P(t,!1),j()},async sendCoordinatorClaim(e){ee();let t={...e};p({direction:`sent`,frame:t}),await P(t,!1),j()},async sendGossipUpdate(e){ee();let t=await oe(e);p({direction:`sent`,frame:t}),await P(t,!1),j()},getTopologyPeers(){return S.compute()},async sendDataFrame(e,t){ee(),t!==void 0&&await ne(t),p({direction:`sent`,frame:e}),await P(e,t!==void 0,t),j()},async close(){m=!0,g!==null&&(clearTimeout(g),g=null),_!==null&&(clearTimeout(_),_=null),M(`connection closed before a response arrived`),w.reset(`the session closed before the channel was ready`),k.rejectAll(`connection closed before a pong arrived`),c!==null&&await c.close(),(l.status===`connected`||l.status===`connecting`||l.status===`reconnecting`)&&(l={status:`closed`,address:l.address,reason:`closed by you`}),j()}}}}function aN(e,t,n={now:()=>Date.now()},r=null,i=[],a,o){let{session:s}=iN(t,n,r,async t=>e.connect(t),a,i,o);return s}async function oN(e,t,n,r={}){let i=r.clock??{now:()=>Date.now()},a=null,o=new Promise(e=>{a=e}),s=!1,{session:c,wireUpConnection:l}=iN(t,i,null,null,e=>{s||(s=!0,a?.(e.device)),r.onPeerAdvert?.(e)},r.addresses,r.onFrame,r.onSessionEnd);return await l(e,r.label??`accepted`,n),{...c,peerDeviceId:o}}function sN(e){return e instanceof Error?e:Error(String(e))}function cN(e){let t=dO(e.selfDeviceId),n=new Set;async function r(t){let n;try{n=await e.shouldExpand(t)}catch(n){e.onExpansionFailed?.(t,[sN(n)]);return}if(!n){e.onExpansionDeclined?.(t);return}let r=[];for(let n of t.addresses)try{let r=await e.dial(n);e.onExpanded(t,n,r);return}catch(e){r.push(sN(e))}e.onExpansionFailed?.(t,r)}return{considerAdvert(e){let i=dO(e.device);i===t||n.has(i)||e.addresses.length===0||(n.add(i),r({device:e.device,addresses:e.addresses}))}}}var lN=/^[0-9a-f]{64}$/,uN=/^[A-Za-z0-9_-]+$/;function dN(e,t){if(!lN.test(e))throw Error(`expected ${t} to be a 64-character lowercase hex device-id, got ${JSON.stringify(e)}`)}function fN(e,t){if(dN(e,`a`),dN(t,`b`),e===t)throw Error(`a DM room path cannot name the same device twice (${e})`);return e<t?`${e}+${t}`:`${t}+${e}`}function pN(e){let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(0,t),r=e.slice(t+1);if(lN.test(n)&&uN.test(r))return{kind:`owner-named`,owner:n,localName:r}}let n=e.indexOf(`+`);if(n!==-1){let t=e.slice(0,n),r=e.slice(n+1);if(lN.test(t)&&lN.test(r)&&t!==r)return{kind:`dm`,participants:[t,r]}}throw Error(`${JSON.stringify(e)} is not a valid room-path`)}var mN=5,hN=1e3,gN=3e4,_N=2,vN={maxAttempts:mN,delayMs:e=>Math.min(hN*_N**(e-1),gN)},yN=4,bN=1024,xN=bN*bN*100,SN=new Uint8Array(yN);function CN(e){let t=Mg(e,hg),n=new Uint8Array(yN+t.length);return new DataView(n.buffer).setUint32(0,t.length),n.set(t,yN),n}function wN(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*TN(e){let t=new Uint8Array;try{for(;;){let n=await e.read();if(n.done)return;for(t=wN(t,n.value);t.length>=yN;){let e=new DataView(t.buffer,t.byteOffset).getUint32(0);if(e>104857600)throw Error(`frame of ${String(e)} bytes exceeds the ${String(xN)}-byte limit`);if(t.length<yN+e)break;if(e===0){t=t.slice(yN);continue}let n=t.slice(yN,yN+e);t=t.slice(yN+e);let r=ME.safeParse(b_(n,x_));r.success&&(yield r.data)}}}catch(t){throw await e.cancel(t),t}}function EN(e,t={opened:!1}){let n=e.writable.getWriter(),r=e.readable.getReader(),i=TN(r),a=t.opened?n.write(SN):Promise.resolve();return a.catch(()=>void 0),{send:async e=>{await a,await n.write(CN(e))},receive:()=>i,close:async()=>{await Promise.allSettled([n.close(),r.cancel()])}}}var DN=`/wire-mesh`,ON=8e3,kN=`the web console is a client only: it cannot listen`;async function AN(e){let t=e.incomingUnidirectionalStreams.getReader(),n=await t.read();if(t.releaseLock(),n.done)throw Error(`the node opened no announcement stream`);let r=n.value;if(!(r instanceof ReadableStream))throw Error(`the announcement stream is not a readable stream`);let i=[],a=r.getReader();for(;;){let e=await a.read();if(e.done)break;if(!(e.value instanceof Uint8Array))throw Error(`the announcement carried something other than bytes`);i.push(e.value)}let o=new Uint8Array(i.reduce((e,t)=>e+t.length,0)),s=0;for(let e of i)o.set(e,s),s+=e.length;return K_(o)}async function jN(e){let t,n=new Promise(e=>{t=setTimeout(()=>{e(`timed out`)},ON)});try{let t=await Promise.race([e.createBidirectionalStream(),n]);if(t===`timed out`)throw e.close(),Error(`this browser cannot open a stream to this node: it is waiting for flow-control credit the node never grants, which is how Safari behaves with the node's HTTP/3 library (fails-components/webtransport#490); reach the node over wss:// instead`);return t}finally{clearTimeout(t)}}function MN(e){return{async connect(t){if(typeof WebTransport>`u`)throw Error(`this browser does not support WebTransport`);let{url:n,sha256:r}=U_(t),i=new URL(n).host,a=q_(r,await e.recall(i)),o=new WebTransport(new URL(DN,n).toString(),{serverCertificateHashes:a.map(e=>({algorithm:`sha-256`,value:e}))});await o.ready;let s=EN(await jN(o),{opened:!0});o.closed.catch(()=>void 0).then(async()=>s.close());let c;return AN(o).then(async t=>{c=t,await e.remember(i,t)}).catch(()=>void 0),{...s,redialAddress:()=>c===void 0?t:Y_(t,c)}},async listen(){return Promise.reject(Error(kN))}}}var NN=1e3,PN=1002,FN=`the web console is a client only: it cannot listen`;function IN(e){let t=[],n=[],r=!1,i=null;function a(){r=!0;for(let e of n.splice(0))e.resolve({value:void 0,done:!0})}function o(e){i=e,r=!0;for(let t of n.splice(0))t.reject(e)}e.addEventListener(`message`,r=>{if(!(r.data instanceof ArrayBuffer)){o(Error(`expected a binary WebSocket message`)),e.close(PN,`protocol error`);return}let i;try{i=Yj(r.data)}catch(t){if(t instanceof Jj)return;o(t instanceof Error?t:Error(`frame body failed to decode: ${String(t)}`)),e.close(PN,`protocol error`);return}let a=n.shift();a?a.resolve({value:i,done:!1}):t.push(i)}),e.addEventListener(`close`,a),e.addEventListener(`error`,a);let s={[Symbol.asyncIterator](){return{next:async()=>c()}}};async function c(){let e=t.shift();return e===void 0?i===null?r?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})}):Promise.reject(i):Promise.resolve({value:e,done:!1})}return{async send(t){return r?Promise.reject(Error(`connection is closed`)):(e.send(Kj(t)),Promise.resolve())},receive:()=>s,async close(){return e.close(NN),Promise.resolve()}}}function LN(){return{async connect(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)return Promise.reject(Error(`not a WebSocket address: ${e}`));let n=new WebSocket(t);return n.binaryType=`arraybuffer`,new Promise((e,r)=>{n.addEventListener(`open`,()=>{e()}),n.addEventListener(`error`,()=>{r(Error(`connect to ${t.toString()} failed`))})}).then(()=>IN(n))},async listen(){return Promise.reject(Error(FN))}}}function RN(e){let t=LN(),n=MN(e);return{connect:async e=>H_(e)?n.connect(e):t.connect(e),listen:async(e,n)=>t.listen(e,n)}}var zN=[{urls:`stun:stun.cloudflare.com:3478`}],BN=`webrtc:signal`,VN={kind:`node`};function HN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.offer`}function UN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.answer`}function WN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.ice-candidate`}function GN(e,t){return{verb:BN,params:{verb:`webrtc.offer`,"negotiation-id":e,sdp:t}}}function KN(e,t){return{verb:BN,params:{verb:`webrtc.answer`,"negotiation-id":e,sdp:t}}}function qN(e,t){return{verb:BN,params:{verb:`webrtc.ice-candidate`,"negotiation-id":e,...t===void 0?{}:{candidate:t}}}}function JN(e){return{candidate:e.candidate,...e.sdpMid===null?{}:{"sdp-mid":e.sdpMid},...e.sdpMLineIndex===null?{}:{"sdp-m-line-index":e.sdpMLineIndex},...e.usernameFragment===null?{}:{"username-fragment":e.usernameFragment}}}function YN(e){return{candidate:e.candidate,...e[`sdp-mid`]===void 0?{}:{sdpMid:e[`sdp-mid`]},...e[`sdp-m-line-index`]===void 0?{}:{sdpMLineIndex:e[`sdp-m-line-index`]},...e[`username-fragment`]===void 0?{}:{usernameFragment:e[`username-fragment`]}}}function XN(){let e=0;return()=>{let t=e;return e+=1,t}}async function ZN(e,t){if(e.token===void 0)return!1;let n=await JA(e.token,t);return n.ok?n.claims.capability===`webrtc:signal`&&n.claims.scope.kind===VN.kind:!1}function QN(e){let t=[],n=[],r=!1,i=null;function a(){r=!0;for(let e of n.splice(0))e.resolve({value:void 0,done:!0})}function o(e){i=e,r=!0;for(let t of n.splice(0))t.reject(e)}e.addEventListener(`message`,r=>{if(!(r.data instanceof ArrayBuffer)){o(Error(`expected a binary data channel message`)),e.close();return}let i;try{i=Yj(r.data)}catch(t){if(t instanceof Jj)return;o(t instanceof Error?t:Error(`frame body failed to decode: ${String(t)}`)),e.close();return}let a=n.shift();a?a.resolve({value:i,done:!1}):t.push(i)}),e.addEventListener(`close`,a),e.addEventListener(`error`,a);let s={[Symbol.asyncIterator](){return{next:async()=>c()}}};async function c(){let e=t.shift();return e===void 0?i===null?r?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})}):Promise.reject(i):Promise.resolve({value:e,done:!1})}return{async send(t){return e.readyState===`open`?(e.send(Kj(t)),Promise.resolve()):Promise.reject(Error(`data channel is not open (state: ${e.readyState})`))},receive:()=>s,async close(){return e.close(),Promise.resolve()}}}var $N=`wire-mesh`;function eP(e,t){for(let n of t.localTracks??[])e.addTrack(n);t.onRemoteTrack!==void 0&&e.addEventListener(`track`,t.onRemoteTrack)}function tP(e,t){e.addEventListener(`open`,()=>{t(QN(e))},{once:!0})}var nP=16,rP=36e5;async function iP(e,t){let n=new Uint8Array(nP);crypto.getRandomValues(n);let r=await tj({identity:e,clock:t,tokenId:n,bearer:e.deviceId,capability:BN,scope:VN,expires:t.now()+rP});if(!r.ok)throw Error(`could not mint a webrtc:signal token: ${r.reason}`);return r.token}function aP(e,t){let n={identity:t.identity,clock:t.clock,revocation:t.revocation},r=new Map,i=new Map,a=XN();async function o(t,n){let r=qN(t,n===null?void 0:JN(n));await e.sendManageRequest(r,VN,i.get(t))}async function s(a,s){if(!await ZN(a,n)){await a.respond({result:`error`,code:`unauthorized`});return}let c=s[`negotiation-id`];i.set(c,a.fromDevice);let l=new RTCPeerConnection({iceServers:[...t.iceServers]});r.set(c,l),eP(l,t),l.addEventListener(`icecandidate`,e=>{o(c,e.candidate)}),l.addEventListener(`datachannel`,e=>{e.channel.binaryType=`arraybuffer`,tP(e.channel,t.onIncomingConnection)}),await l.setRemoteDescription({type:`offer`,sdp:s.sdp});let u=await l.createAnswer();await l.setLocalDescription(u),await a.respond({result:`ok`}),await e.sendManageRequest(KN(c,u.sdp??``),VN,a.fromDevice)}async function c(e,t){let n=r.get(t[`negotiation-id`]);n!==void 0&&await n.setRemoteDescription({type:`answer`,sdp:t.sdp}),await e.respond({result:`ok`})}async function l(e,t){let n=r.get(t[`negotiation-id`]);n!==void 0&&await n.addIceCandidate(t.candidate===void 0?null:YN(t.candidate)),await e.respond({result:`ok`})}async function u(){for await(let t of e.incomingManageRequests){if(t.command.verb!==`webrtc:signal`)continue;let e=t.command.params;HN(e)?await s(t,e):UN(e)?await c(t,e):WN(e)&&await l(t,e)}}return u(),{async initiate(n){let s=a();i.set(s,n);let c=new RTCPeerConnection({iceServers:[...t.iceServers]});r.set(s,c),eP(c,t),c.addEventListener(`icecandidate`,e=>{o(s,e.candidate)});let l=c.createDataChannel($N);l.binaryType=`arraybuffer`;let u=new Promise((e,t)=>{tP(l,e),l.addEventListener(`error`,()=>{t(Error(`data channel failed to open`))},{once:!0})}),d=await c.createOffer();await c.setLocalDescription(d);let f=await e.sendManageRequest(GN(s,d.sdp??``),VN,n,await iP(t.identity,t.clock));if(f.result===`error`)throw r.delete(s),i.delete(s),c.close(),Error(`webrtc offer rejected: ${f.code}`);return u}}}var oP={frames:0,stage:void 0,handshake:void 0,issued:0,seen:new Set};function sP(e){return dO(e)}function cP(e,t){if(t.type===`gossip`)return e===`received`?t.peers.map(e=>({kind:`peer`,summary:`Peer seen:`,peer:sP(e.device)})):[{kind:`peer`,summary:`Advertised this console to the node`,peer:void 0}];if(t.type===`relay-connect`)return[{kind:`pairing`,summary:`Asked the node to pair this console with`,peer:sP(t[`target-device`])}];if(t.type===`relay-inbound`)return[{kind:`pairing`,summary:`Pairing established with`,peer:sP(t[`source-device`])}];if(t.type===`relay-data`){let n=e===`sent`?t[`to-device`]:t[`from-device`];return[{kind:`relay`,summary:e===`sent`?`Relayed a message to`:`Relayed message received from`,peer:n===void 0?void 0:sP(n)}]}return t.type===`close`?[{kind:`connection`,summary:`The node closed the connection`,peer:void 0}]:[]}function lP(e){return e.status===`reconnecting`?`reconnecting:${String(e.attempt)}`:e.status}function uP(e,t,n){let r=[],i=e=>{r.push({kind:`connection`,summary:e,peer:void 0})};if(lP(t)!==e.stage)switch(t.status){case`connecting`:i(`Connecting to ${t.address}`);break;case`connected`:i(`Connected to ${t.address}`);break;case`reconnecting`:i(`${e.stage?.startsWith(`reconnecting`)===!0?`Retry failed`:`Connection lost`} (${t.reason}); retrying, attempt ${String(t.attempt)}`);break;case`closed`:i(`Closed (${t.reason})`)}return t.status===`connected`&&n!==e.handshake&&(t.handshake.status===`negotiated`?i(`Handshake negotiated: ${t.handshake.sharedDomains.join(`, `)}`):t.handshake.status===`unanswered`?i(`The node does not answer handshakes (a relay-only node)`):t.handshake.status===`rejected`&&i(`Handshake rejected (${t.handshake.reason})`)),r}function dP(e){return e.status===`connected`?e.handshake.status:void 0}function fP(e,t,n){let r=dP(t.state),i=new Set(e.seen),a=[...uP(e,t.state,r),...t.frameLog.slice(e.frames).flatMap(e=>cP(e.direction,e.frame)).filter(e=>e.kind!==`peer`||e.peer===void 0||!i.has(e.peer)&&(i.add(e.peer),!0))].map((t,r)=>({...t,key:`activity-${String(e.issued+r)}`,at:n}));return{tracker:{frames:t.frameLog.length,stage:lP(t.state),handshake:r,issued:e.issued+a.length,seen:i},entries:a}}function pP(e){return e.map(e=>({key:`certificate-${e.key}`,at:e.at,kind:`certificate`,summary:`Certificate changed: ${e.node} announced certificates unlike the remembered ones`,peer:void 0}))}function mP(e,t){let[n,r]=(0,k.useState)({event:void 0,activity:[],statusSince:void 0});return(0,k.useEffect)(()=>{let n={cancelled:!1};return(async()=>{let i=oP;for await(let a of e.events){if(n.cancelled)return;let e=t.now(),o=fP(i,a,e),s=o.tracker.stage!==i.stage;i=o.tracker,r(t=>({event:a,activity:[...t.activity,...o.entries].slice(-500),statusSince:s?e:t.statusSince}))}})(),()=>{n.cancelled=!0}},[e,t]),n}var hP=`local-network-access`,gP=4,_P=255,vP=8,yP=32,bP=[`10.0.0.0/8`,`127.0.0.0/8`,`172.16.0.0/12`,`192.168.0.0/16`,`169.254.0.0/16`,`100.64.0.0/10`];function xP(e){let t=e.split(`.`);if(t.length!==gP)return;let n=0;for(let e of t){let t=/^\d{1,3}$/.test(e)?Number(e):NaN;if(!(t<=_P))return;n=n*2**vP+t}return n}function SP(e,t){let[n,r]=t.split(`/`),i=xP(n??``),a=Number(r);if(i===void 0)return!1;let o=2**(yP-a);return Math.floor(e/o)===Math.floor(i/o)}function CP(e){let t=e.replace(/^\[|\]$/g,``).toLowerCase(),n=xP(t);return n===void 0?t.includes(`:`)?t===`::1`||/^f[cd]/.test(t)||/^fe[89ab]/.test(t):t===`localhost`||t.endsWith(`.local`)||!t.includes(`.`):bP.some(e=>SP(n,e))}function wP(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`ws://${e}`).hostname}catch{return}}function TP(e){return typeof e==`object`&&!!e&&`name`in e&&typeof e.name==`string`}function EP(){if(`permissions`in navigator)return{query:async e=>{if(!TP(e))throw TypeError(`not a permission descriptor`);return navigator.permissions.query(e)}}}async function DP(e,t,n){let r=wP(e);if(r!==void 0&&CP(r)&&!CP(t)&&n!==void 0)try{let{state:e}=await n.query({name:hP});return e===`denied`?`Your browser blocked this page from reaching ${r}, a device on your local network. Allow "Local network access" for this site in the browser's site settings (the icon left of the address), then connect again.`:void 0}catch{return}}var OP=(0,k.createContext)(void 0);function kP(){let e=(0,k.useContext)(OP);if(e===void 0)throw Error(`usePeerNames must be used inside PeerNamesProvider`);return e}var AP={pongTimeoutMs:5e3,intervalMs:15e3};function jP(e,t,n=AP){let[r,i]=(0,k.useState)([]),[a,o]=(0,k.useState)(!1),s=(0,k.useRef)(!1),c=(0,k.useCallback)(()=>{e.sendPingMeasureRtt(n.pongTimeoutMs).then(e=>{s.current=!0,o(!1),i(t=>[...t,e].slice(-40))},e=>{e instanceof TM&&(o(!s.current),i(e=>[...e,void 0].slice(-40)))})},[e,n.pongTimeoutMs]);return(0,k.useEffect)(()=>{if(!t||a)return;c();let e=setInterval(c,n.intervalMs);return()=>{clearInterval(e)}},[t,a,c,n.intervalMs]),{samples:r,unresponsive:a,probe:c}}function MP(e,t,n){let[r,i]=(0,k.useState)(()=>e.now());return(0,k.useEffect)(()=>{if(!t)return;let r=setInterval(()=>{i(e.now())},n);return()=>{clearInterval(r)}},[e,t,n]),r}var NP=1e3,PP=60,FP=60,IP=24;function LP(e){let t=Math.floor(e/NP);if(t<1)return;if(t<PP)return`${String(t)} s`;let n=Math.floor(t/PP);if(n<FP)return`${String(n)} min`;let r=Math.floor(n/FP);return r<IP?`${String(r)} h`:`${String(Math.floor(r/IP))} d`}function RP(e){let t=LP(e);return t===void 0?`just now`:`${t} ago`}function zP(e){let t=LP(e);return t===void 0?`in under a second`:`in ${t}`}function BP(e){return`${String(Math.max(0,Math.ceil(e/NP)))} s`}function VP(e,t,n){if(n.length===0)return{kind:`first-use`,node:e,presented:t};let r=new Set(n),i=t.filter(e=>r.has(e));return i.length>0?{kind:`known`,node:e,trusted:i}:{kind:`changed`,node:e,remembered:n,presented:t}}function HP(e){if(H_(e))try{let{url:t,sha256:n}=U_(e);return{node:new URL(t).host,sha256:[...n]}}catch{return}}function UP(e,t){return{recall:e.recall,remember:async(n,r)=>{let i=VP(n,r.map(e=>uO(e)),(await e.recall(n)).map(e=>uO(e)));await e.remember(n,r),i.kind===`changed`&&t({node:n,remembered:i.remembered,presented:i.presented})}}}var WP=2;function GP(e){let t=[];for(let n=0;n<e.length;n+=WP)t.push(e.slice(n,n+WP).toUpperCase());return t.join(`:`)}var KP=/^([a-z][a-z0-9+.-]*):\/\//i,qP={ws:`ws:`,wss:`wss:`,http:`ws:`,https:`wss:`};function JP(e){if(H_(e))return e;let t=KP.exec(e);if(t===null)return`ws://${e}`;let n=qP[t[1]?.toLowerCase()??``];if(n===void 0)return e;let r=new URL(e);return r.protocol=n,r.hash=``,r.toString()}function YP({deviceHex:e}){return(0,z.jsx)(z.Fragment,{children:Nj(kP().labelOf(e))})}function XP(e){return JSON.stringify(e,(e,t)=>t instanceof Uint8Array?`<${String(t.byteLength)} bytes>`:t)}function ZP({activity:e,frameLog:t}){let[n,r]=(0,k.useState)(!1);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(um,{mt:`md`,label:`Show raw frames`,checked:n,onChange:e=>{r(e.currentTarget.checked)}}),n?(0,z.jsx)(km.ScrollContainer,{minWidth:0,h:384,"data-testid":`frame-log`,children:(0,z.jsxs)(km,{children:[(0,z.jsx)(km.Thead,{children:(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Th,{children:`direction`}),(0,z.jsx)(km.Th,{children:`frame`})]})}),(0,z.jsx)(km.Tbody,{children:t.map((e,t)=>(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Td,{children:e.direction}),(0,z.jsx)(km.Td,{children:XP(e.frame)})]},t))})]})}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Activity`}),e.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Nothing has happened yet.`}):(0,z.jsx)(km.ScrollContainer,{minWidth:0,h:384,"data-testid":`activity-log`,children:(0,z.jsx)(km,{children:(0,z.jsx)(km.Tbody,{children:[...e].reverse().map(e=>(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Td,{children:new Date(e.at).toLocaleTimeString()}),(0,z.jsxs)(km.Td,{children:[e.summary,e.peer!==void 0&&(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)(YP,{deviceHex:e.peer})]})]})]},e.key))})})})]})]})}var QP=160,$P=32,eF=3,tF=2,nF=26;function rF(e){let t=e.at(-1);return t===void 0?e.length===0?`No round trips measured yet`:`Last ping got no pong`:`Round trip ${String(Math.round(t))} ms`}function iF({samples:e}){let t=e.filter(e=>e!==void 0),n=Math.max(1,...t),r=QP/39,i=(40-e.length)*r,a=e.map((e,t)=>({x:i+t*r,y:e===void 0?void 0:eF+nF*(1-e/n)})),o=a.filter(e=>e.y!==void 0).map(e=>`${e.x.toFixed(1)},${String(e.y)}`).join(` `);return(0,z.jsxs)(`div`,{"data-testid":`rtt-sparkline`,children:[(0,z.jsxs)(`svg`,{role:`img`,"aria-label":rF(e),width:QP,height:$P,viewBox:`0 0 ${String(QP)} ${String($P)}`,children:[(0,z.jsx)(`polyline`,{points:o,fill:`none`,stroke:`currentColor`,strokeWidth:1.5}),a.map(e=>e.y===void 0?null:(0,z.jsx)(`circle`,{cx:e.x,cy:e.y,r:tF,fill:`currentColor`},e.x)),a.filter(e=>e.y===void 0).map(e=>(0,z.jsx)(`line`,{x1:e.x,x2:e.x,y1:21,y2:29,stroke:`var(--mantine-color-red-6)`,strokeWidth:2},e.x))]}),(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:rF(e)})]})}function aF({state:e,statusSince:t,now:n,policy:r}){let i=t===void 0?void 0:t+r.delayMs(e.attempt),a=i===void 0?0:i-n;return(0,z.jsxs)(U,{size:`sm`,c:`orange`,"data-testid":`reconnect-status`,children:[a>0?`Retrying in ${BP(a)}`:`Retrying now`,` `,`(attempt `,e.attempt,` of `,r.maxAttempts,`). Last failure:`,` `,e.reason]})}function oF({state:e,statusSince:t,now:n,policy:r,health:i}){return e.status===`reconnecting`?(0,z.jsx)(aF,{state:e,statusSince:t,now:n,policy:r}):e.status===`connected`?(0,z.jsxs)(pl,{align:`flex-end`,gap:`md`,mb:`sm`,children:[(0,z.jsx)(iF,{samples:i.samples}),i.unresponsive&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`This node does not answer pings, so round trips are not measured automatically.`})]}):null}function sF(e){e?.focus()}function cF({deviceHex:e}){let t=kP(),n=t.labelOf(e),[r,i]=(0,k.useState)(void 0);return r===void 0?(0,z.jsxs)(pl,{gap:`xs`,wrap:`nowrap`,children:[(0,z.jsxs)(`div`,{children:[n.source===`self`&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`calls itself`}),(0,z.jsx)(U,{size:`sm`,fw:n.source===`petname`?`bold`:`normal`,fs:n.source===`self`?`italic`:`normal`,ff:n.source===`id`?`monospace`:`text`,children:n.primary}),n.matchesPetname&&(0,z.jsx)(_d,{size:`xs`,color:`orange`,variant:`light`,children:`same as a name you set`}),n.secondary!==void 0&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,ff:n.source===`self`?`monospace`:`text`,children:n.secondary})]}),(0,z.jsx)(zd,{value:e,children:({copied:e,copy:t})=>(0,z.jsx)(Zp,{label:e?`Copied`:`Copy device id`,children:(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Copy device id of ${n.primary}`,onClick:t,children:`⧉`})})}),(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Rename ${n.primary}`,onClick:()=>{i(t.petnameOf(e)??``)},children:`✎`})]}):(0,z.jsx)(`form`,{onSubmit:n=>{n.preventDefault(),t.rename(e,r).then(()=>{i(void 0)})},children:(0,z.jsxs)(pl,{gap:`xs`,wrap:`nowrap`,children:[(0,z.jsx)(Am,{size:`xs`,"aria-label":`Petname for ${n.primary}`,value:r,ref:sF,onChange:e=>{i(e.currentTarget.value)}}),(0,z.jsx)(rl,{type:`submit`,size:`sm`,"aria-label":`Save petname`,children:`✓`}),(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Cancel rename`,onClick:()=>{i(void 0)},children:`×`})]})})}var lF=`q7ltm10`,uF=`q7ltm11`;function dF({columns:e,rows:t}){return(0,z.jsxs)(km,{striped:!0,className:uF,children:[(0,z.jsx)(km.Thead,{role:`rowgroup`,children:(0,z.jsx)(km.Tr,{role:`row`,children:e.map(e=>(0,z.jsx)(km.Th,{role:`columnheader`,children:e.headerless===!0?null:e.label},e.label))})}),(0,z.jsx)(km.Tbody,{role:`rowgroup`,children:t.map(t=>(0,z.jsx)(km.Tr,{role:`row`,children:e.map((e,n)=>(0,z.jsx)(km.Td,{role:`cell`,"data-label":e.label,children:t.cells[n]},e.label))},t.key))})]})}var fF=16,pF=1e3;function mF(e){let t=``;for(let n of e)t+=n.toString(fF).padStart(2,`0`);return t}function hF(e){if(e.state.status!==`connected`)return``;switch(e.state.handshake.status){case`pending`:return` · handshake pending`;case`negotiated`:return` · v${String(e.state.handshake.version)} · ${e.state.handshake.sharedDomains.join(`, `)}`;case`unanswered`:return` · handshake unanswered (relay-only node?)`;case`rejected`:return` · handshake rejected (${e.state.handshake.reason})`}return``}function gF(e){let{state:t}=e;switch(t.status){case`connecting`:return`connecting…`;case`connected`:return`connected${hF(e)}`;case`reconnecting`:return`reconnecting (attempt ${String(t.attempt)}, ${t.reason})…`;case`closed`:return`closed (${t.reason})`;case`idle`:return`idle`}return``}var _F=1e3,vF=[{label:`device`},{label:`addresses`},{label:`advertised`},{label:`actions`,headerless:!0}];function yF({address:e,session:t,clock:n,reconnectPolicy:r,certificateChanges:i,onClose:a,onMessagePeer:o,pageHost:s=window.location.hostname,permissions:c=EP()}){let{event:l,activity:u,statusSince:d}=mP(t,n),f=l?.state.status===`reconnecting`||l?.state.status===`closed`,[p,m]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{let t={value:!0};return f&&DP(e,s,c).then(n=>{t.value&&m({address:e,message:n})}),()=>{t.value=!1}},[f,e,s,c]);let h=f&&p?.address===e?p.message:void 0,{observeDirectory:g,selfName:_}=kP(),v=l?.state.status===`connected`;(0,k.useEffect)(()=>{l!==void 0&&g(l.directory)},[l,g]);let y=(0,k.useRef)(!1),[b,x]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{v&&(_!==void 0||y.current)&&(y.current=_!==void 0,t.sendGossipUpdate(_===void 0?void 0:jj(_)).then(()=>{x(void 0)},e=>{x(e instanceof Error?e.message:String(e))}))},[v,_,t]);let S=l===void 0?`idle`:gF(l),C=l?.directory??[],w=l?.frameLog??[],T=jP(t,v),E=MP(n,l?.state.status===`reconnecting`||C.length>0,_F),D=HP(JP(e))?.node,O=(0,k.useMemo)(()=>[...u,...pP(i.filter(e=>e.node===D))].sort((e,t)=>e.at-t.at),[u,i,D]);return(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,children:[(0,z.jsxs)(pl,{justify:`space-between`,mb:`xs`,children:[(0,z.jsx)(U,{fw:600,children:e}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,disabled:!v,onClick:T.probe,children:`Send ping`}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:a,children:`Disconnect`})]})]}),(0,z.jsx)(U,{fw:600,size:`sm`,mb:`sm`,children:S}),h===void 0?null:(0,z.jsx)(eu,{color:`yellow`,mb:`sm`,children:h}),b!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Could not publish your display name`,mb:`sm`,children:b}),l!==void 0&&(0,z.jsx)(oF,{state:l.state,statusSince:d,now:E,policy:r,health:T}),(0,z.jsx)(U,{fw:600,size:`sm`,children:`Peer directory`}),C.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`No gossip received yet.`}):(0,z.jsx)(dF,{columns:vF,rows:C.map(e=>({key:mF(e.device),cells:[(0,z.jsx)(cF,{deviceHex:mF(e.device)},`device`),e.advert.addresses.join(`, `),(0,z.jsx)(Zp,{label:`As the peer advertised it, by its own clock`,children:(0,z.jsx)(`span`,{children:RP(E-e.advert[`snapshot-seconds`]*pF)})},`advertised`),(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{o(e.device)},children:`Message`},`actions`)]}))}),(0,z.jsx)(ZP,{activity:O,frameLog:w})]})}var bF=[{label:`device`},{label:`addresses`},{label:`gossiped by`},{label:`actions`,headerless:!0}];function xF({peers:e,onConnect:t,onDismiss:n}){return e.length===0?null:(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,"data-testid":`discovered-peers`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mb:`xs`,children:`Discovered peers`}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,mb:`xs`,children:`Each node below was listed in the directory of a node you are connected to, which is the only thing vouching for it: the address it lists may not be a wire-mesh node at all. Nothing is dialled until you connect.`}),(0,z.jsx)(dF,{columns:bF,rows:e.map(e=>({key:e.key,cells:[(0,z.jsx)(cF,{deviceHex:mF(e.device)},`device`),e.addresses.join(`, `),(0,z.jsxs)(k.Fragment,{children:[e.via.claimedDevice!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`claimed to be`}),(0,z.jsx)(cF,{deviceHex:e.via.claimedDevice})]}),(0,z.jsxs)(U,{size:`xs`,c:`dimmed`,children:[`over `,e.via.address]})]},`via`),(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{t(e.key)},children:`Connect`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,color:`red`,onClick:()=>{n(e.key)},children:`Dismiss`})]},`actions`)]}))})]})}function SF({label:e,hashes:t}){return(0,z.jsxs)(`div`,{children:[(0,z.jsx)(U,{size:`sm`,fw:600,children:e}),t.map(e=>(0,z.jsx)(Ld,{block:!0,children:GP(e)},e))]})}function CF({prompt:e}){let{assessment:t,decide:n}=e,r=t.kind===`changed`;return(0,z.jsx)(eu,{color:r?`red`:`blue`,title:r?`Certificate changed for ${t.node}`:`First connection to ${t.node}`,"data-testid":`certificate-prompt`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:r?`This address presents a certificate that shares nothing with the one remembered for this node. The node may have replaced its certificate, or something else may be answering at this address. Only continue if you expected the change.`:`This console has not connected to this node before. Connecting pins the certificate below as the one to expect from it from now on. Compare it with what the node's operator reports before you trust it.`}),r&&(0,z.jsx)(SF,{label:`Remembered`,hashes:t.remembered}),(0,z.jsx)(SF,{label:r?`Presented now`:`Certificate (SHA-256)`,hashes:t.presented}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:r?`red`:`blue`,onClick:()=>{n(!0)},children:r?`Trust the new certificate`:`Trust and connect`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{n(!1)},children:`Cancel`})]})]})})}function wF({prompts:e,changes:t,onDismissChange:n}){let r=t.filter(e=>!e.dismissed);return e.length===0&&r.length===0?null:(0,z.jsxs)(rm,{gap:`sm`,"data-testid":`certificate-trust`,children:[e.map(e=>(0,z.jsx)(CF,{prompt:e},e.key)),r.map(e=>(0,z.jsx)(eu,{color:`red`,title:`${e.node} announced different certificates`,withCloseButton:!0,closeButtonLabel:`Dismiss`,onClose:()=>{n(e.key)},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`The node is still reachable through the certificate you pinned, but it now announces certificates that share nothing with the ones remembered for it, and the announced set is what this console will pin from now on.`}),(0,z.jsx)(SF,{label:`Remembered`,hashes:e.remembered}),(0,z.jsx)(SF,{label:`Announced`,hashes:e.presented})]})},e.key))]})}function TF(e,t){let[n,r]=(0,k.useState)([]),[i,a]=(0,k.useState)([]),o=(0,k.useMemo)(()=>UP(e,e=>{a(n=>[...n,{...e,key:crypto.randomUUID(),at:t.now(),dismissed:!1}])}),[e,t]),s=(0,k.useRef)(new Map),c=(0,k.useRef)(new Map);(0,k.useEffect)(()=>{let e=c.current;return()=>{for(let{refuse:t}of[...e.values()])t()}},[]);let l=(0,k.useCallback)(async e=>{let t=`${e.node} ${[...e.presented].sort().join(`,`)}`,n=s.current.get(t);if(n!==void 0)return n.decision;let i=crypto.randomUUID(),a=new Promise(n=>{let a=!1,o=e=>{a||(a=!0,c.current.get(t)?.promptKey===i&&c.current.delete(t),s.current.get(t)?.promptKey===i&&s.current.delete(t),r(e=>e.filter(e=>e.key!==i)),n(e))};c.current.set(t,{promptKey:i,refuse:()=>{o(!1)}}),r(t=>[...t,{key:i,assessment:e,decide:o}])});return s.current.set(t,{promptKey:i,decision:a}),a},[]);return{prompts:n,changes:i,memory:o,confirmAddress:(0,k.useCallback)(async t=>{let n=HP(t);if(n===void 0)return t;let r=VP(n.node,n.sha256.map(e=>uO(e)),(await e.recall(n.node)).map(e=>uO(e)));if(r.kind===`known`)return Y_(t,n.sha256.filter(e=>r.trusted.includes(uO(e))));if(await l(r))return await e.remember(n.node,n.sha256),t},[e,l]),dismissChange:(0,k.useCallback)(e=>{a(t=>t.map(t=>t.key===e?{...t,dismissed:!0}:t))},[])}}function EF({store:e,children:t}){let[n,r]=(0,k.useState)(new Map),[i,a]=(0,k.useState)(new Map),[o,s]=(0,k.useState)(void 0),[c,l]=(0,k.useState)(void 0),u=(0,k.useRef)(Promise.resolve()),d=(0,k.useCallback)(async e=>{u.current=u.current.then(async()=>{try{await e(),l(void 0)}catch(e){l(e instanceof Error?e.message:String(e))}}),await u.current},[]);(0,k.useEffect)(()=>{Promise.all([e.petnames(),e.selfName()]).then(([e,t])=>{r(e),s(t)},e=>{l(e instanceof Error?e.message:String(e))})},[e]);let f=(0,k.useCallback)(async(t,n)=>d(async()=>{await e.setPetname(t,n),r(await e.petnames())}),[e,d]),p=(0,k.useCallback)(async t=>d(async()=>{await e.setSelfName(t),s(await e.selfName())}),[e,d]),m=(0,k.useCallback)(e=>{a(t=>{let n;for(let r of e){let e=Aj(r.advert),i=dO(r.device);t.get(i)!==e&&(n??=new Map(t),e===void 0?n.delete(i):n.set(i,e))}return n??t})},[]),h=(0,k.useMemo)(()=>new Set(n.values()),[n]),g=(0,k.useMemo)(()=>({labelOf:e=>Mj(e,n.get(e),i.get(e),h),petnameOf:e=>n.get(e),rename:f,selfName:o,setSelfName:p,observeDirectory:m}),[n,h,i,o,f,p,m]);return(0,z.jsxs)(OP.Provider,{value:g,children:[c!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Saved names are unavailable`,mb:`md`,children:c}),t]})}function DF(){let{selfName:e,setSelfName:t}=kP(),[n,r]=(0,k.useState)(void 0),i=n??e??``;return(0,z.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),t(i).then(()=>{r(void 0)})},children:(0,z.jsxs)(pl,{align:`flex-end`,wrap:`wrap`,children:[(0,z.jsx)(Am,{label:`Your display name`,description:`Shown to the peers you connect to, signed by this device's key. Leave empty to show only your short id.`,value:i,maxLength:64,onChange:e=>{r(e.currentTarget.value)},style:{flex:1,minWidth:`16rem`}}),(0,z.jsx)(Ed,{type:`submit`,variant:`light`,disabled:(kj(i)??``)===(e??``),children:`Save name`})]})})}function OF({onDismiss:e}){return(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,"data-testid":`onboarding-intro`,children:[(0,z.jsx)(Lm,{order:2,size:`h4`,mb:`xs`,children:`Welcome to the wire-mesh console`}),(0,z.jsxs)(vf,{type:`ordered`,spacing:`xs`,size:`sm`,children:[(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Connect.`}),` `,`Enter a node's address in the Node field and press Connect. A console served by a node starts with that node's address filled in, so there is usually nothing to type. The status line shows the connection coming up.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`See who is here.`}),` `,`Once connected, the node's peer directory lists the devices it knows. Message opens a conversation with one. Devices appear under the name they chose for themselves, or a short id; use the pencil beside a device to give it a name of your own, which only this console keeps.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Discovered peers wait for you.`}),` `,`A node you are connected to can tell you about other nodes. Nothing vouches for those addresses except the node that listed them, and one may not be a wire-mesh node at all, so the console never dials one by itself. Each waits in the Discovered peers list until you press Connect or dismiss it.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Offline.`}),` `,`The console itself loads without a network, and conversations are kept on this device, so history stays readable. Sending needs a route to the peer, through a node or directly; a message that could not be sent stays with its reason until you retry or dismiss it.`]})]}),(0,z.jsx)(Ed,{mt:`md`,size:`xs`,onClick:e,children:`Got it`})]})}function kF(e,t){return e.sentAt===t.sentAt?uO(e.messageId).localeCompare(uO(t.messageId)):e.sentAt-t.sentAt}function AF(e,t){let n=new Set(e.map(e=>uO(e.messageId))),r=t.filter(e=>!n.has(uO(e.messageId)));return r.length===0?e:[...e,...r].sort(kF)}function jF(e,t,n){let r=e.get(t);return r===void 0?e:new Map(e).set(t,n(r))}function MF(e,t){return{roomPath:e,participants:t,direct:void 0,relay:void 0,via:void 0,token:void 0,status:`closed`,messages:[],notices:[],outgoing:[],pendingJoinRequest:void 0,unread:0}}function NF(e,t,n){let r=t===void 0?n===void 0?void 0:`hub`:`direct`;return{...e,direct:t,relay:n,via:r,status:r===void 0?`closed`:`connected`}}function PF(e,t){switch(t.type){case`direct-opened`:{let n=e.get(t.roomPath)??MF(t.roomPath,t.participants);return new Map(e).set(t.roomPath,{...NF(n,t.session,n.relay),participants:t.participants,notices:[]})}case`relay-opened`:{let n=e.get(t.roomPath)??MF(t.roomPath,t.participants);return new Map(e).set(t.roomPath,NF(n,n.direct,t.route))}case`direct-closed`:return jF(e,t.roomPath,e=>NF(e,void 0,e.relay));case`hub-closed`:{let n=e;for(let r of e.values())r.relay?.hub===t.hub&&(n=jF(n,r.roomPath,e=>NF(e,e.direct,void 0)));return n}case`restored`:return e.get(t.roomPath)===void 0?new Map(e).set(t.roomPath,{...MF(t.roomPath,t.participants),messages:AF([],t.messages)}):jF(e,t.roomPath,e=>({...e,messages:AF(e.messages,t.messages)}));case`notices`:return jF(e,t.roomPath,e=>({...e,notices:t.notices}));case`message`:return jF(e,t.roomPath,e=>{let n=AF(e.messages,[t.message]),r=n!==e.messages;return{...e,messages:n,unread:r&&t.message.direction===`received`?e.unread+1:e.unread}});case`read`:return jF(e,t.roomPath,e=>e.unread===0?e:{...e,unread:0});case`outgoing`:return jF(e,t.roomPath,e=>({...e,outgoing:e.outgoing.some(e=>e.localId===t.entry.localId)?e.outgoing.map(e=>e.localId===t.entry.localId?t.entry:e):[...e.outgoing,t.entry]}));case`outgoing-removed`:return jF(e,t.roomPath,e=>({...e,outgoing:e.outgoing.filter(e=>e.localId!==t.localId)}));case`join-request`:return jF(e,t.roomPath,e=>({...e,pendingJoinRequest:t.request}));case`join-request-settled`:return jF(e,t.roomPath,e=>({...e,pendingJoinRequest:void 0}));case`token`:return jF(e,t.roomPath,e=>({...e,token:t.token}))}return e}function FF(e,t){let n=pN(e);return n.kind===`dm`?n.participants.filter(e=>e!==t):n.owner===t?[]:[n.owner]}function IF(e,t){return e.participants.length===0?e.roomPath:e.participants.map(e=>Nj(t.labelOf(e))).join(`, `)}function LF(e){return e.toLowerCase().split(/\s+/).filter(e=>e!==``)}function RF(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e))}function zF(e,t){let n=LF(t);if(n.length===0)return[];let r=new TextDecoder,i=[];for(let t of e)t.messages.forEach((e,r)=>{RF(e.text,n)&&i.push({key:`${t.roomPath}/message/${String(r)}`,roomPath:t.roomPath,kind:`message`,text:e.text,at:e.sentAt,direction:e.direction})}),t.notices.forEach((e,a)=>{if(e.plaintext===void 0||e.claims===void 0)return;let o=r.decode(e.plaintext);RF(o,n)&&i.push({key:`${t.roomPath}/notice/${String(a)}`,roomPath:t.roomPath,kind:`notice`,text:o,at:e.claims[`posted-at`],direction:void 0})});return i.sort((e,t)=>t.at-e.at).slice(0,50)}function BF({conversations:e,onSelect:t}){let n=kP(),[r,i]=(0,k.useState)(``);if(e.length===0)return null;let a=zF(e,r),o=LF(r).length>0,s=new Map(e.map(e=>[e.roomPath,e]));return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`search-panel`,children:[(0,z.jsx)(Am,{type:`search`,label:`Search conversations and notices`,value:r,onChange:e=>{i(e.currentTarget.value)}}),o&&a.length===0&&(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Nothing matches.`}),a.map(e=>{let i=s.get(e.roomPath);return(0,z.jsx)(Sf,{label:(0,z.jsx)(nf,{highlight:LF(r),size:`sm`,children:e.text}),description:(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(_d,{size:`xs`,variant:`light`,children:e.kind}),(0,z.jsxs)(U,{size:`xs`,c:`dimmed`,children:[i===void 0?e.roomPath:IF(i,n),` · `,new Date(e.at).toLocaleString()]})]}),onClick:()=>{t(e.roomPath)}},e.key)})]})}var VF=16;function HF(){let e=new Uint8Array(VF);return crypto.getRandomValues(e),e}function UF(e){typeof e==`object`&&e&&`unref`in e&&typeof e.unref==`function`&&Reflect.apply(e.unref,e,[])}function WF(e,t){return{verb:e,params:{verb:`capability.request`,capability:e,...t===void 0?{}:{"valid-until":t}}}}var GF=class extends Error{capability;code;constructor(e,t){super(`capability request for "${e}" was refused (${t})`),this.name=`CapabilityRequestRefusedError`,this.capability=e,this.code=t}};async function KF(e,t,n,r,i,a,o){let s=await e.sendManageRequest(WF(t,a),n,r,o,i);if(s.result!==`ok`)throw new GF(t,s.code);let c=qE.safeParse(s);if(!c.success)throw Error(`capability request for "${t}" response was malformed`);return c.data}var qF=`manage:request`;async function JF(e,t){if(e.token===void 0)return{ok:!1,code:`token_required`};if(t.revocation===void 0)throw Error(`requireRequestToken needs a revocation view on the handler options`);let n=await JA(e.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.bearerDevice,...t.extraPredicateResolvers===void 0?{}:{extraPredicateResolvers:t.extraPredicateResolvers}});if(!n.ok)return{ok:!1,code:n.reason};if(n.claims.capability!==`manage:request`)return{ok:!1,code:`capability_mismatch`};let r=n.claims[`requests-capability`];return r!==void 0&&r!==t.capability?{ok:!1,code:`capability_mismatch`}:NO(n.claims.scope,e.scope)?{ok:!0}:{ok:!1,code:`scope_mismatch`}}function YF(e){return async function(t){let n=KE.safeParse(t.command.params);if(!n.success||n.data.capability!==e.capability){await t.respond({result:`error`,code:`malformed`});return}let r=n.data;if(e.requireRequestToken===!0){let n=await JF(t,e);if(!n.ok){await t.respond({result:`error`,code:n.code});return}}let i=r[`valid-until`];if(i!==void 0&&i<=e.clock.now()){await t.respond({result:`error`,code:`expired`});return}let a=!1,o=setTimeout(()=>{a||(a=!0,t.respond({result:`error`,code:`timeout`,message:`no decision within the capability-request timeout`}).catch(()=>void 0))},e.timeoutMs);UF(o),e.onRequest({scope:t.scope,requesterDevice:e.bearerDevice,async decide(n){if(a)return;if(a=!0,clearTimeout(o),n.kind===`reject`){await t.respond({result:`error`,code:`denied`,...n.reason===void 0?{}:{message:n.reason}});return}let r=await tj({identity:e.identity,clock:e.clock,tokenId:HF(),bearer:e.bearerDevice,capability:n.capability,scope:t.scope,expires:n.expires,...n.delegationsRemaining===void 0?{}:{delegationsRemaining:n.delegationsRemaining}});if(!r.ok){await t.respond({result:`error`,code:`mint_failed`});return}let i=r.token;await t.respond({result:`ok`,"granted-token":i,...n.extensions??{}})}})}}var XF=16,ZF=36e5,QF=[{verb:`room:member`,scopeKind:`room`},{verb:`room:join`,scopeKind:`room`},{verb:`room:invite`,scopeKind:`room`},{verb:`webrtc:signal`,scopeKind:`node`},{verb:`relay:use`,scopeKind:`node`},{verb:`pin:write`,scopeKind:`folder`},{verb:`exec:pty`,scopeKind:`folder`},{verb:`exec:proc`,scopeKind:`folder`},{verb:`group:member`,scopeKind:`group`},{verb:VA,scopeKind:`folder`},{verb:qF,scopeKind:`room`}],$F={[VA]:`grantsCapability`,[qF]:`requestsCapability`},eI={already_expired:`the grant would already have expired`,parent_malformed:`the grant it delegates from is malformed`,parent_bearer_mismatch:`the grant it delegates from is not held by this device`,expires_exceeds_parent:`it would outlast the grant it delegates from`,scope_does_not_narrow:`its scope is wider than the grant it delegates from`,capability_mismatch:`its capability differs from the grant it delegates from`,delegation_exceeds_parent:`it permits more delegation than its parent does`,links_exclusive:`it would carry both a parent grant and an authorising grant`,authorisation_malformed:`the grant authorising it is malformed`,authorisation_parent_forbidden:`a grant permission cannot be delegated from a parent grant`,authorisation_bearer_mismatch:`the grant authorising it is not held by this device`,authorisation_capability_mismatch:`the grant authorising it names a different capability`,authorisation_scope_does_not_narrow:`its scope is wider than the grant authorising it`,authorisation_exceeds_authoriser:`it would outlast the grant authorising it`,authorisation_delegation_exceeds:`it permits more delegation than the grant authorising it does`,authorisation_conditions_not_satisfied:`the grant authorising it does not allow this mint`};function tI(e,t){let n=(t??``).trim();if(n===``)return{ok:!0};let r=$F[e];if(r===void 0)return{ok:!1,error:`only ${VA} and ${qF} name a verb they cover`};let i=AD.safeParse(n);return i.success?{ok:!0,claim:r,verb:i.data}:{ok:!1,error:`the covered verb must look like subsystem:action, for example room:member`}}function nI(){let e=new Uint8Array(XF);return crypto.getRandomValues(e),e}async function rI(e,t){let n;try{n=pO(e.bearerHex.trim().toLowerCase())}catch{return{ok:!1,error:`the bearer must be a 64-character hex device-id`}}let r=AD.safeParse(e.capability.trim());if(!r.success)return{ok:!1,error:`the capability must look like subsystem:action, for example room:member`};if(e.scopeKind.trim()===``)return{ok:!1,error:`the scope needs a kind, for example room`};if(!Number.isFinite(e.lifetimeHours)||e.lifetimeHours<=0)return{ok:!1,error:`the lifetime must be more than zero hours`};if(e.delegationsRemaining!==void 0&&!(Number.isSafeInteger(e.delegationsRemaining)&&e.delegationsRemaining>=0))return{ok:!1,error:`further delegations must be a whole number, zero or more`};let i=tI(r.data,e.targetVerb);if(!i.ok)return i;let a=e.selfGrantBars??[];if(a.length>0&&r.data!==`manage:grant`)return{ok:!1,error:`only a ${VA} can bar its holder from granting to itself`};let o=[];for(let e of a){let t=AD.safeParse(e.trim());if(!t.success)return{ok:!1,error:`the barred verb "${e}" must look like subsystem:action`};o.push(MA(t.data,n))}let s=e.scopePath.trim(),c=await tj({identity:t.identity,clock:t.clock,tokenId:nI(),bearer:n,capability:r.data,scope:{kind:e.scopeKind.trim(),...s===``?{}:{path:s}},expires:Math.round(t.clock.now()+e.lifetimeHours*ZF),...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining},...e.parent===void 0?{}:{parent:e.parent},...e.authorisedBy===void 0?{}:{authorisedBy:e.authorisedBy},...i.claim===void 0||i.verb===void 0?{}:{[i.claim]:i.verb},...o.length===0?{}:{conditions:o}});return c.ok?{ok:!0,token:c.token}:{ok:!1,error:`refused: ${eI[c.reason]}`}}var iI=3e4;function aI(e){let{identity:t,clock:n,grants:r,revocations:i,announce:a}=e,[o,s]=(0,k.useState)([]),[c,l]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{let e={cancelled:!1,latestLoad:0},a=async()=>{e.latestLoad+=1;let a=e.latestLoad,o=await r.list(),c=await Promise.all(o.map(async e=>({...e,status:await lj(e.token,{identity:t,clock:n,revocation:i.view,...e.direction===`held`?{expectedBearer:t.deviceId}:{}})})));!e.cancelled&&a===e.latestLoad&&(s(c),l(void 0))},o=()=>{a().catch(t=>{e.cancelled||l(t instanceof Error?t.message:String(t))})};o();let c=[r.subscribe(o),i.subscribe(o)],u=setInterval(o,iI);return()=>{e.cancelled=!0,clearInterval(u);for(let e of c)e()}},[t,n,r,i]);let u=(0,k.useCallback)(async e=>{let i=await rI(e,{identity:t,clock:n});return i.ok?(await r.record(`issued`,i.token,n.now()),{ok:!0,code:sj(i.token)}):i},[t,n,r]),d=(0,k.useCallback)(async e=>{let a;try{a=cj(e)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let o=await lj(a,{identity:t,clock:n,revocation:i.view,expectedBearer:t.deviceId});return o.kind===`invalid`?{ok:!1,error:`this device cannot hold that grant: ${dj(o)}`}:(await r.record(`held`,a,n.now()),{ok:!0})},[t,n,r,i]),f=(0,k.useCallback)(async e=>{try{let t=await i.revoke(e.claims[`token-id`]);return{ok:!0,announced:await a(t)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},[i,a]);return(0,k.useMemo)(()=>({rows:o,loadError:c,mint:u,importCode:d,revoke:f}),[o,c,u,d,f])}function oI({label:e,children:t}){return(0,z.jsxs)(U,{size:`sm`,children:[(0,z.jsxs)(U,{span:!0,fw:600,children:[e,`:`]}),` `,t]})}function sI({row:e}){let{claims:t}=e,n=sj(e.token);return(0,z.jsxs)(rm,{gap:4,"data-testid":`grant-details`,children:[(0,z.jsx)(oI,{label:`Token id`,children:(0,z.jsx)(Ld,{children:e.tokenId})}),(0,z.jsx)(oI,{label:`Issuer`,children:(0,z.jsx)(YP,{deviceHex:dO(t.issuer)})}),(0,z.jsx)(oI,{label:`Bearer`,children:(0,z.jsx)(YP,{deviceHex:dO(t.bearer)})}),(0,z.jsxs)(oI,{label:`Allows`,children:[t.capability,` over `,t.scope.kind,t.scope.path===void 0?``:` ${t.scope.path}`]}),(0,z.jsx)(oI,{label:`Expires`,children:new Date(t.expires).toISOString()}),t[`not-before`]!==void 0&&(0,z.jsx)(oI,{label:`Not before`,children:new Date(t[`not-before`]).toISOString()}),t[`delegations-remaining`]!==void 0&&(0,z.jsx)(oI,{label:`Further delegations`,children:t[`delegations-remaining`]}),t.parent!==void 0&&(0,z.jsx)(oI,{label:`Delegated from`,children:`another grant (its parent rides inside this one)`}),(0,z.jsx)(oI,{label:`Status`,children:dj(e.status)}),(0,z.jsx)(df,{readOnly:!0,label:`Grant code`,description:`Paste this into the other device's grant import to give it this grant.`,value:n,autosize:!0,minRows:2,maxRows:4}),(0,z.jsx)(zd,{value:n,children:({copied:e,copy:t})=>(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:t,w:`fit-content`,children:e?`Copied`:`Copy grant code`})})]})}function cI(e,t){return e>t?zP(e-t):RP(t-e)}function lI({title:e,rows:t,other:n,now:r,onRevoke:i}){let[a,o]=(0,k.useState)(void 0),[s,c]=(0,k.useState)(void 0);return(0,z.jsxs)(`div`,{"data-testid":`grants-${e.toLowerCase()}`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`sm`,children:e}),t.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`None.`}):(0,z.jsx)(dF,{columns:[{label:`capability`},{label:`over`},{label:n===`issuer`?`from`:`to`},{label:`expires`},{label:`status`},{label:`actions`,headerless:!0}],rows:t.map(e=>({key:`${e.direction}/${e.tokenId}`,cells:[e.claims.capability,`${e.claims.scope.kind}${e.claims.scope.path===void 0?``:` ${e.claims.scope.path}`}`,(0,z.jsx)(cF,{deviceHex:dO(e.claims[n])},`other`),cI(e.claims.expires,r),(0,z.jsx)(_d,{color:e.status.kind===`valid`?`green`:`red`,variant:`light`,children:dj(e.status)},`status`),(0,z.jsxs)(k.Fragment,{children:[(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o(a===e.tokenId?void 0:e.tokenId)},children:a===e.tokenId?`Hide`:`Inspect`}),i!==void 0&&e.status.kind===`valid`&&(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:s===e.tokenId?`filled`:`light`,onClick:()=>{s===e.tokenId?(c(void 0),i(e)):c(e.tokenId)},children:s===e.tokenId?`Confirm: revoke for good`:`Revoke`})]}),a===e.tokenId&&(0,z.jsx)(sI,{row:e})]},`actions`)]}))})]})}function uI({onImport:e}){let[t,n]=(0,k.useState)(``),[r,i]=(0,k.useState)(void 0);return(0,z.jsx)(`form`,{onSubmit:r=>{r.preventDefault(),e(t).then(e=>{i(e),e.ok&&n(``)})},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Add a grant you were given`}),(0,z.jsx)(df,{label:`Grant code`,value:t,onChange:e=>{n(e.currentTarget.value)},autosize:!0,minRows:2,maxRows:4,required:!0}),(0,z.jsx)(Ed,{type:`submit`,size:`xs`,w:`fit-content`,children:`Add grant`}),r?.ok===!1&&(0,z.jsx)(eu,{color:`red`,title:`Not added`,children:r.error}),r?.ok===!0&&(0,z.jsx)(eu,{color:`green`,title:`Grant added`,children:`It is listed under Held.`})]})})}var dI=24,fI=`root`,pI=`none`;function mI(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}function hI({delegable:e,onMint:t}){let[n,r]=(0,k.useState)(``),[i,a]=(0,k.useState)(``),[o,s]=(0,k.useState)(``),[c,l]=(0,k.useState)(``),[u,d]=(0,k.useState)(dI),[f,p]=(0,k.useState)(``),[m,h]=(0,k.useState)(fI),[g,_]=(0,k.useState)(pI),[v,y]=(0,k.useState)(``),[b,x]=(0,k.useState)(``),[S,C]=(0,k.useState)(void 0),w=e.find(e=>e.tokenId===m),T=e.find(e=>e.tokenId===g),E=e.filter(e=>e.claims.capability===VA),D=i===`manage:grant`||i===`manage:request`;function O(){if(m!==fI&&w===void 0){C({ok:!1,error:`the grant you chose to delegate from is no longer valid; choose another, or choose Root grant to mint without one`});return}if(g!==pI&&T===void 0){C({ok:!1,error:`the grant you chose to authorise this is no longer valid; choose another, or choose None to mint without one`});return}t({bearerHex:n,capability:i,scopeKind:o,scopePath:c,lifetimeHours:u,delegationsRemaining:f===``?void 0:f,parent:w?.token,authorisedBy:T?.token,targetVerb:D?v:``,selfGrantBars:i===`manage:grant`?mI(b):[]}).then(C,e=>{C({ok:!1,error:e instanceof Error?e.message:String(e)})})}return(0,z.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),O()},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Mint a grant`}),(0,z.jsx)(Am,{label:`Bearer device-id`,description:`The device the grant is for: 64 hex characters, copied from a peer's directory row.`,value:n,onChange:e=>{r(e.currentTarget.value)},required:!0}),(0,z.jsx)(md,{label:`Capability`,description:`What it allows, as subsystem:action.`,data:QF.map(e=>e.verb),value:i,onChange:e=>{a(e);let t=QF.find(t=>t.verb===e);t!==void 0&&s(t.scopeKind)},required:!0}),(0,z.jsx)(Am,{label:`Scope kind`,value:o,onChange:e=>{s(e.currentTarget.value)},required:!0}),(0,z.jsx)(Am,{label:`Scope path`,description:`Leave empty for a scope with no path.`,value:c,onChange:e=>{l(e.currentTarget.value)}}),D&&(0,z.jsx)(Am,{label:`Covered verb`,description:i===`manage:grant`?`The one verb the holder may grant, as subsystem:action. Empty means any verb within the scope.`:`The one verb the holder may request, as subsystem:action. Empty means any verb within the scope.`,value:v,onChange:e=>{y(e.currentTarget.value)}}),i===`manage:grant`&&(0,z.jsx)(Am,{label:`Barred from granting to itself`,description:`Comma-separated verbs the holder may not grant to its own device, for example manage:grant to stop it passing on the right to grant.`,value:b,onChange:e=>{x(e.currentTarget.value)}}),(0,z.jsx)(Lp,{label:`Lasts (hours)`,min:0,value:u,onChange:e=>{d(typeof e==`number`?e:0)}}),(0,z.jsx)(Lp,{label:`Further delegations`,description:`How many times the bearer may pass it on. Empty leaves it unset.`,min:0,allowDecimal:!1,value:f,onChange:e=>{p(typeof e==`number`?e:``)}}),(0,z.jsx)($p,{label:`Delegate from`,description:`A grant you hold, which the new grant may only narrow. Root means none.`,allowDeselect:!1,data:[{value:fI,label:`Root grant (none)`},...e.map(e=>({value:e.tokenId,label:`${e.claims.capability} from ${Dj(dO(e.claims.issuer))}`}))],value:m,onChange:e=>{h(e??fI)}}),(0,z.jsx)($p,{label:`Authorised by`,description:`A manage:grant you hold that permits this mint; it may bar what you can grant. None means this grant is minted on your own authority.`,allowDeselect:!1,data:[{value:pI,label:`None`},...E.map(e=>({value:e.tokenId,label:`manage:grant from ${Dj(dO(e.claims.issuer))}`}))],value:g,onChange:e=>{_(e??pI)}}),(0,z.jsx)(Ed,{type:`submit`,size:`xs`,w:`fit-content`,children:`Mint grant`}),S?.ok===!1&&(0,z.jsx)(eu,{color:`red`,title:`Not minted`,children:S.error}),S?.ok===!0&&(0,z.jsx)(eu,{color:`green`,title:`Grant minted`,children:`It is listed under Issued, where Inspect shows its grant code.`})]})})}var gI=1e3;function _I(e){if(!e.ok)return{color:`red`,title:`Not revoked`,text:e.error};let{attempted:t,reached:n}=e.announced;return t===0?{color:`yellow`,title:`Revoked here only`,text:`No connection was open, so no node was told. This console no longer honours the grant.`}:n<t?{color:`yellow`,title:`Revoked, but not every node was told`,text:`Sent to ${String(n)} of ${String(t)} connected nodes. This console no longer honours the grant.`}:{color:`green`,title:`Revoked`,text:`Sent to ${String(n)} connected ${n===1?`node`:`nodes`}. This console no longer honours the grant.`}}function vI({grants:e,clock:t}){let n=MP(t,!0,gI),[r,i]=(0,k.useState)(void 0),a=r===void 0?void 0:_I(r),o=e.rows.filter(e=>e.direction===`held`),s=e.rows.filter(e=>e.direction===`issued`);return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`grants-panel`,children:[(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`A grant is a signed statement that one device may do something over something until a time. Revoking one you issued is recorded here, where this console stops honouring it at once, and sent to the nodes you are connected to. A node only passes it on if it relays revocations, which the hub does not.`}),e.loadError!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Grants could not be read`,children:e.loadError}),(0,z.jsx)(lI,{title:`Held`,rows:o,other:`issuer`,now:n}),(0,z.jsx)(lI,{title:`Issued`,rows:s,other:`bearer`,now:n,onRevoke:t=>{e.revoke(t).then(i,e=>{i({ok:!1,error:e instanceof Error?e.message:String(e)})})}}),a!==void 0&&(0,z.jsx)(eu,{color:a.color,title:a.title,"data-testid":`revocation-report`,children:a.text}),(0,z.jsx)(hI,{delegable:o.filter(e=>e.status.kind===`valid`),onMint:e.mint}),(0,z.jsx)(uI,{onImport:e.importCode})]})}var yI=6e4;function bI(e,t){let n=URL.createObjectURL(new Blob([t],{type:`application/json`})),r=document.createElement(`a`);r.href=n,r.download=e,r.hidden=!0,document.body.append(r),r.click(),r.remove(),setTimeout(()=>{URL.revokeObjectURL(n)},yI)}var xI=`wire-mesh-console-identity.json`,SI=2;function CI(){location.reload()}function wI({identity:e,backup:t,save:n=bI,reload:r=CI}){let i=dO(e.deviceId),[a,o]=(0,k.useState)({kind:`idle`}),[s,c]=(0,k.useState)(!1);async function l(){try{n(xI,JSON.stringify(await t.export(),void 0,SI)),o({kind:`exported`})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}async function u(e){try{await t.restore(e),o({kind:`restored`})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}async function d(e){if(e!==null)try{o({kind:`confirm-restore`,backup:await OO(await e.text())})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`identity-panel`,children:[(0,z.jsxs)(U,{size:`sm`,children:[`This device is `,(0,z.jsx)(Ld,{"data-testid":`own-device-id`,children:i}),` `,(0,z.jsx)(zd,{value:i,children:({copied:e,copy:t})=>(0,z.jsx)(Ed,{size:`compact-xs`,variant:`subtle`,onClick:t,children:e?`Copied`:`Copy device id`})})]}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Its key is ES256 (P-256) and lives in this browser. If this browser's storage is cleared or the device is lost, the identity is gone, along with every grant made to it. A backup file lets you keep it.`}),a.kind===`confirm-export`&&(0,z.jsx)(eu,{color:`orange`,title:`This file holds your private key`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`Anyone who has it can act as this device. Save it somewhere private, and do not send it to anyone. The console does not show the key or keep a copy of the file.`}),(0,z.jsx)(od,{label:`I understand, and I want a backup file`,checked:s,onChange:e=>{c(e.currentTarget.checked)}}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:`orange`,disabled:!s,onClick:()=>{l()},children:`Save backup file`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o({kind:`idle`})},children:`Cancel`})]})]})}),a.kind===`exported`&&(0,z.jsxs)(eu,{color:`green`,title:`Backup file handed to your browser`,children:[(0,z.jsx)(U,{size:`sm`,children:`The browser was asked to save it, and may have asked where. Check that the file is there before you rely on it.`}),(0,z.jsx)(U,{size:`sm`,children:`Keep it private. Restoring it on another browser makes that browser this device.`})]}),a.kind===`confirm-restore`&&(0,z.jsx)(eu,{color:`red`,title:`Replace this device's identity?`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsxs)(U,{size:`sm`,children:[`This device is now `,(0,z.jsx)(Ld,{children:i}),`. The backup is`,` `,(0,z.jsx)(Ld,{children:a.backup.deviceId}),`. Restoring makes this browser the backup's device the next time the console loads, and this identity, with the grants made to it, is gone unless you have a backup of it.`]}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:`red`,onClick:()=>{u(a.backup)},children:`Replace this identity`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o({kind:`idle`})},children:`Cancel`})]})]})}),a.kind===`restored`&&(0,z.jsx)(eu,{color:`green`,title:`Identity restored`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`Reload the console to run as the restored identity.`}),(0,z.jsx)(Ed,{size:`xs`,w:`fit-content`,onClick:r,children:`Reload now`})]})}),a.kind===`error`&&(0,z.jsx)(eu,{color:`red`,title:`That did not work`,children:a.message}),(a.kind===`idle`||a.kind===`exported`||a.kind===`error`)&&(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{c(!1),o({kind:`confirm-export`})},children:`Back up this identity`}),(0,z.jsx)(Wd,{accept:`application/json,.json`,onChange:e=>{d(e)},children:e=>(0,z.jsx)(Ed,{size:`xs`,variant:`light`,color:`red`,...e,children:`Restore from a backup file`})})]})]})}function TI({identity:e,clock:t,grants:n,revocations:r,identityBackup:i,announceRevocation:a}){let o=aI({identity:e,clock:t,grants:n,revocations:r,announce:a});return(0,z.jsxs)(Zl,{multiple:!0,variant:`contained`,"data-testid":`identity-section`,children:[(0,z.jsxs)(Zl.Item,{value:`identity`,children:[(0,z.jsx)(Zl.Control,{children:`Identity`}),(0,z.jsx)(Zl.Panel,{children:(0,z.jsx)(wI,{identity:e,backup:i})})]}),(0,z.jsxs)(Zl.Item,{value:`grants`,children:[(0,z.jsx)(Zl.Control,{children:`Grants`}),(0,z.jsx)(Zl.Panel,{children:(0,z.jsx)(vI,{grants:o,clock:t})})]})]})}function EI({revocations:e,onFailure:t}){let n=(0,k.useSyncExternalStore)(e.subscribe,e.unreadable);return n.length===0?null:(0,z.jsx)(eu,{color:`red`,title:`Some stored revocations could not be loaded`,"data-testid":`unreadable-revocations`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`A grant that one of these revoked may read as valid until it is dealt with. Discarding an entry deletes it from this console's storage.`}),n.map(n=>(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsxs)(U,{size:`sm`,children:[n.key,`: `,n.reason]}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:()=>{e.discardUnreadable(n.key).catch(e=>{t(e instanceof Error?e.message:String(e))})},children:`Discard`})]},n.key))]})})}function DI(e){return e instanceof Error?e.message:String(e)}function OI(e){let[t,n]=(0,k.useState)(void 0),[r,i]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{e.introDismissed().then(n,e=>{n(!1),i(DI(e))})},[e]);let a=(0,k.useCallback)(t=>{n(t),e.setIntroDismissed(t).then(()=>{i(void 0)},e=>{i(DI(e))})},[e]),o=(0,k.useCallback)(()=>{a(!0)},[a]),s=(0,k.useCallback)(()=>{a(!1)},[a]);return{visible:t===!1,ready:t!==void 0,error:r,dismiss:o,show:s}}function kI({conversations:e,selected:t,onSelect:n}){let r=kP();return e.length===0?null:(0,z.jsxs)(rm,{gap:0,"data-testid":`conversation-list`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mb:`xs`,children:`Conversations`}),e.map(e=>(0,z.jsx)(Sf,{active:e.roomPath===t,label:IF(e,r),description:e.status===`connected`?void 0:`offline`,rightSection:(0,z.jsxs)(pl,{gap:4,wrap:`nowrap`,children:[e.pendingJoinRequest!==void 0&&(0,z.jsx)(_d,{color:`blue`,size:`sm`,children:`request`}),e.unread>0&&(0,z.jsx)(_d,{size:`sm`,"aria-label":`${String(e.unread)} unread`,children:e.unread})]}),onClick:()=>{n(e.roomPath)}},e.roomPath))]})}function AI({placeholder:e,ariaLabel:t,submitLabel:n,onSubmit:r,onCancel:i,size:a,autoFocus:o}){let[s,c]=(0,k.useState)(``),[l,u]=(0,k.useState)(void 0);function d(){let e=s.trim();e!==``&&(u(void 0),Promise.resolve(r(e)).then(()=>{c(``)}).catch(e=>{u(e instanceof Error?e.message:String(e))}))}function f(e){e.key===`Enter`&&d(),e.key===`Escape`&&i?.()}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(pl,{gap:`xs`,flex:1,children:[(0,z.jsx)(Am,{flex:1,...a===void 0?{}:{size:a},placeholder:e,"aria-label":t,autoComplete:`off`,autoFocus:o,value:s,onChange:e=>{c(e.currentTarget.value)},onKeyDown:f}),(0,z.jsx)(Ed,{...a===void 0?{}:{size:a},onClick:d,children:n})]}),l!==void 0&&(0,z.jsx)(U,{size:`sm`,c:`red`,children:l})]})}var jI=`You`,MI=256,NI=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`});function PI({sentAt:e}){return(0,z.jsx)(U,{component:`time`,size:`xs`,c:`dimmed`,dateTime:new Date(e).toISOString(),children:NI.format(e)})}function FI({messages:e,outgoing:t,peerLabel:n,onRetry:r,onDiscard:i}){let a=(0,k.useRef)(null);return(0,k.useEffect)(()=>{let e=a.current;e!==null&&(e.scrollTop=e.scrollHeight)},[e,t]),(0,z.jsx)(Gs,{h:MI,viewportRef:a,children:(0,z.jsxs)(rm,{gap:4,children:[e.map((t,r)=>{let i=t.direction===`sent`,a=r===0||e[r-1]?.direction!==t.direction;return(0,z.jsxs)(rm,{gap:0,align:i?`flex-end`:`flex-start`,mt:a?`xs`:0,children:[a&&(0,z.jsx)(U,{size:`xs`,fw:600,c:`dimmed`,children:i?jI:n}),(0,z.jsx)(U,{size:`sm`,children:t.text}),(0,z.jsx)(PI,{sentAt:t.sentAt})]},uO(t.messageId))}),t.map(e=>(0,z.jsxs)(rm,{gap:0,align:`flex-end`,mt:`xs`,children:[(0,z.jsx)(U,{size:`xs`,fw:600,c:`dimmed`,children:jI}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:e.text}),e.status===`failed`?(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(U,{size:`xs`,c:`red`,children:`Not sent: ${e.error}`}),(0,z.jsx)(Ed,{size:`compact-xs`,variant:`light`,onClick:()=>{r(e.localId)},children:`Retry`}),(0,z.jsx)(Ed,{size:`compact-xs`,variant:`subtle`,color:`gray`,onClick:()=>{i(e.localId)},children:`Dismiss`})]}):(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:e.status===`awaiting-approval`?`Waiting for ${n} to allow messages`:`Sending`})]},e.localId))]})})}function II(e){if(e.plaintext!==void 0)return new TextDecoder().decode(e.plaintext)}function LI({notices:e}){if(e.length===0)return null;let t=e.map((e,t)=>{let n=II(e);return(0,z.jsx)(H,{children:n===void 0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,fs:`italic`,children:`encrypted notice -- no key held for its epoch`}):(0,z.jsx)(U,{size:`sm`,children:n})},t)});return(0,z.jsxs)(rm,{gap:4,children:[t,(0,z.jsxs)(_d,{variant:`light`,color:`gray`,size:`sm`,w:`fit-content`,children:[e.length,` notice`,e.length===1?``:`s`]})]})}var RI=864e5;function zI(e){return e===`direct`?`direct`:e===`hub`?`via hub`:`offline`}function BI({view:e,onSend:t,onPostNotice:n,onRetry:r,onDiscard:i}){let a=kP();return(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsx)(U,{fw:600,"data-testid":`conversation-header`,children:IF(e,a)}),(0,z.jsx)(U,{size:`sm`,c:e.status===`connected`?`green`:`dimmed`,children:zI(e.via)})]}),e.pendingJoinRequest&&(0,z.jsx)(eu,{color:`blue`,title:`Message request`,children:(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsxs)(U,{size:`sm`,children:[(0,z.jsx)(YP,{deviceHex:e.pendingJoinRequest.requesterHex}),` `,`wants to message you`]}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{e.pendingJoinRequest?.decide({kind:`accept`,capability:`room:member`,expires:Date.now()+RI})},children:`Allow`}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:()=>{e.pendingJoinRequest?.decide({kind:`reject`})},children:`Deny`})]})]})}),(0,z.jsx)(FI,{messages:e.messages,outgoing:e.outgoing,peerLabel:IF(e,a),onRetry:r,onDiscard:i}),(0,z.jsx)(pl,{children:(0,z.jsx)(AI,{ariaLabel:`Message`,placeholder:`Message`,submitLabel:`Send`,onSubmit:t})}),(0,z.jsx)(Ud,{label:`Durable notices (encrypted, replicated)`,labelPosition:`center`}),(0,z.jsx)(LI,{notices:e.notices}),e.via===void 0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Durable notices can be posted while the conversation is connected.`}):(0,z.jsx)(pl,{children:(0,z.jsx)(AI,{ariaLabel:`Post a durable notice`,placeholder:`Post a durable notice`,submitLabel:`Post notice`,onSubmit:n})})]})}var VI=`room:member`;async function HI(e,t){let n=await JA(e,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.expectedBearer});if(!n.ok)return n;if(n.claims.scope.kind!==`room`)return{ok:!1,reason:`wrong_scope_kind`};if(n.claims.scope.path!==t.roomPath)return{ok:!1,reason:`wrong_scope_path`};let r=pN(t.roomPath),i=dO(n.rootIssuer);if(r.kind===`owner-named`){if(i!==r.owner)return{ok:!1,reason:`wrong_chain_root`}}else if(t.dmRootPolicy===`either-participant`){if(i!==r.participants[0]&&i!==r.participants[1])return{ok:!1,reason:`wrong_chain_root`}}else if(i!==dO(t.identity.deviceId))return{ok:!1,reason:`wrong_chain_root`};return{ok:!0,claims:n.claims,rootIssuerKey:n.rootIssuerKey}}async function UI(e,t,n,r){for(let i of await e.list()){let e=i.claims;if(i.direction!==`held`||e.capability!==`manage:request`)continue;let a=e[`requests-capability`];if((a===void 0||a===n)&&NO(e.scope,r)&&(await lj(i.token,t)).kind===`valid`)return i.token}}function WI(e){if(e instanceof GF)switch(e.code){case`denied`:return`the other side denied the request`;case`token_required`:return`the other side only accepts requests that present a request permission, and this device holds none that covers this one`;case`capability_mismatch`:return`the request permission presented does not cover this capability`;case`scope_mismatch`:return`the request permission presented does not cover this conversation`;default:return`the request permission presented was refused (${e.code})`}}function GI(e){return async function(t){if(t.command.verb!==e.capability){await t.respond({result:`error`,code:`malformed`});return}let n=JE.safeParse(t.command.params);if(!n.success){await t.respond({result:`error`,code:`malformed`});return}let r=n.data[`granted-token`],i=await JA(r,{identity:e.identity,clock:e.clock,revocation:e.revocation,expectedBearer:e.identity.deviceId});if(!i.ok){await t.respond({result:`error`,code:i.reason});return}if(i.claims.capability!==e.capability){await t.respond({result:`error`,code:`capability_mismatch`});return}if(!NO(i.claims.scope,t.scope)){await t.respond({result:`error`,code:`scope_mismatch`});return}await t.respond({result:`ok`}),e.onGrant({capability:e.capability,grantedToken:r,scope:t.scope,granterDevice:e.granterDevice})}}var KI=16;function qI(){let e=new Uint8Array(KI);return crypto.getRandomValues(e),e}var JI=3e5;function YI(e,t,n){return{verb:VI,params:{verb:`room.send`,"message-id":t,"sent-at":n,text:e}}}async function XI(e,t,n,r,i){let a=YI(n,qI(),Date.now());return e.sendManageRequest(a,{kind:`room`,path:t},i,r)}async function ZI(e,t,n,r){let i;try{i=await KF(e,VI,{kind:`room`,path:t},n,void 0,void 0,r)}catch(e){let t=WI(e);throw t===void 0?e:Error(t)}let a=fD.safeParse(i);if(!a.success)throw Error(`room.join response for ${t} was malformed`);return{token:a.data[`granted-token`],members:a.data.members.map(e=>e.device)}}function QI(e,t,n){async function r(e,r){let i=e.scope.path;if(i===void 0||e.token===void 0){await e.respond({result:`error`,code:`unauthorized`});return}if(!(await HI(e.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.peerDevice,roomPath:i})).ok){await e.respond({result:`error`,code:`unauthorized`});return}await e.respond({result:`ok`});let a=r[`message-id`],o=r[`sent-at`],s=r.text;a instanceof Uint8Array&&typeof o==`number`&&typeof s==`string`&&n.onMessage?.({roomPath:i,text:s,messageId:a,sentAt:o})}function i(e){return async n=>{if(n.kind===`reject`){let t={kind:`reject`,...n.reason===void 0?{}:{reason:n.reason}};await e.decide(t);return}let r=[...t.currentMembers?.()??[],t.peerDevice].map(e=>({device:e})),i={kind:`accept`,capability:n.capability,expires:n.expires,...n.delegationsRemaining===void 0?{}:{delegationsRemaining:n.delegationsRemaining},extensions:{members:r}};await e.decide(i)}}let a=YF({capability:VI,identity:t.identity,clock:t.clock,bearerDevice:t.peerDevice,timeoutMs:t.joinRequestTimeoutMs??JI,onRequest(e){let t=e.scope.path,r=n.onJoinRequest;if(t===void 0||r===void 0){e.decide({kind:`reject`,reason:`unsupported verb`});return}r({roomPath:t,requesterDevice:e.requesterDevice,decide:i(e)})}});async function o(e){if(e.scope.path===void 0){await e.respond({result:`error`,code:`missing_scope_path`});return}if(n.onJoinRequest===void 0){await e.respond({result:`error`,code:`unsupported_verb`});return}await a({...e,respond:async t=>{if(t.result===`ok`){let e=LD.safeParse(t[`granted-token`]);e.success&&n.onGrantIssued?.(e.data)}await e.respond(t)}})}let s=GI({capability:VI,identity:t.identity,clock:t.clock,revocation:t.revocation,granterDevice:t.peerDevice,onGrant(e){let t=e.scope.path,r=n.onRoomInvite;t!==void 0&&r!==void 0&&r({roomPath:t,granterDevice:e.granterDevice,token:e.grantedToken})}});async function c(e){if(e.scope.path===void 0){await e.respond({result:`error`,code:`missing_scope_path`});return}if(n.onRoomInvite===void 0){await e.respond({result:`error`,code:`unsupported_verb`});return}await s(e)}(async()=>{for await(let t of e.incomingManageRequests){if(t.command.verb!==`room:member`)continue;let e=t.command.params;typeof e==`object`&&`verb`in e&&(e.verb===`room.send`?await r(t,e):e.verb===`capability.request`?await o(t):e.verb===`capability.grant`?await c(t):e.verb===`room.rekey`&&n.onRekey!==void 0&&await n.onRekey(t))}})()}var $I=`room-key/`,eL=`room-token/`,tL=`room-key-delivered/`,nL=String(2**53-1).length;function rL(e,t){return`${$I}${e}/${String(t).padStart(nL,`0`)}`}function iL(e){return{get:async(t,n)=>e.get(rL(t,n)),set:async(t,n,r)=>{await e.set(rL(t,n),new Uint8Array(r))},currentEpoch:async t=>{let n=(await e.keys(`${$I}${t}/`)).sort().at(-1);return n===void 0?void 0:Number(n.slice(n.lastIndexOf(`/`)+1))}}}function aL(e,t,n,r){return{get:async i=>{let a=eL+i,o=await e.get(a);if(o===void 0)return;let s=LD.safeParse(b_(o,x_));if(s.success&&(await JA(s.data,{identity:t,clock:n,revocation:r,expectedBearer:t.deviceId})).ok)return s.data;await e.delete(a)},set:async(t,n)=>{await e.set(eL+t,new Uint8Array(Mg(n,hg)))},rooms:async()=>(await e.keys(eL)).map(e=>e.slice(11))}}function oL(e){return{isDelivered:async t=>await e.get(tL+t)!==void 0,markDelivered:async t=>{await e.set(tL+t,new Uint8Array([1]))}}}var sL=32,cL=256,lL=12,uL=4,dL=8,fL=new TextEncoder().encode(`wire-mesh/room-rekey/v1\0`);function pL(){return crypto.getRandomValues(new Uint8Array(sL))}function mL(e){let t=new TextEncoder().encode(e.room),n=new Uint8Array(uL);new DataView(n.buffer).setUint32(0,t.length,!1);let r=new Uint8Array(dL);new DataView(r.buffer).setBigUint64(0,BigInt(e.keyEpoch),!1);let i=new Uint8Array(fL.length+n.length+t.length+r.length),a=0;return i.set(fL,a),a+=fL.length,i.set(n,a),a+=n.length,i.set(t,a),a+=t.length,i.set(r,a),i}async function hL(e,t){let n=await crypto.subtle.importKey(`raw`,Uint8Array.from(e),`HKDF`,!1,[`deriveKey`]);return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:Uint8Array.from(new Uint8Array),info:Uint8Array.from(mL(t))},n,{name:`AES-GCM`,length:cL},!1,[`encrypt`,`decrypt`])}async function gL(e,t){let n=crypto.getRandomValues(new Uint8Array(lL)),r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n},e,Uint8Array.from(t))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}async function _L(e,t){if(t.length<lL)throw Error(`ciphertext shorter than the AES-GCM IV it must carry`);let n=t.slice(0,lL),r=t.slice(lL);return new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:n},e,r))}async function vL(e,t){return gL(e,t)}async function yL(e,t){return _L(e,t)}async function bL(e){return crypto.subtle.importKey(`raw`,Uint8Array.from(e),`AES-GCM`,!1,[`encrypt`,`decrypt`])}async function xL(e,t){return gL(await bL(e),t)}async function SL(e,t){return _L(await bL(e),t)}var CL=`+aes256gcm`;function wL(e){return EL(e)?e:`${e}${CL}`}function TL(e){return EL(e)?e.slice(0,e.length-10):e}function EL(e){return e.endsWith(CL)}function DL(e,t){return{verb:VI,params:{verb:`room.rekey`,"key-epoch":e,"wrapped-key":t}}}async function OL(e,t,n,r,i,a){return e.sendManageRequest(DL(n,r),{kind:`room`,path:t},i,a)}function kL(e){return async function(t){if(t.command.verb!==`room:member`){await t.respond({result:`error`,code:`malformed`});return}let n=uD.safeParse(t.command.params);if(!n.success){await t.respond({result:`error`,code:`malformed`});return}if(t.scope.kind!==`room`||t.scope.path===void 0){await t.respond({result:`error`,code:`scope_mismatch`});return}let r=t.scope.path,i=await HI(e.ownRoomMemberToken,{identity:e.identity,clock:e.clock,revocation:e.revocation,expectedBearer:e.identity.deviceId,roomPath:r,dmRootPolicy:`either-participant`});if(!i.ok){await t.respond({result:`error`,code:i.reason});return}let a=e.identity.deriveSharedSecret;if(a===void 0){await t.respond({result:`error`,code:`ecdh_unsupported`});return}let o=n.data[`key-epoch`],s=Array.isArray(n.data[`wrapped-key`])?n.data[`wrapped-key`]:[n.data[`wrapped-key`]],c=o-s.length+1,l;try{let e=await a(i.rootIssuerKey);l=await Promise.all(s.map(async(t,n)=>yL(await hL(e,{room:r,keyEpoch:c+n}),t)))}catch{await t.respond({result:`error`,code:`unwrap_failed`});return}await t.respond({result:`ok`}),await e.onRekey({room:r,keyEpoch:o,contentKeys:l})}}function AL(e){return Uint8Array.from(e)}function jL(e){return AL(Mg(e,hg))}function ML(e){return jL({1:e.identityKey.alg,4:e.deviceId})}function NL(e,t){return Mg([`Signature1`,e,new Uint8Array,t],hg)}function PL(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function FL(e,t){let[n,,r,i]=e;if(r===null)return{ok:!1,reason:`malformed`};let a;try{a=b_(r,x_)}catch{return{ok:!1,reason:`malformed`}}let o=mD.safeParse(a);if(!o.success)return{ok:!1,reason:`malformed`};let s=o.data;if(t.expectedRoom!==void 0&&s.room!==t.expectedRoom)return{ok:!1,reason:`wrong_room`};if(!await t.identity.verify(s[`poster-key`],NL(n,r),i))return{ok:!1,reason:`bad_signature`};if(!PL(await t.identity.deriveDeviceId(s[`poster-key`][`public-key`]),s.poster))return{ok:!1,reason:`wrong_poster`};let c=s[`valid-until`];if(c!==void 0&&c<=t.clock.now())return{ok:!1,reason:`content_expired`};let l=s[`key-epoch`];if(EL(s[`content-type`])!==(l!==void 0))return{ok:!1,reason:`key_epoch_mismatch`};let u=await HI(s.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:s.poster,roomPath:s.room,...t.dmRootPolicy===void 0?{}:{dmRootPolicy:t.dmRootPolicy}});return u.ok?{ok:!0,claims:s}:{ok:!1,reason:u.reason}}async function IL(e){let t=jL({room:e.room,poster:e.identity.deviceId,"poster-key":e.identity.identityKey,token:e.token,"notice-id":e.noticeId,"posted-at":e.clock.now(),"content-type":e.contentType,content:e.content,...e.refs===void 0?{}:{refs:[...e.refs]},...e.validUntil===void 0?{}:{"valid-until":e.validUntil},...e.keyEpoch===void 0?{}:{"key-epoch":e.keyEpoch}}),n=ML(e.identity);return[n,{},t,await e.identity.sign(NL(n,t))]}var LL=16;function RL(e){return new Uint8Array(Mg(e,hg))}function zL(e){let{identity:t,storage:n,clock:r,revocation:i,roomKeys:a}=e;async function o(e){let i=await a.currentEpoch(e.room);if(i===void 0)throw Error(`no content key held for room ${e.room}: room.rekey this room before posting encrypted notices`);let o=await a.get(e.room,i);if(o===void 0)throw Error(`content key store is inconsistent: epoch ${String(i)} is current for room ${e.room} but holds no key`);let s=e.noticeId??crypto.getRandomValues(new Uint8Array(LL)),c=await xL(o,e.plaintext),l=await IL({identity:t,clock:r,room:e.room,token:e.token,noticeId:s,contentType:wL(e.contentType),content:c,keyEpoch:i}),{haveFrame:u}=await bM({identity:t,storage:n},RL(l));return{dataHave:u,notice:l,keyEpoch:i}}async function s(e,t){let r=await yM(n,e);if(!(await SM(n,{type:`data-entries`,peer:e,"from-seq":r,entries:[t]})).ok)throw Error(`gap rejecting entry for peer log (head ${String(r)})`)}async function c(e,t,r){let i=await CM(n,e,0),a=[];for(let e of i)a.push(await l(e,t,r));return a}async function l(e,n,o){let s=u(e);if(s===void 0)return{verified:!1,reason:`malformed`};let c=await FL(s,{identity:t,clock:r,revocation:i,expectedRoom:n,dmRootPolicy:o});if(!c.ok)return{verified:!1,reason:c.reason};let l=c.claims;if(!EL(l[`content-type`]))return{verified:!0,contentType:l[`content-type`],plaintext:l.content,claims:l};let d=l[`key-epoch`];if(d===void 0)return{verified:!1,reason:`key_epoch_mismatch`};let f=await a.get(l.room,d),p={verified:!0,contentType:TL(l[`content-type`]),claims:l};if(f===void 0)return p;try{let e=await SL(f,l.content);return{...p,plaintext:e}}catch{return p}}function u(e){try{let t=b_(e,x_),n=pD.safeParse(t);return n.success?n.data:void 0}catch{return}}return{postEncryptedNotice:o,ingestPeerEntry:s,readOwnNotices:async e=>c(t.deviceId,e,`either-participant`),readPeerNotices:async(e,t)=>c(e,t,`self`)}}var BL=32;function VL(e){let{senders:t,storage:n,identity:r,clock:i,revocation:a,roomKeys:o,onChange:s}=e,c=zL({identity:r,storage:n,clock:i,revocation:a,roomKeys:o});async function l(e,t){let r=await yM(n,t);await e.sendDataFrame({type:`data-request`,peer:t,"from-seq":r})}async function u(e){let t=await yM(n,r.deviceId);t!==0&&await e.sendDataFrame({type:`data-have`,peer:r.deviceId,"head-seq":t})}function d(e,t){if(e.type===`data-have`){l(t,e.peer).catch(()=>void 0);return}if(e.type===`data-entries`){(async()=>{(await SM(n,e)).ok&&(e.entries.length>=BL&&await l(t,e.peer).catch(()=>void 0),s())})();return}e.type===`data-request`&&(async()=>{let r=await xM(n,e,BL);r!==null&&await t.sendDataFrame(r)})().catch(()=>void 0)}return{handleFrame:d,async post(e){let{dataHave:n}=await c.postEncryptedNotice(e);await Promise.allSettled(t().map(async e=>e.sendDataFrame(n))),s()},async readRoom(e,t){let n=await c.readOwnNotices(e),r=await Promise.all(t.map(async t=>c.readPeerNotices(t,e)));return[...n,...r.flat()]},async sync(e,t){await u(e),await Promise.all(t.map(async t=>l(e,t)))},async pull(e){await Promise.allSettled(t().flatMap(t=>e.map(async e=>l(t,e))))},roomKeys:o}}async function HL(e){let{session:t,target:n,identity:r,clock:i,revocation:a,ownRoomMemberToken:o,roomPath:s,roomKeys:c,delivery:l}=e,u=s.split(`+`)[0]??``;if(u===``||dO(r.deviceId)!==u)return;let d=await c.currentEpoch(s);if(d!==void 0&&d!==1||await l.isDelivered(s))return;let f=await HI(o,{identity:r,clock:i,revocation:a,expectedBearer:r.deviceId,roomPath:s,dmRootPolicy:`either-participant`});if(!f.ok)throw Error(`own room token failed verification: ${f.reason}`);let p=r.deriveSharedSecret;if(p===void 0)throw Error(`this identity cannot derive ECDH shared secrets`);let m=d===void 0?pL():await c.get(s,1);if(m===void 0)throw Error(`room ${s} lost its epoch 1 key`);let h=await vL(await hL(await p(f.rootIssuerKey),{room:s,keyEpoch:1}),m);d===void 0&&await c.set(s,1,m);let g=await OL(t,s,1,h,n,o);if(g.result!==`ok`)throw Error(`room.rekey was refused: ${g.code}`);await l.markDelivered(s)}var UL=[`core/management`,`core/room`],WL=16;function GL(){let e=new Uint8Array(WL);return crypto.getRandomValues(e),e}function KL(e){if(e?.direct!==void 0)return{session:e.direct,target:void 0};if(e?.relay!==void 0)return{session:e.relay.hub,target:e.relay.peer};throw Error(`conversation is not connected`)}function qL(e,t,n,r,i){let{revocation:a,grants:o}=i,[s,c]=(0,k.useReducer)(PF,new Map),l=dO(e.deviceId),[u,d]=(0,k.useState)(void 0),f=(0,k.useCallback)(e=>{e.then(void 0,e=>{d(e instanceof Error?e.message:String(e))})},[]),p=(0,k.useRef)(s);(0,k.useEffect)(()=>{p.current=s},[s]);let m=(0,k.useRef)(new Set),h=(0,k.useRef)(new WeakSet),g=(0,k.useMemo)(()=>iL(r),[r]);function _(){return[...p.current.values()].flatMap(e=>e.participants.map(e=>pO(e)))}let v=(0,k.useRef)(()=>void 0),y=(0,k.useMemo)(()=>VL({senders:()=>[...new Set([...[...p.current.values()].flatMap(e=>[...e.direct===void 0?[]:[e.direct],...e.relay===void 0?[]:[e.relay.hub]]),...m.current])],storage:r,identity:e,clock:t,revocation:a,roomKeys:g,onChange:()=>{v.current()}}),[e,t,r,g,a]);function b(e){let t=p.current.get(e)?.participants;t!==void 0&&y.readRoom(e,t.map(e=>pO(e))).then(t=>{c({type:`notices`,roomPath:e,notices:[...t]})})}(0,k.useEffect)(()=>{v.current=()=>{for(let e of p.current.keys())b(e)}});let x=(0,k.useRef)(new Map),S=(0,k.useMemo)(()=>oL(r),[r]),C=(0,k.useMemo)(()=>aL(r,e,t,a),[r,e,t,a]);async function w(e,t){x.current.set(e,t),await C.set(e,t)}async function T(e){let t=x.current.get(e);if(t!==void 0)return t;let n=await C.get(e);return n!==void 0&&x.current.set(e,n),n}(0,k.useEffect)(()=>{let e=new AbortController;return(async()=>{let t=new Set([...await n.roomPaths(),...await C.rooms()]);for(let r of t){let t=await n.list(r);if(e.signal.aborted)return;let i=FF(r,l);c({type:`restored`,roomPath:r,participants:i,messages:t}),y.readRoom(r,i.map(e=>pO(e))).then(e=>{c({type:`notices`,roomPath:r,notices:[...e]})})}})(),()=>{e.abort()}},[n,C,y,l]);let E=(0,k.useRef)(new Map);async function D(n,r,i){let o=E.current.get(n);if(o!==void 0)return o;let s=HL({session:i.session,target:i.target,identity:e,clock:t,revocation:a,ownRoomMemberToken:r,roomPath:n,roomKeys:g,delivery:S}).finally(()=>{E.current.delete(n)});return E.current.set(n,s),s}function O(r){return{onMessage:e=>{let t={direction:`received`,text:e.text,messageId:e.messageId,sentAt:e.sentAt};f(n.append(r,t)),c({type:`message`,roomPath:r,message:t}),y.pull((p.current.get(r)?.participants??[]).map(e=>pO(e)))},onGrantIssued:e=>{f(o.record(`issued`,e,t.now()))},onJoinRequest:e=>{c({type:`join-request`,roomPath:r,request:{requesterHex:dO(e.requesterDevice),async decide(t){c({type:`join-request-settled`,roomPath:r}),await e.decide(t),(async()=>{let e=await T(r),t=p.current.get(r);e!==void 0&&t!==void 0&&await D(r,e,KL(t))})().catch(()=>void 0)}}})},onRekey:async n=>{let i=await T(r);if(i===void 0){await n.respond({result:`error`,code:`no_token`});return}await kL({identity:e,clock:t,revocation:a,ownRoomMemberToken:i,onRekey:async e=>{for(let[t,n]of e.contentKeys.entries())await g.set(r,e.keyEpoch-e.contentKeys.length+1+t,n);b(r)}})(n)}}}let A=(0,k.useCallback)(async(r,i)=>{let o={},u=await oN(r,e,UL,{clock:t,onFrame:(e,t)=>{o.current?.(t)}}),d=i??await u.peerDeviceId,f=dO(d),p=fN(l,f);if(s.get(p)?.direct!==void 0){await u.close();return}o.current=e=>{y.handleFrame(e,u)},c({type:`direct-opened`,roomPath:p,participants:[f],session:u}),c({type:`restored`,roomPath:p,participants:[f],messages:await n.list(p)}),y.sync(u,[d]).catch(()=>void 0),QI(u,{identity:e,clock:t,revocation:a,peerDevice:d,currentMembers:()=>[e.deviceId,d]},O(p)),(async()=>{for await(let e of u.events)e.state.status===`closed`&&c({type:`direct-closed`,roomPath:p})})()},[e,t,l,s,n,y]),j=(0,k.useCallback)(async n=>UI(o,{identity:e,clock:t,revocation:a,expectedBearer:e.deviceId},VI,{kind:`room`,path:n}),[o,e,t,a]),M=(0,k.useCallback)(async(e,r,i)=>{let a=s.get(e),{session:l,target:u}=KL(a),d=a?.token;if(d===void 0){i(`awaiting-approval`);let n=await ZI(l,e,u,await j(e));i(`sending`),d=n.token,await w(e,d),f(o.record(`held`,d,t.now())),c({type:`token`,roomPath:e,token:d}),D(e,d,{session:l,target:u}).catch(()=>void 0)}let p=await XI(l,e,r,d,u);if(p.result!==`ok`)throw Error(`send failed: ${p.code}`);let m={direction:`sent`,text:r,messageId:GL(),sentAt:t.now()};return await n.append(e,m),m},[s,t,n,e,g,j]),N=(0,k.useCallback)(async(e,t,n)=>{c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:`sending`}});try{let r=await M(e,n,r=>{c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:r}})});c({type:`message`,roomPath:e,message:r}),c({type:`outgoing-removed`,roomPath:e,localId:t})}catch(r){c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:`failed`,error:r instanceof Error?r.message:String(r)}})}},[M]),ee=(0,k.useCallback)(async(e,t)=>N(e,crypto.randomUUID(),t),[N]),P=(0,k.useCallback)(async(e,t)=>{let n=s.get(e)?.outgoing.find(e=>e.localId===t);n!==void 0&&await N(e,t,n.text)},[s,N]),F=(0,k.useCallback)((e,t)=>{c({type:`outgoing-removed`,roomPath:e,localId:t})},[]),I=(0,k.useCallback)(async(e,n)=>{let r=s.get(e),{session:i,target:a}=KL(r),l=r?.token??await T(e);l===void 0&&(l=(await ZI(i,e,a,await j(e))).token,await w(e,l),f(o.record(`held`,l,t.now())),c({type:`token`,roomPath:e,token:l})),await D(e,l,{session:i,target:a}),await y.post({room:e,token:l,contentType:`text/plain`,plaintext:new TextEncoder().encode(n)}),b(e)},[s,e,t,g,y,j]),te=(0,k.useCallback)(e=>{c({type:`read`,roomPath:e})},[]),ne=(0,k.useCallback)((e,t)=>{let r=fN(l,dO(t)),i=[dO(t)];c({type:`relay-opened`,roomPath:r,participants:i,route:{hub:e,peer:t}}),n.list(r).then(e=>{c({type:`restored`,roomPath:r,participants:i,messages:e})}),y.sync(e,[t]).catch(()=>void 0)},[l,n,y]),re=(0,k.useCallback)(n=>{let r=new Map;m.current.add(n),(async()=>{for await(let i of n.incomingManageRequests){let o=i.fromDevice;if(o===void 0)continue;let s=dO(o),c=r.get(s);if(c===void 0){c=fM(),r.set(s,c);let i=fN(l,s);ne(n,o),QI({incomingManageRequests:c.stream},{identity:e,clock:t,revocation:a,peerDevice:o,currentMembers:()=>[e.deviceId,o]},O(i))}c.push(i)}})()},[e,t,l,ne]),ie=(0,k.useCallback)(e=>{m.current.delete(e),c({type:`hub-closed`,hub:e})},[]),L=(0,k.useCallback)((e,t,n)=>{h.current.has(t)||(h.current.add(t),y.sync(e,_()).catch(()=>void 0)),y.handleFrame(n,e)},[y]);return{conversations:[...s.values()],persistenceFailure:u,openRelay:ne,watchHub:re,dropHub:ie,onHubFrame:L,attach:A,send:ee,retry:P,discard:F,postNotice:I,markRead:te}}function JL(e,t){let n=new Map(t.map(e=>[e,fM()]));return(async()=>{for await(let t of e)n.get(t.command.verb)?.push(t)})(),{stream:e=>{let t=n.get(e);if(t===void 0)throw Error(`the demux was not built to carry verb ${e}`);return t.stream}}}var YL=8787,XL=/^(localhost|127\.\d+\.\d+\.\d+)(:\d+)?$/;function ZL(e){return XL.test(e)}async function QL(e=YL){try{return await fetch(`http://127.0.0.1:${String(e)}/`,{mode:`no-cors`}),`ws://127.0.0.1:${String(e)}`}catch{return}}async function $L(e=typeof location>`u`?``:location.host){return ZL(e)?Promise.resolve(void 0):QL()}var eR=`ws://localhost:8787`,tR=[`core/management`,`core/exec`,`core/data`],nR=[`core/management`,`core/data`],rR=[BN,VI];function iR({identity:e,clock:t,messageStore:n,roomStorage:r,certificateMemory:i,nameStore:a,preferences:o,grants:s,revocations:c,identityBackup:l,discoverLocalNode:u=$L,defaultAddress:d=eR}){let[f,p]=(0,k.useState)(d),[m,h]=(0,k.useState)(nR),[g,_]=(0,k.useState)([]),[v,y]=(0,k.useState)([]),[b,x]=(0,k.useState)([]),[S,C]=(0,k.useState)(void 0),w=OI(o),T=TF(i,t),E=(0,k.useMemo)(()=>({revocation:c.view,grants:s}),[c,s]),D=qL(e,t,n,r,E),[O,A]=(0,k.useState)(),j=D.conversations.find(e=>e.roomPath===O)??D.conversations[0],{markRead:M}=D,N=j?.roomPath,ee=j?.unread??0;(0,k.useEffect)(()=>{N!==void 0&&ee>0&&M(N)},[N,ee,M]);let P=(0,k.useRef)(new Map),F=(0,k.useRef)(D.onHubFrame);(0,k.useEffect)(()=>{F.current=D.onHubFrame},[D.onHubFrame]);let I=(0,k.useRef)(D.watchHub);(0,k.useEffect)(()=>{I.current=D.watchHub},[D.watchHub]);let te=(0,k.useRef)(D.attach);(0,k.useEffect)(()=>{te.current=D.attach},[D.attach]);let ne=(0,k.useRef)(g);(0,k.useEffect)(()=>{ne.current=g},[g]);let re=(0,k.useRef)(new Set),ie=(0,k.useRef)(new Map),L=(0,k.useRef)(!1),R=()=>L.current;(0,k.useEffect)(()=>(L.current=!1,()=>{L.current=!0;for(let e of ne.current)e.session.close()}),[]);let ae=(0,k.useRef)(m);(0,k.useEffect)(()=>{ae.current=m},[m]);function oe(n,r){let i=JL(r.incomingManageRequests,rR),a=aP({sendManageRequest:async(...e)=>r.sendManageRequest(...e),incomingManageRequests:i.stream(BN)},{identity:e,clock:t,revocation:E.revocation,iceServers:zN,onIncomingConnection:e=>{te.current(e)}});(async()=>{for await(let e of r.revocationAnnouncements)try{await c.ingest(e)}catch(e){C(e instanceof Error?e.message:String(e))}})();let o={sendManageRequest:async(...e)=>r.sendManageRequest(...e),sendDataFrame:async e=>r.sendDataFrame(e),incomingManageRequests:i.stream(VI)};P.current.set(r,o),I.current(o),_(e=>[...e,{address:n,session:r,hub:o,negotiator:a}])}async function se(e,t){let n=mF(e.device);for(let t of e.addresses){let e=ie.current.get(t)??new Set;e.add(n),ie.current.set(t,e)}return new Promise(r=>{y(i=>[...i,{key:n,device:e.device,addresses:e.addresses,via:t,resolve:r}])})}function ce(e,t){y(n=>(n.find(t=>t.key===e)?.resolve(t),n.filter(t=>t.key!==e)))}function le(n){let r={current:null},i={current:null},a=aN(RN(T.memory),e,t,vN,[],e=>{r.current?.considerAdvert(e)},(e,t)=>{let n=i.current===null?void 0:P.current.get(i.current);n!==void 0&&F.current(n,e,t)});return i.current=a,r.current=cN({selfDeviceId:e.deviceId,shouldExpand:async e=>se(e,n),dial:de,onExpanded:(e,t,n)=>{oe(t,n),ue(e)},onExpansionDeclined:ue,onExpansionFailed:ue}),a}function ue(e){let t=mF(e.device);for(let n of e.addresses){let e=ie.current.get(n);e?.delete(t),e?.size===0&&ie.current.delete(n)}}async function de(e){let t=await T.confirmAddress(JP(e));if(t===void 0)throw Error(`the certificate of ${e} was not trusted`);if(R())throw Error(`the console was closed before the dial began`);let n=ie.current.get(e),[r]=n??[],i=le({address:e,claimedDevice:n?.size===1?r:void 0});if(await i.connect(t,ae.current),R())throw await i.close(),Error(`the console was closed while the dial was connecting`);return i}function fe(e){ne.current.some(t=>t.address===e)||re.current.has(e)||(re.current.add(e),T.confirmAddress(JP(e)).then(t=>{if(t===void 0||R())return;let n=le({address:e,claimedDevice:void 0});oe(e,n),n.connect(t,m).catch(()=>{})}).finally(()=>{re.current.delete(e)}))}let pe=(0,k.useRef)(fe);(0,k.useEffect)(()=>{pe.current=fe});let me=(0,k.useRef)(u);(0,k.useEffect)(()=>{me.current=u},[u]);let he=(0,k.useRef)(!1);(0,k.useEffect)(()=>{he.current||(he.current=!0,me.current().then(e=>{e!==void 0&&pe.current(e)}))},[]);function ge(e){e.preventDefault(),fe(f)}async function _e(e){let t=await Promise.allSettled(ne.current.map(async t=>t.session.sendRevocationAnnounce([e])));return{attempted:t.length,reached:t.filter(e=>e.status===`fulfilled`).length}}function ve(e){D.dropHub(e.hub),e.session.close(),_(t=>t.filter(t=>t.session!==e.session))}function ye(t,n){D.openRelay(t.hub,n),A(fN(dO(e.deviceId),dO(n))),t.negotiator.initiate(n).then(async e=>D.attach(e,n)).catch(e=>{x(t=>[...t,{key:crypto.randomUUID(),peer:mF(n),reason:e instanceof Error?e.message:String(e)}])})}return(0,z.jsx)(EF,{store:a,children:(0,z.jsxs)(rm,{className:lF,p:`md`,gap:`lg`,children:[(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsx)(Lm,{order:1,children:`wire-mesh console`}),w.ready&&!w.visible&&(0,z.jsx)(Ed,{size:`xs`,variant:`subtle`,onClick:w.show,children:`How this works`})]}),w.error!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`The first-run intro's setting is unavailable`,children:w.error}),w.visible&&(0,z.jsx)(OF,{onDismiss:w.dismiss}),(0,z.jsx)(DF,{}),(0,z.jsxs)(`form`,{onSubmit:ge,children:[(0,z.jsxs)(pl,{align:`flex-end`,wrap:`wrap`,children:[(0,z.jsx)(Am,{label:`Node`,value:f,onChange:e=>{p(e.currentTarget.value)},required:!0,style:{flex:1,minWidth:`16rem`}}),(0,z.jsx)(Ed,{type:`submit`,children:`Connect`})]}),(0,z.jsx)(od.Group,{label:`Domains offered`,value:m,onChange:h,children:(0,z.jsx)(pl,{mt:`xs`,children:tR.map(e=>(0,z.jsx)(od,{value:e,label:e},e))})})]}),(0,z.jsx)(wF,{prompts:T.prompts,changes:T.changes,onDismissChange:T.dismissChange}),(0,z.jsx)(xF,{peers:v,onConnect:e=>{ce(e,!0)},onDismiss:e=>{ce(e,!1)}}),g.map(e=>(0,z.jsx)(yF,{address:e.address,session:e.session,clock:t,reconnectPolicy:vN,certificateChanges:T.changes,onClose:()=>{ve(e)},onMessagePeer:t=>{ye(e,t)}},e.address)),b.map(e=>(0,z.jsxs)(eu,{color:`yellow`,title:(0,z.jsxs)(z.Fragment,{children:[`No direct connection to `,(0,z.jsx)(YP,{deviceHex:e.peer})]}),withCloseButton:!0,onClose:()=>{x(t=>t.filter(t=>t.key!==e.key))},children:[e.reason,`. Messages go through the hub instead.`]},e.key)),D.persistenceFailure!==void 0&&(0,z.jsxs)(eu,{color:`red`,title:`Could not save to this console's storage`,children:[D.persistenceFailure,`. The conversation carries on, but what failed to save will be missing after a reload.`]}),S!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`A revocation could not be stored`,children:S}),(0,z.jsx)(EI,{revocations:c,onFailure:C}),(0,z.jsx)(BF,{conversations:D.conversations,onSelect:A}),(0,z.jsx)(TI,{identity:e,clock:t,grants:s,revocations:c,identityBackup:l,announceRevocation:_e}),(0,z.jsx)(kI,{conversations:D.conversations,selected:j?.roomPath,onSelect:A}),j!==void 0&&(0,z.jsx)(BI,{view:j,onSend:async e=>D.send(j.roomPath,e),onPostNotice:async e=>D.postNotice(j.roomPath,e),onRetry:e=>{D.retry(j.roomPath,e)},onDiscard:e=>{D.discard(j.roomPath,e)}},j.roomPath)]})})}var aR=`modulepreload`,oR=function(e){return`/`+e},sR={},cR=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=oR(t,n),t=s(t),t in sR)return;sR[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:aR,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},lR=`false`,uR=`false`,dR=lR===`true`,fR=uR===`true`;function pR(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,dR||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await cR(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!fR){if(dR)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}function mR(e={}){let{immediate:t=!0,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,[c,l]=(0,k.useState)(!1),[u,d]=(0,k.useState)(!1),[f]=(0,k.useState)(()=>pR({immediate:t,onNeedReload:n,onOfflineReady(){d(!0),i?.()},onNeedRefresh(){l(!0),r?.()},onRegistered:a,onRegisteredSW:o,onRegisterError:s}));return{needRefresh:[c,l],offlineReady:[u,d],updateServiceWorker:f}}function hR(){let{offlineReady:[e,t],needRefresh:[n,r],updateServiceWorker:i}=mR();function a(){t(!1),r(!1)}return!e&&!n?null:(0,z.jsx)(Ef,{onClose:a,closeButtonProps:{"aria-label":`Dismiss`},title:n?`Update available`:`Ready to work offline`,pos:`fixed`,bottom:`1rem`,right:`1rem`,style:{zIndex:1e3},children:(0,z.jsx)(pl,{gap:`xs`,children:n?(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{i(!0)},children:`Reload`}):void 0})})}var gR=`ws://localhost:8787`;function _R(e){return`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}`}function vR(e,t){return e?gR:_R(t)}var yR=await qm(),bR=await F_(yR),xR={now:()=>Date.now()},SR=gj(await qm()),CR=await xj({storage:await qm(),identity:bR,clock:xR}),wR=kO(yR),TR=Gj(await qm()),ER=await qm(),DR=hO(await qm()),OR=Rj(await qm()),kR=wj(await qm()),AR=vR(!1,window.location),jR=document.getElementById(`root`);if(jR===null)throw Error(`missing #root element`);(0,Rm.createRoot)(jR).render((0,z.jsx)(k.StrictMode,{children:(0,z.jsxs)(xn,{children:[(0,z.jsx)(iR,{identity:bR,clock:xR,messageStore:TR,roomStorage:ER,certificateMemory:DR,nameStore:OR,preferences:kR,grants:SR,revocations:CR,identityBackup:wR,defaultAddress:AR}),(0,z.jsx)(hR,{})]})}));
|
|
80
|
+
`,t:` `,r:`\r`,f:`\f`,v:`\v`},zk=class{pattern;pos=0;constructor(e){this.pattern=e}get position(){return this.pos}atEnd(){return this.pos>=this.pattern.length}peek(e=0){return this.pattern[this.pos+e]}advance(){let e=this.pattern[this.pos];if(e===void 0)throw new kk(this.pattern,this.pos,`unexpected end of pattern`);return this.pos+=1,e}parseAlternation(){let e=this.parseSequence(),t=[];for(;this.peek()===`|`;)this.advance(),t.push(this.parseSequence());return t.length===0?e:{kind:`alternation`,branches:[e,...t]}}parseSequence(){if(this.atEnd()||Lk.has(this.peek()??``))return{kind:`concat`,operands:[]};let e=this.parseQuantified(),t=[];for(;!this.atEnd()&&!Lk.has(this.peek()??``);)t.push(this.parseQuantified());return t.length===0?e:{kind:`concat`,operands:[e,...t]}}parseQuantified(){let e=this.pos,t=this.parseAtom();if(t.kind===`anchorStart`||t.kind===`anchorEnd`){if(this.peekIsQuantifierStart())throw new kk(this.pattern,e,`an anchor ('${t.kind===`anchorStart`?`^`:`$`}') cannot be quantified`);return t}let n=this.tryParseQuantifier();if(n===void 0)return t;if(this.peekIsQuantifierStart())throw new kk(this.pattern,this.pos,`a quantifier cannot itself be quantified -- this grammar has no lazy or possessive modifiers, since a pattern that only ever answers a yes/no match question has no notion for either to change`);switch(n.kind){case`star`:return{kind:`star`,operand:t};case`plus`:return{kind:`plus`,operand:t};case`optional`:return{kind:`optional`,operand:t};case`repeat`:return{kind:`repeat`,operand:t,min:n.min,max:n.max};default:throw Error(`unreachable quantifier kind`)}}peekIsQuantifierStart(){let e=this.peek();if(e===`*`||e===`+`||e===`?`)return!0;if(e===`{`){let e=this.pos,t=this.tryParseBound();return this.pos=e,t!==void 0}return!1}tryParseQuantifier(){let e=this.peek();if(e===`*`)return this.advance(),{kind:`star`};if(e===`+`)return this.advance(),{kind:`plus`};if(e===`?`)return this.advance(),{kind:`optional`};if(e===`{`){let e=this.tryParseBound();return e===void 0?void 0:{kind:`repeat`,min:e.min,max:e.max}}}tryParseBound(){let e=this.pos;this.pos+=1;let t=this.readDigits();if(t===``){this.pos=e;return}let n,r=!1;if(this.peek()===`,`&&(r=!0,this.pos+=1,n=this.readDigits()),this.peek()!==`}`){this.pos=e;return}this.pos+=1;let i=Number.parseInt(t,10),a=r?n===``?void 0:Number.parseInt(n??``,10):i;if(a!==void 0&&a<i)throw new kk(this.pattern,e,`quantifier range is backwards: {${t}${r?`,`+(n??``):``}} would require between ${String(i)} and ${String(a)} repetitions`);return{min:i,max:a}}readDigits(){let e=``;for(;;){let t=this.peek();if(t===void 0||t<`0`||t>`9`)break;e+=t,this.pos+=1}return e}parseAtom(){let e=this.peek();if(e===void 0)throw new kk(this.pattern,this.pos,`unexpected end of pattern`);if(e===`^`)return this.advance(),{kind:`anchorStart`};if(e===`$`)return this.advance(),{kind:`anchorEnd`};if(e===`.`)return this.advance(),{kind:`anyChar`};if(e===`(`)return this.parseGroup();if(e===`[`)return this.parseCharClass();if(e===`\\`)return this.parseEscapedAtom();if(e===`*`||e===`+`||e===`?`)throw new kk(this.pattern,this.pos,`quantifier '${e}' with nothing to repeat`);return this.advance(),{kind:`literal`,codeUnit:e.charCodeAt(0)}}parseGroup(){let e=this.pos;if(this.advance(),this.peek()===`?`&&this.peek(1)===`:`)this.advance(),this.advance();else throw new kk(this.pattern,e,`capturing groups are not supported in this grammar -- there is nothing to capture, since a pattern only ever answers whether it matches. Use '(?:...)' for grouping.`);let t=this.parseAlternation();if(this.peek()!==`)`)throw new kk(this.pattern,this.pos,`expected ')' to close '(?:'`);return this.advance(),t}parseEscapedAtom(){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`D`||t===`w`||t===`W`||t===`s`||t===`S`)return Ik(t);let n=Rk[t];if(n!==void 0)return{kind:`literal`,codeUnit:n.charCodeAt(0)};throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`)}parseCharClass(){let e=this.pos;this.advance();let t=!1;this.peek()===`^`&&(this.advance(),t=!0);let n=[];for(;;){if(this.atEnd())throw new kk(this.pattern,e,`unterminated character class -- missing closing ']'`);if(this.peek()===`]`){if(n.length===0)throw new kk(this.pattern,this.pos,`a character class must contain at least one item -- ']' immediately, or immediately after '[^', is not the empty class here (escape it as '\\]' to match a literal ']')`);this.advance();break}n.push(...this.parseClassItem())}return{kind:`charClass`,negated:t,ranges:n}}parseClassItem(){let e=this.peek();if(e===`\\`){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`w`||t===`s`)return Ik(t).ranges;if(t===`D`||t===`W`||t===`S`)throw new kk(this.pattern,e,`the negated shorthand class '\\${t}' cannot be embedded inside a character class, because its complement cannot be represented as a set of ranges to union with the class's other members -- use it as its own atom instead of embedding it here`);let n=Rk[t];if(n===void 0)throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`);return this.parseOptionalRangeFrom(n.charCodeAt(0))}if(e===void 0)throw new kk(this.pattern,this.pos,`unterminated character class -- missing closing ']'`);return this.advance(),this.parseOptionalRangeFrom(e.charCodeAt(0))}parseOptionalRangeFrom(e){if(this.peek()===`-`&&this.peek(1)!==void 0&&this.peek(1)!==`]`){let t=this.pos;this.advance();let n=this.parseClassRangeEndpoint();if(n<e)throw new kk(this.pattern,t,`invalid range in character class: '${String.fromCharCode(e)}-${String.fromCharCode(n)}' is reversed`);return[{from:e,to:n}]}return[{from:e,to:e}]}parseClassRangeEndpoint(){let e=this.peek();if(e===`\\`){let e=this.pos;if(this.advance(),this.atEnd())throw new kk(this.pattern,e,`trailing backslash with nothing to escape`);let t=this.advance();if(t===`d`||t===`D`||t===`w`||t===`W`||t===`s`||t===`S`)throw new kk(this.pattern,e,`a shorthand class ('\\${t}') cannot be a range endpoint`);let n=Rk[t];if(n===void 0)throw new kk(this.pattern,e,`unknown escape sequence '\\${t}'`);return n.charCodeAt(0)}if(e===void 0)throw new kk(this.pattern,this.pos,`unterminated character class -- missing closing ']'`);return this.advance(),e.charCodeAt(0)}};function Bk(e){let t=new zk(e),n=t.parseAlternation();if(!t.atEnd())throw new kk(e,t.position,`unexpected character -- if this was meant literally, escape it with a backslash`);return n}var Vk=class{states=[];add(e){return this.states.push(e),this.states.length-1}patch(e,t){for(let n of e){let e=this.states[n.state];if(e!==void 0)switch(n.field){case`to`:(e.kind===`char`||e.kind===`anchorStart`||e.kind===`anchorEnd`)&&(e.to=t);break;case`to1`:e.kind===`split`&&(e.to1=t);break;case`to2`:e.kind===`split`&&(e.to2=t)}}}emptyFrag(){let e=this.add({kind:`split`,to1:-1,to2:-1});return{start:e,out:[{state:e,field:`to1`},{state:e,field:`to2`}]}}compileRepeat(e){let{operand:t,min:n,max:r}=e;if(r===void 0){if(n===0)return this.compileNode({kind:`star`,operand:t});let e=[];for(let r=0;r<n-1;r+=1)e.push(t);return e.push({kind:`plus`,operand:t}),this.compileNode({kind:`concat`,operands:e})}let i=[];for(let e=0;e<n;e+=1)i.push(t);for(let e=0;e<r-n;e+=1)i.push({kind:`optional`,operand:t});return i.length===0?this.emptyFrag():this.compileNode({kind:`concat`,operands:i})}compileNode(e){switch(e.kind){case`literal`:{let t=e.codeUnit,n=this.add({kind:`char`,test:e=>e===t,to:-1});return{start:n,out:[{state:n,field:`to`}]}}case`anyChar`:{let e=this.add({kind:`char`,test:()=>!0,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`charClass`:{let t=this.add({kind:`char`,test:t=>Ok(e,t),to:-1});return{start:t,out:[{state:t,field:`to`}]}}case`anchorStart`:{let e=this.add({kind:`anchorStart`,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`anchorEnd`:{let e=this.add({kind:`anchorEnd`,to:-1});return{start:e,out:[{state:e,field:`to`}]}}case`concat`:{if(e.operands.length===0)return this.emptyFrag();let[t,...n]=e.operands;if(t===void 0)throw Error(`unreachable: a non-empty operands array always has a first element`);let r=this.compileNode(t);for(let e of n){let t=this.compileNode(e);this.patch(r.out,t.start),r={start:r.start,out:t.out}}return r}case`alternation`:{let[t,...n]=e.branches;if(t===void 0)throw Error(`unreachable: AlternationNode always has at least two branches`);let r=this.compileNode(t);for(let e of n){let t=this.compileNode(e);r={start:this.add({kind:`split`,to1:r.start,to2:t.start}),out:[...r.out,...t.out]}}return r}case`star`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return this.patch(t.out,n),{start:n,out:[{state:n,field:`to2`}]}}case`plus`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return this.patch(t.out,n),{start:t.start,out:[{state:n,field:`to2`}]}}case`optional`:{let t=this.compileNode(e.operand),n=this.add({kind:`split`,to1:t.start,to2:-1});return{start:n,out:[...t.out,{state:n,field:`to2`}]}}case`repeat`:return this.compileRepeat(e);default:throw Error(`unreachable regex node kind`)}}build(e){let t=this.compileNode(e),n=this.add({kind:`match`});return this.patch(t.out,n),{states:this.states,start:t.start,matchState:n}}};function Hk(e){return new Vk().build(e)}function Uk(e,t,n,r){let i=new Set,a=new Set,o=[...t];for(;o.length>0;){let t=o.pop();if(t===void 0||a.has(t))continue;a.add(t);let s=e.states[t];if(s!==void 0)switch(s.kind){case`char`:case`match`:i.add(t);break;case`split`:o.push(s.to1,s.to2);break;case`anchorStart`:n===0&&o.push(s.to);break;case`anchorEnd`:n===r&&o.push(s.to)}}return i}function Wk(e,t,n){let r=new Set;for(let i of t){let t=e.states[i];t?.kind===`char`&&t.test(n)&&r.add(t.to)}return r}function Gk(e,t){let n=t.length,r=Uk(e,[e.start],0,n);if(r.has(e.matchState))return!0;for(let i=0;i<n;i+=1){let a=t.charCodeAt(i),o=Wk(e,r,a);if(o.add(e.start),r=Uk(e,[...o],i+1,n),r.has(e.matchState))return!0}return!1}function Kk(e){let t=Hk(Bk(e));return{test:e=>Gk(t,e)}}function qk(e,t){if(e.status===`definite`&&!e.value||t.status===`definite`&&!t.value)return Q(!1);let n=VO(e,t);return n===void 0?Q(!0):{status:`indeterminate`,reason:n}}function Jk(e,t){if(e.status===`definite`&&e.value||t.status===`definite`&&t.value)return Q(!0);let n=VO(e,t);return n===void 0?Q(!1):{status:`indeterminate`,reason:n}}function Yk(e,t,n){switch(e){case`gt`:return t>n;case`gte`:return t>=n;case`lt`:return t<n;case`lte`:return t<=n;case`eq`:return t===n;case`neq`:return t!==n;default:throw Error(`unreachable comparison operator`)}}var Xk={ms:1,s:1e3,min:6e4,h:36e5,d:864e5};function Zk(e,t){return e*Xk[t]}function Qk(e){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function $k(e){return $(`wrong-type`,`'${e}' is not a parseable ISO-8601 timestamp`)}function eA(e){let t=new Date(e);return Number.isNaN(t.getTime())?$(`domain-error`,`the resulting instant falls outside the representable timestamp range`):Q({kind:`instant`,value:t.toISOString()})}function tA(e,t,n){switch(t.kind){case`number`:return n.kind===`number`?RO(t.unit,n.unit)?Q(Yk(e,t.value,n.value)):$(`wrong-type`,`cannot compare numbers with incompatible units`):$(`wrong-type`,`cannot compare a 'number' value with a '${n.kind}' value`);case`text`:return $(`wrong-type`,`text values are not comparable via 'compare'; use 'textCompare'`);case`boolean`:return n.kind===`boolean`?e!==`eq`&&e!==`neq`?$(`wrong-type`,`booleans have no natural ordering; '${e}' is only defined for 'eq'/'neq'`):Q(e===`eq`?t.value===n.value:t.value!==n.value):$(`wrong-type`,`cannot compare a 'boolean' value with a '${n.kind}' value`);case`instant`:{if(n.kind!==`instant`)return $(`wrong-type`,`cannot compare an 'instant' value with a '${n.kind}' value`);let r=Qk(t.value);if(r===void 0)return $k(t.value);let i=Qk(n.value);return i===void 0?$k(n.value):Q(Yk(e,r,i))}case`duration`:return n.kind===`duration`?Q(Yk(e,Zk(t.value,t.unit),Zk(n.value,n.unit))):$(`wrong-type`,`cannot compare a 'duration' value with a '${n.kind}' value`);case`complex`:return e!==`eq`&&e!==`neq`?$(`wrong-type`,`ordering operator '${e}' is not defined for complex values; the complex plane has no total order`):n.kind===`complex`?RO(t.unit,n.unit)?Q(e===`eq`?t.re===n.re&&t.im===n.im:t.re!==n.re||t.im!==n.im):$(`wrong-type`,`cannot compare complex values with incompatible units`):$(`wrong-type`,`cannot compare a 'complex' value with a '${n.kind}' value`);default:throw Error(`unreachable computed-value kind`)}}function nA(e,t,n){if(t.kind!==`text`)return $(`wrong-type`,`'textCompare' requires 'text' operands; the left operand is '${t.kind}'`);if(n.kind!==`text`)return $(`wrong-type`,`'textCompare' requires 'text' operands; the right operand is '${n.kind}'`);switch(e){case`equals`:return Q(t.value===n.value);case`notEquals`:return Q(t.value!==n.value);case`matches`:case`notMatches`:{let r;try{r=new RegExp(n.value)}catch{return $(`wrong-type`,`'${n.value}' is not a valid regular expression pattern`)}let i=r.test(t.value);return Q(e===`matches`?i:!i)}case`portableMatches`:case`portableNotMatches`:{let r;try{r=Kk(n.value)}catch(e){let t=e instanceof kk?e.message:String(e);return $(`wrong-type`,`'${n.value}' is not a valid trilean-regex pattern: ${t}`)}let i=r.test(t.value);return Q(e===`portableMatches`?i:!i)}default:throw Error(`unreachable text comparison operator`)}}function rA(e,t){switch(e.kind){case`number`:return t.kind===`number`?RO(e.unit,t.unit)?Q(e.value===t.value):$(`wrong-type`,`cannot compare numbers with incompatible units for membership`):$(`wrong-type`,`cannot compare a 'number' value with a '${t.kind}' value for membership`);case`text`:return t.kind===`text`?Q(e.value===t.value):$(`wrong-type`,`cannot compare a 'text' value with a '${t.kind}' value for membership`);case`boolean`:return t.kind===`boolean`?Q(e.value===t.value):$(`wrong-type`,`cannot compare a 'boolean' value with a '${t.kind}' value for membership`);case`instant`:{if(t.kind!==`instant`)return $(`wrong-type`,`cannot compare an 'instant' value with a '${t.kind}' value for membership`);let n=Qk(e.value);if(n===void 0)return $k(e.value);let r=Qk(t.value);return r===void 0?$k(t.value):Q(n===r)}case`duration`:return t.kind===`duration`?Q(Zk(e.value,e.unit)===Zk(t.value,t.unit)):$(`wrong-type`,`cannot compare a 'duration' value with a '${t.kind}' value for membership`);case`complex`:return t.kind===`complex`?RO(e.unit,t.unit)?Q(e.re===t.re&&e.im===t.im):$(`wrong-type`,`cannot compare complex values with incompatible units for membership`):$(`wrong-type`,`cannot compare a 'complex' value with a '${t.kind}' value for membership`);default:throw Error(`unreachable computed-value kind`)}}function iA(e){return RO(e,void 0)}function aA(e){switch(e.kind){case`number`:return Q({kind:`number`,value:-e.value,unit:e.unit});case`duration`:return Q({kind:`duration`,value:-e.value,unit:e.unit});case`complex`:return Q({kind:`complex`,re:-e.re,im:-e.im,unit:e.unit});case`text`:case`instant`:case`boolean`:return $(`wrong-type`,`cannot negate a '${e.kind}' value`);default:throw Error(`unreachable computed-value kind`)}}function oA(e,t,n){switch(e){case`add`:return RO(t.unit,n.unit)?Q({kind:`number`,value:t.value+n.value,unit:t.unit}):$(`wrong-type`,`cannot add numbers with incompatible units`);case`subtract`:return RO(t.unit,n.unit)?Q({kind:`number`,value:t.value-n.value,unit:t.unit}):$(`wrong-type`,`cannot subtract numbers with incompatible units`);case`multiply`:return Q({kind:`number`,value:t.value*n.value,unit:zO(t.unit,n.unit)});case`divide`:return n.value===0?$(`domain-error`,`division by zero`):Q({kind:`number`,value:t.value/n.value,unit:BO(t.unit,n.unit)});case`power`:return!iA(t.unit)||!iA(n.unit)?$(`wrong-type`,`'power' requires dimensionless operands`):t.value<0&&!Number.isInteger(n.value)?$(`domain-error`,`a negative base raised to a non-integer power is not a real number`):t.value===0&&n.value<0?$(`domain-error`,`zero raised to a negative power is a division by zero`):Q({kind:`number`,value:t.value**n.value});case`modulo`:return!iA(t.unit)||!iA(n.unit)?$(`wrong-type`,`'modulo' requires dimensionless operands`):n.value===0?$(`domain-error`,`modulo by zero`):Q({kind:`number`,value:t.value%n.value});default:throw Error(`unreachable arithmetic operator`)}}function sA(e,t,n){switch(e){case`add`:return Q({kind:`duration`,value:Zk(t.value,t.unit)+Zk(n.value,n.unit),unit:`ms`});case`subtract`:return Q({kind:`duration`,value:Zk(t.value,t.unit)-Zk(n.value,n.unit),unit:`ms`});case`multiply`:case`divide`:case`power`:case`modulo`:return $(`wrong-type`,`arithmetic operator '${e}' is not defined between two 'duration' values`);default:throw Error(`unreachable arithmetic operator`)}}function cA(e){return e.kind===`complex`?e:{kind:`complex`,re:e.value,im:0,unit:e.unit}}function lA(e,t){return{kind:`complex`,re:e.re*t.re-e.im*t.im,im:e.re*t.im+e.im*t.re,unit:zO(e.unit,t.unit)}}function uA(e,t,n){switch(e){case`add`:return RO(t.unit,n.unit)?Q({kind:`complex`,re:t.re+n.re,im:t.im+n.im,unit:t.unit}):$(`wrong-type`,`cannot add complex values with incompatible units`);case`subtract`:return RO(t.unit,n.unit)?Q({kind:`complex`,re:t.re-n.re,im:t.im-n.im,unit:t.unit}):$(`wrong-type`,`cannot subtract complex values with incompatible units`);case`multiply`:return Q(lA(t,n));case`divide`:{let e=n.re*n.re+n.im*n.im;return e===0?$(`domain-error`,`division by zero`):Q({kind:`complex`,re:(t.re*n.re+t.im*n.im)/e,im:(t.im*n.re-t.re*n.im)/e,unit:BO(t.unit,n.unit)})}case`modulo`:return $(`domain-error`,`'modulo' is undefined for complex values`);default:throw Error(`unreachable arithmetic operator`)}}function dA(e,t){if(t.kind!==`number`||!Number.isInteger(t.value))return $(`wrong-type`,`'power' with a complex operand requires a real integer exponent`);if(!iA(e.unit)||!iA(t.unit))return $(`wrong-type`,`'power' requires dimensionless operands`);let n={kind:`complex`,re:1,im:0,unit:{}},r=cA(e),i=n;for(let e=0;e<Math.abs(t.value);e+=1)i=lA(i,r);return t.value>=0?Q(i):uA(`divide`,n,i)}function fA(e,t,n){if(t.kind===`instant`&&n.kind===`instant`&&e===`subtract`){let e=Qk(t.value);if(e===void 0)return $k(t.value);let r=Qk(n.value);return r===void 0?$k(n.value):Q({kind:`duration`,value:e-r,unit:`ms`})}if(t.kind===`instant`&&n.kind===`duration`&&e===`add`){let e=Qk(t.value);return e===void 0?$k(t.value):eA(e+Zk(n.value,n.unit))}if(t.kind===`duration`&&n.kind===`instant`&&e===`add`){let e=Qk(n.value);return e===void 0?$k(n.value):eA(e+Zk(t.value,t.unit))}return t.kind===`instant`||n.kind===`instant`?$(`wrong-type`,`arithmetic operator '${e}' is not defined between a '${t.kind}' and a '${n.kind}' value`):t.kind===`duration`&&n.kind===`duration`?sA(e,t,n):t.kind===`duration`||n.kind===`duration`?$(`wrong-type`,`arithmetic operator '${e}' is not defined between a '${t.kind}' and a '${n.kind}' value`):t.kind!==`number`&&t.kind!==`complex`?$(`wrong-type`,`arithmetic requires numeric operands; got a '${t.kind}' value`):n.kind!==`number`&&n.kind!==`complex`?$(`wrong-type`,`arithmetic requires numeric operands; got a '${n.kind}' value`):t.kind===`complex`||n.kind===`complex`?e===`power`?dA(t,n):uA(e,cA(t),cA(n)):oA(e,t,n)}function pA(e,t){if(e!==void 0){if(t.kind!==`number`&&t.kind!==`complex`)return $(`wrong-type`,`a unit was expected on a reference that resolved to a non-numeric value`);if(!RO(e,t.unit))return $(`wrong-type`,`the resolved value's unit does not match the reference's expected unit`)}}function mA(e,t,n){let r=Object.hasOwn(e,t)?e[t]:void 0;if(r===void 0)return $(`wrong-type`,`no function registered under the name '${t}'`);let i=r(n);return`domainError`in i?$(`domain-error`,i.domainError):Q(i)}async function hA(e,t,n,r,i,a,o,s,c){let l=s.checkNode(c);if(l!==void 0)return l;switch(e.kind){case`not`:{let l=await hA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`?l:Q(!l.value)}case`and`:{let[l,u]=await Promise.all([hA(e.left,t,n,r,i,a,o,s,c+1),hA(e.right,t,n,r,i,a,o,s,c+1)]);return qk(l,u)}case`or`:{let[l,u]=await Promise.all([hA(e.left,t,n,r,i,a,o,s,c+1),hA(e.right,t,n,r,i,a,o,s,c+1)]);return Jk(l,u)}case`allOf`:return(await Promise.all(e.operands.map(async e=>hA(e,t,n,r,i,a,o,s,c+1)))).reduce(qk,Q(!0));case`anyOf`:return(await Promise.all(e.operands.map(async e=>hA(e,t,n,r,i,a,o,s,c+1)))).reduce(Jk,Q(!1));case`compare`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:tA(e.op,l.value,u.value)}case`textCompare`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:nA(e.op,l.value,u.value)}case`memberOf`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);if(l.status===`indeterminate`)return l;let u=await Promise.all(e.candidates.map(async e=>{let u=await gA(e,t,n,r,i,a,o,s,c+1);return u.status===`indeterminate`?u:rA(l.value,u.value)}));for(let t of u)if(t.status===`definite`&&t.value)return Q(e.op===`in`);let d=VO(...u);return d===void 0?Q(e.op===`notIn`):{status:`indeterminate`,reason:d}}case`exists`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`&&l.reason.code===`not-found`?Q(!1):Q(!0)}case`some`:case`every`:{let r=await Tk(hA,e.collection,e.filter,t,n,i,a,o,s,c+1),l=(await Promise.all(r.map(async({item:t,filterOutcome:r})=>{if(r!==`exclude`)return r===`include`?hA(e.item,t,n,void 0,i,a,o,s,c+1):r}))).filter(e=>e!==void 0),u=e.kind===`some`?Jk:qk,d=e.kind===`some`?Q(!1):Q(!0);return l.reduce(u,d)}case`treeReference`:{if(n.resolveTree===void 0)return $(`wrong-type`,`no tree resolver registered for treeReference nodes`);let l=JSON.stringify(e.key);if(a.has(l))return $(`domain-error`,`circular treeReference detected`);if(o>=100)return $(`domain-error`,`treeReference chain exceeds the maximum depth of 100`);let u=await n.resolveTree(e.key,t);if(!u.found)return $(`not-found`,`treeReference key did not resolve to a tree`);let d=ok.safeParse(u.node);return d.success?hA(d.data,t,n,r,i,new Set([...a,l]),o+1,s,c+1):$(`wrong-type`,`the referenced tree is not a valid PredicateNode`)}default:throw Error(`unreachable predicate node kind`)}}async function gA(e,t,n,r,i,a,o,s,c){let l=s.checkNode(c);if(l!==void 0)return l;switch(e.kind){case`reference`:{let r=await n.resolveValue(e.key,t);if(!r.found)return $(`not-found`,`no value found for reference key ${JSON.stringify(e.key)}`);let i=pA(e.unit,r.value);return i===void 0?Q(r.value):i}case`accumulator`:return r===void 0?$(`wrong-type`,`accumulator used outside a reduce fold's combine expression`):Q(r);case`call`:{let l=await Promise.all(e.args.map(async e=>gA(e,t,n,r,i,a,o,s,c+1))),u=[];for(let e of l){if(e.status===`indeterminate`)return e;u.push(e.value)}return mA(i,e.fn,u)}case`numberLiteral`:return Q({kind:`number`,value:e.value,unit:e.unit});case`textLiteral`:return Q({kind:`text`,value:e.value});case`booleanLiteral`:return Q({kind:`boolean`,value:e.value});case`instantLiteral`:return Q({kind:`instant`,value:e.value});case`durationLiteral`:return Q({kind:`duration`,value:e.value,unit:e.unit});case`complexLiteral`:return`re`in e?Q({kind:`complex`,re:e.re,im:e.im,unit:e.unit}):Q(PO(e.magnitude,e.phase,e.unit));case`arithmetic`:{let[l,u]=await Promise.all([gA(e.left,t,n,r,i,a,o,s,c+1),gA(e.right,t,n,r,i,a,o,s,c+1)]);return l.status===`indeterminate`?l:u.status===`indeterminate`?u:fA(e.op,l.value,u.value)}case`negate`:{let l=await gA(e.operand,t,n,r,i,a,o,s,c+1);return l.status===`indeterminate`?l:aA(l.value)}case`lookup`:{let l=await Promise.all(e.keys.map(async e=>gA(e,t,n,r,i,a,o,s,c+1))),u=[];for(let e of l){if(e.status===`indeterminate`)return e;u.push(e.value)}let d=await n.resolveLookup(e.table,u,t);return d.found?Q(d.value):$(`not-found`,`no match found in lookup table ${JSON.stringify(e.table)}`)}case`conditional`:{if((e.hitPolicy??`first`)===`first`){for(let{when:l,then:u}of e.cases){let e=await hA(l,t,n,r,i,a,o,s,c+1);if(e.status===`indeterminate`)return e;if(e.value)return gA(u,t,n,r,i,a,o,s,c+1)}return gA(e.fallback,t,n,r,i,a,o,s,c+1)}let l=await Promise.all(e.cases.map(async({when:e,then:l})=>({then:l,whenResult:await hA(e,t,n,r,i,a,o,s,c+1)}))),u=l.filter(({whenResult:e})=>e.status===`definite`&&e.value);if(u.length>=2)return $(`domain-error`,`more than one case matched under the 'unique' hit policy`);let d=VO(...l.map(({whenResult:e})=>e));if(d!==void 0)return{status:`indeterminate`,reason:d};let[f]=u;return gA(f===void 0?e.fallback:f.then,t,n,r,i,a,o,s,c+1)}case`fold`:{let r=await Tk(hA,e.collection,e.filter,t,n,i,a,o,s,c+1),l=Ek(r);if(l!==void 0)return{status:`indeterminate`,reason:l};let u=r.filter(({filterOutcome:e})=>e===`include`).map(({item:e})=>e);if(e.combiner.mode===`reduce`){let r=await gA(e.combiner.initial,t,n,void 0,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;let l=r.value;for(let t of u){let r=await gA(e.combiner.combine,t,n,l,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;l=r.value}return Q(l)}if(u.length===0)return $(`domain-error`,`'${e.combiner.mode}' has no participating items to seed a running result from`);let d=e.combiner.mode===`max`?`gt`:`lt`,f;for(let t of u){let r=await gA(e.combiner.item,t,n,void 0,i,a,o,s,c+1);if(r.status===`indeterminate`)return r;if(f===void 0){f=r.value;continue}let l=tA(d,r.value,f);if(l.status===`indeterminate`)return l;l.value&&(f=r.value)}if(f===void 0)throw Error(`unreachable: max/min over a non-empty participating list produced no running result`);return Q(f)}case`delegate`:{if(n.resolveDelegate===void 0)return $(`wrong-type`,`no delegate handler registered for external system '${e.system}'`);let r=await n.resolveDelegate(e.system,e.payload,t);return r.found?Q(r.value):$(`not-found`,`delegate handler for external system '${e.system}' reported no value`)}case`treeReference`:{if(n.resolveTree===void 0)return $(`wrong-type`,`no tree resolver registered for treeReference nodes`);let l=JSON.stringify(e.key);if(a.has(l))return $(`domain-error`,`circular treeReference detected`);if(o>=100)return $(`domain-error`,`treeReference chain exceeds the maximum depth of 100`);let u=await n.resolveTree(e.key,t);if(!u.found)return $(`not-found`,`treeReference key did not resolve to a tree`);let d=xk.safeParse(u.node);return d.success?gA(d.data,t,n,r,i,new Set([...a,l]),o+1,s,c+1):$(`wrong-type`,`the referenced tree is not a valid ExpressionNode`)}default:throw Error(`unreachable expression node kind`)}}function _A({functions:e=Sk,maxNodes:t=Ck,maxNestingDepth:n=500}){return{evaluatePredicate:async(r,i,a)=>hA(r,i,a,void 0,e,new Set,0,wk(t,n),0),evaluateValue:async(r,i,a)=>gA(r,i,a,void 0,e,new Set,0,wk(t,n),0)}}var{evaluatePredicate:vA,evaluateValue:yA}=_A({}),bA=TT(ok),xA=`bearer-is`,SA=`expires-at`,CA=`scope-narrows`,wA=`capability-is`,TA=`depth-remaining`,EA=[xA,SA,CA,wA,TA];function DA(e){return e===`bearer-is`||e===`expires-at`||e===`scope-narrows`||e===`capability-is`||e===`depth-remaining`}var OA=`grantee-is`,kA=`granted-capability-is`;function AA(e){return e===`grantee-is`||e===`granted-capability-is`}var jA={[OA]:(e,t)=>t.subject===void 0||typeof e!=`string`?{found:!1}:NA(dO(t.subject.bearer)===e),[kA]:(e,t)=>t.subject===void 0||typeof e!=`string`?{found:!1}:NA(t.subject.capability===e)};function MA(e,t){return{kind:`not`,operand:{kind:`and`,left:FA(kA,e),right:FA(OA,dO(t))}}}function NA(e){return{found:!0,value:{kind:`boolean`,value:e}}}var PA={[xA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(AO(t.parentClaims.bearer,t.childIssuer)),[SA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(t.candidate.expires<=t.parentClaims.expires),[CA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(NO(t.parentClaims.scope,t.candidate.scope)),[wA]:(e,t)=>t.parentClaims===void 0?NA(!1):NA(t.parentClaims.capability===t.candidate.capability),[TA]:(e,t)=>{if(t.parentClaims===void 0)return NA(!1);let n=t.parentClaims[`delegations-remaining`];return NA(n===void 0||t.candidate.delegationsRemaining!==void 0&&t.candidate.delegationsRemaining<n)}};function FA(e,t=null){return{kind:`compare`,op:`eq`,left:{kind:`delegate`,system:e,payload:t},right:{kind:`booleanLiteral`,value:!0}}}var IA=async()=>Promise.resolve({found:!1}),LA=async()=>Promise.resolve({found:!1}),RA=async()=>Promise.resolve([]);async function zA(e,t,n){let r={childIssuer:t,candidate:n,parentClaims:e},i={resolveValue:IA,resolveLookup:LA,resolveCollection:RA,resolveDelegate:async(e,t)=>DA(e)?PA[e](t,r):{found:!1}};for(let e of EA){let t=await vA(FA(e),r,i);if(t.status!==`definite`||!t.value)return e}}async function BA(e,t,n,r={},i){let a=i===void 0?{clock:n,claims:t}:{clock:n,claims:t,subject:i},o={resolveValue:IA,resolveLookup:LA,resolveCollection:RA,resolveDelegate:async(e,t)=>{if(i!==void 0&&AA(e))try{return await jA[e](t,a)}catch{return{found:!1}}let n=Object.hasOwn(r,e)?r[e]:void 0;if(n===void 0)return{found:!1};try{return await n(t,a)}catch{return{found:!1}}}};for(let t of e){let e=await vA(t,a,o);if(e.status!==`definite`||!e.value)return{ok:!1,reason:`not_satisfied`}}return{ok:!0}}var VA=`manage:grant`,HA=64;function UA(e,t){return Mg([`Signature1`,e,new Uint8Array,t],hg)}function WA(e){return Uint8Array.from(e)}function GA(e){return WA(Mg(e,hg))}function KA(e){return GA({1:e.identityKey.alg,4:e.deviceId})}function qA(e){let[,,t]=e;if(t===null)return;let n;try{n=b_(t,x_)}catch{return}let r=RD.safeParse(n);return r.success?r.data:void 0}async function JA(e,t){let n=await XA(e,{identity:t.identity,clock:t.clock,revocation:t.revocation,...t.extraPredicateResolvers===void 0?{}:{extraPredicateResolvers:t.extraPredicateResolvers}});return n.ok&&t.expectedBearer!==void 0&&!AO(n.claims.bearer,t.expectedBearer)?{ok:!1,reason:`bearer_mismatch`}:n}async function YA(e,t,n){if(AO(e.issuer,t.issuer))return!0;if(e.authorization===void 0)return!1;let r;try{r=b_(e.authorization,x_)}catch{return!1}let i=LD.safeParse(r);if(!i.success)return!1;let a=await JA(i.data,{...n,expectedBearer:e.issuer});return a.ok&&a.claims.capability===`manage:revoke`&&NO(a.claims.scope,t.scope)}async function XA(e,t,n,r=0,i=new Set){let[a,,o,s]=e;if(o===null)return{ok:!1,reason:`malformed`};if(r>=HA)return{ok:!1,reason:`chain_too_deep`};let c=uO(o);if(i.has(c))return{ok:!1,reason:`chain_cycle`};let l=new Set(i).add(c),u;try{u=b_(o,x_)}catch{return{ok:!1,reason:`malformed`}}let d=RD.safeParse(u);if(!d.success)return{ok:!1,reason:`malformed`};let f=d.data;if(!await t.identity.verify(f[`issuer-key`],UA(a,o),s))return{ok:!1,reason:`bad_signature`};if(!AO(await t.identity.deriveDeviceId(f[`issuer-key`][`public-key`]),f.issuer))return{ok:!1,reason:`wrong_issuer`};let p=t.clock.now();if(f.expires<=p)return{ok:!1,reason:`expired`};if(f[`not-before`]!==void 0&&f[`not-before`]>p)return{ok:!1,reason:`not_yet_valid`};let m=f[`valid-until`];if(m!==void 0&&m<=p)return{ok:!1,reason:`content_expired`};let h=await t.revocation.entriesFor(f[`token-id`]);for(let e of h)if(await YA(e,f,t))return{ok:!1,reason:`revoked`};if(f.conditions!==void 0){let e;try{e=b_(f.conditions,x_)}catch{return{ok:!1,reason:`conditions_invalid`}}let r=bA.safeParse(e);if(!r.success)return{ok:!1,reason:`conditions_invalid`};if(!(await BA(r.data,f,t.clock,t.extraPredicateResolvers,n)).ok)return{ok:!1,reason:`conditions_not_satisfied`}}let g=f.parent,_=f[`authorised-by`];if(f.capability===`manage:grant`&&g!==void 0)return{ok:!1,reason:`authorisation_invalid`};if(g!==void 0&&_!==void 0)return{ok:!1,reason:`malformed`};if(g!==void 0){let e;try{e=b_(g,x_)}catch{return{ok:!1,reason:`parent_invalid`}}let n=LD.safeParse(e);if(!n.success)return{ok:!1,reason:`parent_invalid`};let i=await XA(n.data,t,void 0,r+1,l);if(!i.ok)return i.reason===`chain_too_deep`||i.reason===`chain_cycle`?{ok:!1,reason:i.reason}:{ok:!1,reason:`parent_invalid`};let a={capability:f.capability,scope:f.scope,expires:f.expires,...f[`delegations-remaining`]===void 0?{}:{delegationsRemaining:f[`delegations-remaining`]}};return await zA(i.claims,f.issuer,a)===void 0?{ok:!0,claims:f,rootIssuer:i.rootIssuer,rootIssuerKey:i.rootIssuerKey,depth:i.depth+1}:{ok:!1,reason:`delegation_exceeds_parent`}}if(_!==void 0){let e;try{e=b_(_,x_)}catch{return{ok:!1,reason:`authorisation_invalid`}}let n=LD.safeParse(e);if(!n.success)return{ok:!1,reason:`authorisation_invalid`};let i=await XA(n.data,t,f,r+1,l);if(!i.ok)return i.reason===`chain_too_deep`||i.reason===`chain_cycle`?{ok:!1,reason:i.reason}:{ok:!1,reason:`authorisation_invalid`};let a=i.claims,o=a[`grants-capability`];return AO(a.bearer,f.issuer)&&a.capability===`manage:grant`&&(o===void 0||o===f.capability)&&NO(a.scope,f.scope)&&f.expires<=a.expires&&(a[`delegations-remaining`]===void 0||f[`delegations-remaining`]!==void 0&&f[`delegations-remaining`]<a[`delegations-remaining`])?{ok:!0,claims:f,rootIssuer:i.rootIssuer,rootIssuerKey:i.rootIssuerKey,depth:i.depth+1}:{ok:!1,reason:`authorisation_invalid`}}return{ok:!0,claims:f,rootIssuer:f.issuer,rootIssuerKey:f[`issuer-key`],depth:0}}async function ZA(e,t){let[n,,r,i]=e;if(r===null)return{ok:!1,reason:`malformed`};let a;try{a=b_(r,x_)}catch{return{ok:!1,reason:`malformed`}}let o=YE.safeParse(a);if(!o.success)return{ok:!1,reason:`malformed`};let s=o.data;return await t.identity.verify(s[`issuer-key`],UA(n,r),i)?AO(await t.identity.deriveDeviceId(s[`issuer-key`][`public-key`]),s.issuer)?{ok:!0,claims:s}:{ok:!1,reason:`wrong_issuer`}:{ok:!1,reason:`bad_signature`}}var QA={"bearer-is":`parent_bearer_mismatch`,"expires-at":`expires_exceeds_parent`,"scope-narrows":`scope_does_not_narrow`,"capability-is":`capability_mismatch`,"depth-remaining":`delegation_exceeds_parent`};async function $A(e,t,n){let r=await zA(e,t,n);return r===void 0?void 0:QA[r]}async function ej(e,t,n){if(e.parent!==void 0)return`authorisation_parent_forbidden`;if(!AO(e.bearer,t))return`authorisation_bearer_mismatch`;let r=e[`grants-capability`];if(e.capability!==`manage:grant`||r!==void 0&&r!==n.capability)return`authorisation_capability_mismatch`;if(!NO(e.scope,n.scope))return`authorisation_scope_does_not_narrow`;if(n.expires>e.expires)return`authorisation_exceeds_authoriser`;let i=e[`delegations-remaining`];if(i!==void 0&&(n.delegationsRemaining===void 0||n.delegationsRemaining>=i))return`authorisation_delegation_exceeds`;if(e.conditions!==void 0){let t;try{t=b_(e.conditions,x_)}catch{return`authorisation_malformed`}let r=bA.safeParse(t);if(!r.success)return`authorisation_malformed`;if(!(await BA(r.data,e,{now:()=>0},{},n)).ok)return`authorisation_conditions_not_satisfied`}}async function tj(e){if(e.expires<=e.clock.now())return{ok:!1,reason:`already_expired`};if(e.parent!==void 0&&e.authorisedBy!==void 0)return{ok:!1,reason:`links_exclusive`};if(e.capability===`manage:grant`&&e.parent!==void 0)return{ok:!1,reason:`authorisation_parent_forbidden`};let t;if(e.parent!==void 0){let n=qA(e.parent);if(n===void 0)return{ok:!1,reason:`parent_malformed`};let r=await $A(n,e.identity.deviceId,{capability:e.capability,scope:e.scope,expires:e.expires,...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining}});if(r!==void 0)return{ok:!1,reason:r};t=GA(e.parent)}let n;if(e.authorisedBy!==void 0){let t=qA(e.authorisedBy);if(t===void 0)return{ok:!1,reason:`authorisation_malformed`};let r=await ej(t,e.identity.deviceId,{capability:e.capability,scope:e.scope,bearer:e.bearer,expires:e.expires,...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining}});if(r!==void 0)return{ok:!1,reason:r};n=GA(e.authorisedBy)}let r=GA({"token-id":e.tokenId,issuer:e.identity.deviceId,"issuer-key":e.identity.identityKey,bearer:e.bearer,capability:e.capability,scope:e.scope,expires:e.expires,...e.notBefore===void 0?{}:{"not-before":e.notBefore},...t===void 0?{}:{parent:t},...e.delegationsRemaining===void 0?{}:{"delegations-remaining":e.delegationsRemaining},...e.conditions===void 0?{}:{conditions:GA(e.conditions)},...n===void 0?{}:{"authorised-by":n},...e.grantsCapability===void 0?{}:{"grants-capability":e.grantsCapability},...e.requestsCapability===void 0?{}:{"requests-capability":e.requestsCapability}}),i=KA(e.identity);return{ok:!0,token:[i,{},r,await e.identity.sign(UA(i,r))]}}async function nj(e){let t=GA({"token-id":e.tokenId,issuer:e.identity.deviceId,"issuer-key":e.identity.identityKey,"revoked-at":e.revokedAt}),n=KA(e.identity);return[n,{},t,await e.identity.sign(UA(n,t))]}var rj=`wm-grant1.`;function ij(e){let t=e[2];if(t===null)return;let n;try{n=b_(t,x_)}catch{return}let r=RD.safeParse(n);return r.success?r.data:void 0}function aj(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function oj(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function sj(e){return rj+aj(Mg(e,hg))}function cj(e){let t=e.trim();if(!t.startsWith(`wm-grant1.`))throw Error(`a grant code starts with "${rj}"`);let n;try{n=b_(oj(t.slice(10)),x_)}catch{throw Error(`the grant code is damaged: it does not decode`)}let r=LD.safeParse(n);if(!r.success||ij(r.data)===void 0)throw Error(`the grant code does not carry a capability token`);return r.data}async function lj(e,t){let n=await JA(e,t);return n.ok?{kind:`valid`}:{kind:`invalid`,reason:n.reason}}var uj={malformed:`malformed`,bad_signature:`signature does not verify`,wrong_issuer:`issuer does not match its key`,bearer_mismatch:`names another bearer`,expired:`expired`,not_yet_valid:`not valid yet`,content_expired:`content expired`,revoked:`revoked`,delegation_exceeds_parent:`exceeds what its parent allows`,parent_invalid:`its parent grant is no longer valid`,conditions_invalid:`its conditions are invalid`,conditions_not_satisfied:`its conditions are not met`,authorisation_invalid:`exceeds what its authorising grant allows`,chain_too_deep:`its chain is deeper than allowed`,chain_cycle:`its chain revisits a token`};function dj(e){return e.kind===`valid`?`valid`:uj[e.reason]}var fj=`grant/`;function pj(e,t){return`${fj}${e}/${t}`}function mj(e){let t=e.slice(6).split(`/`)[0];if(t===`held`||t===`issued`)return t;throw Error(`stored grant key ${e} names no direction`)}function hj(e){return typeof e==`object`&&!!e&&`token`in e&&`recordedAt`in e&&typeof e.recordedAt==`number`}function gj(e){let t=new Set;return{async record(n,r,i){let a=ij(r);if(a===void 0)throw Error(`a grant must carry readable token claims`);let o=pj(n,uO(a[`token-id`]));if(await e.get(o)===void 0){await e.set(o,new Uint8Array(Mg({token:r,recordedAt:i},hg)));for(let e of t)e()}},async list(){let t=[];for(let n of await e.keys(fj)){let r=await e.get(n);if(r===void 0)continue;let i=b_(r,x_);if(!hj(i))throw Error(`stored grant at ${n} is malformed`);let a=LD.safeParse(i.token);if(!a.success)throw Error(`stored grant at ${n} is malformed`);let o=ij(a.data);if(o===void 0)throw Error(`stored grant at ${n} has unreadable claims`);t.push({tokenId:uO(o[`token-id`]),direction:mj(n),token:a.data,claims:o,recordedAt:i.recordedAt})}return t.sort((e,t)=>t.recordedAt-e.recordedAt)},subscribe(e){return t.add(e),()=>{t.delete(e)}}}}function _j(e){return uO(e)}function vj(){let e=new Map;return{async entriesFor(t){return Promise.resolve(e.get(_j(t))??[])},async record(t,n){let r=await ZA(t,n);if(r.ok){let t=_j(r.claims[`token-id`]),n=e.get(t);n===void 0?e.set(t,[r.claims]):n.push(r.claims)}return r}}}var yj=`revocation/`;async function bj(e,t,n){let r;try{r=b_(n,x_)}catch{return`it is not valid CBOR`}let i=XE.safeParse(r);if(!i.success)return`it is not a revocation entry`;let a=await e.record(i.data,{identity:t});return a.ok?void 0:`it no longer verifies (${a.reason})`}async function xj(e){let{storage:t,identity:n,clock:r}=e,i=vj(),a=new Set;async function o(e){let r=await i.record(e,{identity:n});if(r.ok){let n=`${yj}${uO(r.claims.issuer)}/${uO(r.claims[`token-id`])}`;await t.set(n,new Uint8Array(Mg(e,hg)));for(let e of a)e()}return r}let s=[];for(let e of await t.keys(yj)){let r=await t.get(e);if(r===void 0)continue;let a=await bj(i,n,r);a!==void 0&&(s=[...s,{key:e,reason:a}])}return{view:i,unreadable:()=>s,async discardUnreadable(e){await t.delete(e),s=s.filter(t=>t.key!==e);for(let e of a)e()},subscribe(e){return a.add(e),()=>{a.delete(e)}},ingest:o,async revoke(e){let t=await nj({identity:n,tokenId:e,revokedAt:r.now()}),i=await o(t);if(!i.ok)throw Error(`the revocation this device signed does not verify (${i.reason})`);return t}}}var Sj=`preferences/intro-dismissed`,Cj=new Uint8Array([1]);function wj(e){return{async introDismissed(){return await e.get(Sj)!==void 0},async setIntroDismissed(t){t?await e.set(Sj,new Uint8Array(Cj)):await e.delete(Sj)}}}var Tj=`agent/self`,Ej=`wire-mesh-console`;function Dj(e){return e.slice(0,12)}var Oj=/[\p{Cc}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;function kj(e){let t=e.replace(Oj,``).trim();if(t!==``)return Array.from(t).slice(0,64).join(``).trimEnd()}function Aj(e){let t=e[Tj];if(typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`)return kj(t.name)}function jj(e){return{[Tj]:{name:e,harness:Ej}}}function Mj(e,t,n,r){return t===void 0?n===void 0?{primary:Dj(e),secondary:void 0,source:`id`,matchesPetname:!1}:{primary:n,secondary:Dj(e),source:`self`,matchesPetname:r.has(n)}:{primary:t,secondary:n!==void 0&&n!==t?n:void 0,source:`petname`,matchesPetname:!1}}function Nj(e){return e.source===`self`&&e.secondary!==void 0?`${e.primary} (${e.secondary})`:e.primary}var Pj=`petname/`,Fj=`self-name`,Ij=new TextEncoder,Lj=new TextDecoder;function Rj(e){async function t(t,n){let r=kj(n);if(r===void 0){await e.delete(t);return}await e.set(t,new Uint8Array(Ij.encode(r)))}return{async petnames(){let t=new Map;for(let n of await e.keys(Pj)){let r=await e.get(n);r!==void 0&&t.set(n.slice(8),Lj.decode(r))}return t},async setPetname(e,n){await t(Pj+e,n)},async selfName(){let t=await e.get(Fj);return t===void 0?void 0:Lj.decode(t)},async setSelfName(e){await t(Fj,e)}}}var zj=String(2**53-1).length,Bj=`message`;function Vj(e,t){return`${Bj}/${e}/${String(t.sentAt).padStart(zj,`0`)}-${uO(t.messageId)}`}function Hj(e){let t=e.slice(`${Bj}/`.length);return t.slice(0,t.lastIndexOf(`/`))}function Uj(e){return e===`sent`||e===`received`}function Wj(e){return typeof e!=`object`||!e||!(`direction`in e)||!(`text`in e)||!(`messageId`in e)||!(`sentAt`in e)?!1:Uj(e.direction)&&typeof e.text==`string`&&e.messageId instanceof Uint8Array&&typeof e.sentAt==`number`}function Gj(e){return{async append(t,n){await e.set(Vj(t,n),new Uint8Array(Mg(n,hg)))},async roomPaths(){let t=await e.keys(`${Bj}/`);return[...new Set(t.map(Hj))]},async list(t){let n=(await e.keys(`${Bj}/${t}/`)).sort(),r=[];for(let t of n){let n=await e.get(t);if(n===void 0)continue;let i=b_(n,x_);if(!Wj(i))throw Error(`stored message at ${t} is malformed`);r.push(i)}return r}}}function Kj(e){return new Uint8Array(Mg(e,hg))}function qj(e,t){return{type:`relay-data`,payload:Kj(e),...t===void 0?{}:{"to-device":t}}}var Jj=class extends Error{constructor(e){super(e),this.name=`SchemaInvalidFrameError`}};function Yj(e){let t=b_(new Uint8Array(e),x_),n=ME.safeParse(t);if(!n.success)throw new Jj(n.error.message);return n.data}function Xj(e){let t;try{t=b_(e,x_)}catch{return null}let n=ME.safeParse(t);return n.success?n.data:null}var Zj=`signature`,Qj=`identity-key`,$j=new TextEncoder().encode(`wire-mesh/peer-advert/v1\0`);function eM(e){let t={};for(let[n,r]of Object.entries(e))n!==`signature`&&(t[n]=r);let n=Mg(t,hg),r=new Uint8Array($j.length+n.length);return r.set($j,0),r.set(n,$j.length),r}async function tM(e,t){let n=await e.sign(eM(t));return{...t,[Zj]:n}}async function nM(e,t){let n=t[Qj];try{return AO(await e.deriveDeviceId(n[`public-key`]),t.device)?await e.verify(n,eM(t),t[Zj]):!1}catch{return!1}}var rM={name:`wire-mesh-core`,version:`4.0.1`,dependencies:{cbor2:`2.3.0`,"cddl.js":`1.0.1`,trilean:`1.6.2`,zod:`4.5.4`},devDependencies:{"@arethetypeswrong/cli":`0.18.5`,"@exadev/eslint-config":`2.18.0`,"@stryker-mutator/api":`10.0.0`,"@stryker-mutator/core":`10.0.0`,"@stryker-mutator/typescript-checker":`10.0.0`,"@types/node":`26.4.1`,eslint:`10.10.0`,"eslint-config-prettier":`10.1.8`,"eslint-plugin-prettier":`5.5.6`,globals:`17.12.0`,jiti:`2.7.0`,prettier:`3.9.6`,tsdown:`0.23.0`,turbo:`2.10.12`,typescript:`6.0.3`,vitest:`5.0.0`},exports:{"./adapters/byte-stream-connection":{import:`./dist/adapters/byte-stream-connection.mjs`,require:`./dist/adapters/byte-stream-connection.cjs`},"./adapters/frame-codec":{import:`./dist/adapters/frame-codec.mjs`,require:`./dist/adapters/frame-codec.cjs`},"./adapters/memory-storage":{import:`./dist/adapters/memory-storage.mjs`,require:`./dist/adapters/memory-storage.cjs`},"./adapters/node-fs-storage":{import:`./dist/adapters/node-fs-storage.mjs`,require:`./dist/adapters/node-fs-storage.cjs`},"./adapters/node-identity":{import:`./dist/adapters/node-identity.mjs`,require:`./dist/adapters/node-identity.cjs`},"./adapters/system-clock":{import:`./dist/adapters/system-clock.mjs`,require:`./dist/adapters/system-clock.cjs`},"./adapters/tcp-transport":{import:`./dist/adapters/tcp-transport.mjs`,require:`./dist/adapters/tcp-transport.cjs`},"./adapters/threshold-identity":{import:`./dist/adapters/threshold-identity.mjs`,require:`./dist/adapters/threshold-identity.cjs`},"./adapters/threshold-wasm":{import:`./dist/adapters/threshold-wasm.mjs`,require:`./dist/adapters/threshold-wasm.cjs`},"./adapters/tls-transport":{import:`./dist/adapters/tls-transport.mjs`,require:`./dist/adapters/tls-transport.cjs`},"./domain/advert-extension-policy":{import:`./dist/domain/advert-extension-policy.mjs`,require:`./dist/domain/advert-extension-policy.cjs`},"./domain/async-queue":{import:`./dist/domain/async-queue.mjs`,require:`./dist/domain/async-queue.cjs`},"./domain/bulk":{import:`./dist/domain/bulk.mjs`,require:`./dist/domain/bulk.cjs`},"./domain/capability-grant":{import:`./dist/domain/capability-grant.mjs`,require:`./dist/domain/capability-grant.cjs`},"./domain/capability-request":{import:`./dist/domain/capability-request.mjs`,require:`./dist/domain/capability-request.cjs`},"./domain/coordinator-election":{import:`./dist/domain/coordinator-election.mjs`,require:`./dist/domain/coordinator-election.cjs`},"./domain/data-sync":{import:`./dist/domain/data-sync.mjs`,require:`./dist/domain/data-sync.cjs`},"./domain/device-id":{import:`./dist/domain/device-id.mjs`,require:`./dist/domain/device-id.cjs`},"./domain/direct-manage-request":{import:`./dist/domain/direct-manage-request.mjs`,require:`./dist/domain/direct-manage-request.cjs`},"./domain/erasure-coding":{import:`./dist/domain/erasure-coding.mjs`,require:`./dist/domain/erasure-coding.cjs`},"./domain/gossip-expansion":{import:`./dist/domain/gossip-expansion.mjs`,require:`./dist/domain/gossip-expansion.cjs`},"./domain/gossip-extensions":{import:`./dist/domain/gossip-extensions.mjs`,require:`./dist/domain/gossip-extensions.cjs`},"./domain/grant-candidates":{import:`./dist/domain/grant-candidates.mjs`,require:`./dist/domain/grant-candidates.cjs`},"./domain/group-key":{import:`./dist/domain/group-key.mjs`,require:`./dist/domain/group-key.cjs`},"./domain/handshake":{import:`./dist/domain/handshake.mjs`,require:`./dist/domain/handshake.cjs`},"./domain/hub-mailbox":{import:`./dist/domain/hub-mailbox.mjs`,require:`./dist/domain/hub-mailbox.cjs`},"./domain/mesh-session":{import:`./dist/domain/mesh-session.mjs`,require:`./dist/domain/mesh-session.cjs`},"./domain/notice-board":{import:`./dist/domain/notice-board.mjs`,require:`./dist/domain/notice-board.cjs`},"./domain/path-trace":{import:`./dist/domain/path-trace.mjs`,require:`./dist/domain/path-trace.cjs`},"./domain/peer-advert":{import:`./dist/domain/peer-advert.mjs`,require:`./dist/domain/peer-advert.cjs`},"./domain/ping-round-trips":{import:`./dist/domain/ping-round-trips.mjs`,require:`./dist/domain/ping-round-trips.cjs`},"./domain/pinned-address":{import:`./dist/domain/pinned-address.mjs`,require:`./dist/domain/pinned-address.cjs`},"./domain/relay-advert":{import:`./dist/domain/relay-advert.mjs`,require:`./dist/domain/relay-advert.cjs`},"./domain/relay-hub":{import:`./dist/domain/relay-hub.mjs`,require:`./dist/domain/relay-hub.cjs`},"./domain/relay-use-gate":{import:`./dist/domain/relay-use-gate.mjs`,require:`./dist/domain/relay-use-gate.cjs`},"./domain/revocation-view":{import:`./dist/domain/revocation-view.mjs`,require:`./dist/domain/revocation-view.cjs`},"./domain/room":{import:`./dist/domain/room.mjs`,require:`./dist/domain/room.cjs`},"./domain/room-path":{import:`./dist/domain/room-path.mjs`,require:`./dist/domain/room-path.cjs`},"./domain/room-rekey":{import:`./dist/domain/room-rekey.mjs`,require:`./dist/domain/room-rekey.cjs`},"./domain/room-token-verification":{import:`./dist/domain/room-token-verification.mjs`,require:`./dist/domain/room-token-verification.cjs`},"./domain/shard-manifest":{import:`./dist/domain/shard-manifest.mjs`,require:`./dist/domain/shard-manifest.cjs`},"./domain/threshold-subject":{import:`./dist/domain/threshold-subject.mjs`,require:`./dist/domain/threshold-subject.cjs`},"./domain/token-predicates":{import:`./dist/domain/token-predicates.mjs`,require:`./dist/domain/token-predicates.cjs`},"./domain/token-scope":{import:`./dist/domain/token-scope.mjs`,require:`./dist/domain/token-scope.cjs`},"./domain/tokens":{import:`./dist/domain/tokens.mjs`,require:`./dist/domain/tokens.cjs`},"./domain/topology":{import:`./dist/domain/topology.mjs`,require:`./dist/domain/topology.cjs`},"./domain/topology-snapshot":{import:`./dist/domain/topology-snapshot.mjs`,require:`./dist/domain/topology-snapshot.cjs`},"./domain/webrtc-signaling":{import:`./dist/domain/webrtc-signaling.mjs`,require:`./dist/domain/webrtc-signaling.cjs`},"./generated/protocol":{import:`./dist/generated/protocol.mjs`,require:`./dist/generated/protocol.cjs`},"./generated/runtime":{import:`./dist/generated/runtime.mjs`,require:`./dist/generated/runtime.cjs`},"./ports/clock":{import:`./dist/ports/clock.mjs`,require:`./dist/ports/clock.cjs`},"./ports/identity":{import:`./dist/ports/identity.mjs`,require:`./dist/ports/identity.cjs`},"./ports/storage":{import:`./dist/ports/storage.mjs`,require:`./dist/ports/storage.cjs`},"./ports/transport":{import:`./dist/ports/transport.mjs`,require:`./dist/ports/transport.cjs`},"./package.json":`./package.json`},files:[`dist`,`wasm-dist`],license:`MIT`,packageManager:`pnpm@12.4.1+sha512.2e81e399d73fe8390dab25e06aa788ab7a5908248d2f5a370f82b481147a6a7a367bf8048f9a6fdb6460f21a66f0542dedb8b94ca2c8723596741920b1656d4c`,publishConfig:{provenance:!0,access:`public`},repository:{type:`git`,url:`https://github.com/ExaDev/wire-mesh.git`,directory:`ts/packages/core`},scripts:{_build:`tsdown`,"_build-wasm":`./scripts/build-threshold-wasm.sh`,"_conformance-check":`vitest run test/conformance.unit.test.ts`,_generate:`node generate.ts`,_lint:`eslint . --fix --cache --max-warnings 0`,_mutation:`stryker run stryker.config.ts`,_test:`vitest run`,_typecheck:`tsc -p tsconfig.json --noEmit && tsc -p tsconfig.node.json --noEmit`,build:`turbo run _build`,"build-wasm":`turbo run _build-wasm`,"conformance-check":`turbo run _conformance-check`,generate:`turbo run _generate`,lint:`turbo run _lint`,mutation:`turbo run _mutation`,prepack:`node scripts/assert-wasm-dist.ts`,test:`turbo run _test`,typecheck:`turbo run _typecheck`},type:`module`}.version,iM=`wire-mesh/version`,aM=`version.get`;function oM(e){return`verb`in e&&e.verb===aM}function sM(){return{result:`ok`,version:rM}}var cM=new Set([`device`,`addresses`,`snapshot-seconds`,Qj,Zj]),lM=`topology/peers`,uM=/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;function dM(e){for(let t of Object.keys(e)){if(cM.has(t))throw Error(`sendGossipUpdate extension key "${t}" collides with a mandatory peer-advert field`);if(t===`topology/peers`)throw Error(`sendGossipUpdate extension key "${t}" collides with a session-managed gossip field`);if(t===`wire-mesh/version`)throw Error(`sendGossipUpdate extension key "${t}" is reserved for wire-mesh-core's own self-reported version`);if(!uM.test(t))throw Error(`sendGossipUpdate extension key "${t}" must be domain-qualified as "<domain>/<field>" (e.g. "presence/status")`)}}function fM(){let e=[],t=[];return{push(n){let r=e.shift();r===void 0?t.push(n):r(n)},stream:{[Symbol.asyncIterator](){return{next:async()=>new Promise(n=>{let r=t.shift();r===void 0?e.push(e=>{n({value:e,done:!1})}):n({value:r,done:!1})})}}}}}var pM=[`core/federation`];function mM(e,t){let n=Math.min(e.version,t.version),r=e.domains.filter(e=>!pM.includes(e)&&t.domains.includes(e));return{ok:n>=1&&r.length>0,version:n,sharedDomains:r}}function hM(e){return`data/${dO(e)}/head`}function gM(e,t){return`data/${dO(e)}/entry/${String(t)}`}async function _M(e,t){let n=await e.get(hM(t));return n===void 0?0:Number(new TextDecoder().decode(n))}async function vM(e,t,n){await e.set(hM(t),new TextEncoder().encode(String(n)))}async function yM(e,t){return _M(e,t)}async function bM(e,t){let n=await _M(e.storage,e.identity.deviceId)+1;return await e.storage.set(gM(e.identity.deviceId,n),t),await vM(e.storage,e.identity.deviceId,n),{seq:n,haveFrame:{type:`data-have`,peer:e.identity.deviceId,"head-seq":n}}}async function xM(e,t,n){let r=await _M(e,t.peer);if(r<=t[`from-seq`])return null;let i=Math.min(r,t[`from-seq`]+n),a=[];for(let n=t[`from-seq`]+1;n<=i;n+=1){let r=await e.get(gM(t.peer,n));if(r===void 0)break;a.push(r)}return a.length===0?null:{type:`data-entries`,peer:t.peer,"from-seq":t[`from-seq`],entries:a}}async function SM(e,t){let n=await _M(e,t.peer);if(t[`from-seq`]!==n)return{ok:!1,reason:`gap`};let r=t[`from-seq`];for(let n of t.entries)r+=1,await e.set(gM(t.peer,r),n);return await vM(e,t.peer,r),{ok:!0}}async function CM(e,t,n){let r=await _M(e,t),i=[];for(let a=n+1;a<=r;a+=1){let n=await e.get(gM(t,a));if(n===void 0)break;i.push(n)}return i}function wM(e){return e.type===`data-have`||e.type===`data-request`||e.type===`data-entries`}var TM=class extends Error{constructor(){super(`timed out waiting for pong`),this.name=`PingTimeoutError`}};function EM(){let e=[];function t(t){let n=e.findIndex(e=>e.sentAt===t);return n!==-1&&(e.splice(n,1),!0)}return{resolveOldest(t){let n=e.shift();n!==void 0&&n.resolve(t-n.sentAt)},rejectAll(t){for(let n of e.splice(0))n.reject(Error(t))},async sendAndAwait(n,r,i){let a=new Promise((t,r)=>{e.push({sentAt:n,resolve:t,reject:r})});return await r(),i===void 0?a:Promise.race([a,new Promise((e,r)=>{setTimeout(()=>{t(n)&&r(new TM)},i)})])}}}function DM(e){return e.authenticatedPeer===void 0?e.isAccepted?e.firstAdvertisedPeer??void 0:void 0:e.authenticatedPeer}function OM(e){let t=DM(e);return{direct:t===void 0?[]:[t],relayed:e.relayedDevices.map(e=>({device:e,...t===void 0?{}:{via:t}}))}}function kM(e){let t=null;return{recordAdvert:e=>{t??=e},compute:()=>{let n=e.getAuthenticatedPeer();return OM({...n===void 0?{}:{authenticatedPeer:n},firstAdvertisedPeer:t,isAccepted:e.isAccepted,relayedDevices:e.getRelayedDevices()})}}}function AM(){let e=new Map;return{has:t=>e.has(dO(t)),add:t=>{e.set(dO(t),t)},remove:t=>{e.delete(dO(t))},clear:()=>{e.clear()},list:()=>[...e.values()]}}var jM=16,MM=256,NM=256,PM=12,FM=4,IM=8,LM=new TextEncoder,RM=LM.encode(`wire-mesh/secure-hello/v1\0`),zM=LM.encode(`wire-mesh/secure-channel/v1\0`),BM=LM.encode(`wire-mesh/secure-data/v1\0`),VM=LM.encode(`lo-to-hi`),HM=LM.encode(`hi-to-lo`),UM={name:`ECDH`,namedCurve:`P-256`};function WM(...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}function GM(e,t){for(let n=0;n<Math.min(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return e.length-t.length}function KM(e){let t=new Uint8Array(IM);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function qM(e,t,n,r){return WM(RM,e,t,n,r)}async function JM(e,t){let n=await crypto.subtle.generateKey(UM,!1,[`deriveBits`]),r=new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)),i=crypto.getRandomValues(new Uint8Array(jM)),a=await e.sign(qM(r,i,e.deviceId,t));return{peer:t,privateKey:n.privateKey,hello:{type:`secure-hello`,"ephemeral-key":r,nonce:i,"identity-key":e.identityKey,"to-device":t,signature:a}}}async function YM(e,t){let n=t[`identity-key`];try{let r=await e.deriveDeviceId(n[`public-key`]);return AO(t[`to-device`],e.deviceId)?await e.verify(n,qM(t[`ephemeral-key`],t.nonce,r,e.deviceId),t.signature)?{ok:!0,peer:{deviceId:r,identityKey:n}}:{ok:!1,reason:`bad_signature`}:{ok:!1,reason:`wrong_recipient`}}catch{return{ok:!1,reason:`identity_mismatch`}}}function XM(e){let t=new Uint8Array(PM);return t.set(KM(e),FM),t}function ZM(e,t,n){return WM(BM,e,t,KM(n))}async function QM(e,t,n,r,i){let a=await crypto.subtle.importKey(`raw`,Uint8Array.from(e),`HKDF`,!1,[`deriveKey`]);return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:Uint8Array.from(t),info:WM(zM,n,r,i)},a,{name:`AES-GCM`,length:MM},!1,[`encrypt`,`decrypt`])}async function $M(e,t,n,r){let i;try{let e=await crypto.subtle.importKey(`raw`,Uint8Array.from(n[`ephemeral-key`]),UM,!1,[]);i=new Uint8Array(await crypto.subtle.deriveBits({name:`ECDH`,public:e},t.privateKey,NM))}catch{return}let a=GM(e.deviceId,r.deviceId)<0,o=a?e.deviceId:r.deviceId,s=a?r.deviceId:e.deviceId,c=WM(a?t.hello.nonce:n.nonce,a?n.nonce:t.hello.nonce),l=await QM(i,c,o,s,VM),u=await QM(i,c,o,s,HM),d=a?l:u,f=a?u:l,p=0,m=-1,h=Promise.resolve(),g=Promise.resolve();async function _(t,n){return{type:`secure-data`,counter:n,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:XM(n),additionalData:ZM(e.deviceId,r.deviceId,n)},d,Kj(t)))}}async function v(t){if(t.counter<=m)return;let n;try{n=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:XM(t.counter),additionalData:ZM(r.deviceId,e.deviceId,t.counter)},f,Uint8Array.from(t.ciphertext)))}catch{return}return m=t.counter,Xj(n)??void 0}return{peer:r,seal:async e=>{let t=p;p+=1;let n=h.then(async()=>_(e,t));return h=n.catch(()=>void 0),n},open:async e=>{let t=g.then(async()=>v(e));return g=t.catch(()=>void 0),t}}}function eN(e,t){let n=new Map;function r(r){let i=dO(r),a=Promise.withResolvers(),o=JM(e,r),s={status:`awaiting`,pending:o,settle:a};return n.set(i,s),o.then(async({hello:e})=>t(r,e)).catch(e=>{a.reject(e instanceof Error?e:Error(String(e))),n.get(i)===s&&n.delete(i)}),s}return{ensure:async e=>{let t=n.get(dO(e));return t?.status===`established`?t.channel:(t??r(e)).settle.promise},applyHello:async t=>{let i=await YM(e,t);if(!i.ok)return;let a=dO(i.peer.deviceId),o=n.get(a),s=o?.status===`awaiting`?o:r(i.peer.deviceId),c=await $M(e,await s.pending,t,i.peer);if(c===void 0){s.settle.reject(Error(`the peer sent an unusable ephemeral key`)),n.get(a)===s&&n.delete(a);return}n.set(a,{status:`established`,channel:c}),s.settle.resolve(c)},open:async(e,t)=>{if(t===void 0)return;let r=n.get(dO(t));if(r?.status!==`established`)return;let i=await r.channel.open(e);return i===void 0?void 0:{frame:i,from:r.channel.peer.deviceId}},reset:e=>{for(let t of n.values())t.status===`awaiting`&&t.settle.reject(Error(e));n.clear()},forget:e=>{let t=dO(e),r=n.get(t);r?.status===`awaiting`&&r.settle.reject(Error(`the relay pairing was lost`)),n.delete(t)}}}var tN=1e3,nN=3e3;function rN(e){return{type:`handshake`,version:1,domains:[...e]}}function iN(e,t,n,r,i,a=[],o,s){let c=null,l={status:`idle`},u={status:`pending`},d=new Map,f=[];function p(e){f.push(e),f.length>256&&f.splice(0,f.length-256)}let m=!1,h=fM(),g=null,_=null,v=0,y=null,b=0,x=AM(),S=kM({getAuthenticatedPeer:()=>c?.peerDeviceId,isAccepted:r===null,getRelayedDevices:()=>x.list()}),C=new Map,w=eN(e,async(e,t)=>{if(c===null)throw Error(`not connected`);p({direction:`sent`,frame:t}),await c.send(qj(t,e)),j()}),T=fM(),E=fM(),D=fM(),O=fM(),k=EM();function A(){return{state:l,directory:[...d.values()],frameLog:[...f]}}function j(){h.push(A())}function M(e){for(let t of C.values())t.reject(Error(e));C.clear()}function N(e,t,n){let r=b;b+=1;let i=n??y;return{type:`manage-request`,"request-id":r,command:e,scope:t,...i===null?{}:{token:i}}}function ee(){if(c===null||l.status!==`connected`)throw Error(`not connected`);return c}async function P(e,t,n){if(c===null)throw Error(`not connected`);if(!t){await c.send(e);return}if(n===void 0)throw Error(`a relayed frame needs the device it is for`);let r=await(await w.ensure(n)).seal(e);await c.send(qj(r,n))}function F(e,t){let n=e[`request-id`],r=C.get(n);if(r===void 0)return;let i=r.expectedFrom;(i===void 0?t===void 0:t!==void 0&&dO(t)===dO(i))&&(C.delete(n),r.resolve(e.outcome))}function I(e,t){let n=e[`request-id`],r=t?.fromDevice,i=t?.toDevice,a={requestId:n,command:e.command,scope:e.scope,...e.token===void 0?{}:{token:e.token},...r===void 0?{}:{fromDevice:r},...i===void 0?{}:{toDevice:i},respond:async e=>{let i={type:`manage-response`,"request-id":n,outcome:e};p({direction:`sent`,frame:i}),await P(i,t!==void 0,r),j()}};if(oM(e.command.params)){a.respond(sM());return}T.push(a)}async function te(n){if(n.type===`relay-data`){let e=Xj(n.payload);if(e?.type===`secure-hello`){p({direction:`received`,frame:e}),await w.applyHello(e);return}if(e?.type===`secure-data`){let t=await w.open(e,n[`from-device`]);t?.frame.type===`manage-response`?(p({direction:`received`,frame:t.frame}),F(t.frame,t.from)):t!==void 0&&wM(t.frame)?(p({direction:`received`,frame:t.frame}),O.push({frame:t.frame,fromDevice:t.from,...n[`to-device`]===void 0?{}:{toDevice:n[`to-device`]}})):t?.frame.type===`manage-request`&&(p({direction:`received`,frame:t.frame}),I(t.frame,{fromDevice:t.from,...n[`to-device`]===void 0?{}:{toDevice:n[`to-device`]}}));return}p({direction:`received`,frame:n});return}if(p({direction:`received`,frame:n}),n.type===`handshake`)ie(n);else if(n.type===`gossip`)for(let t of n.peers)await nM(e,t)&&(d.set(dO(t.device),{device:t.device,advert:t}),S.recordAdvert(t.device),i?.(t));else if(n.type===`relay-inbound`)x.add(n[`source-device`]);else if(n.type===`manage-response`)F(n);else if(n.type===`manage-request`)I(n);else if(n.type===`pong`)k.resolveOldest(t.now());else if(n.type===`revocation-announce`)for(let e of n.entries)E.push(e);else wM(n)?O.push({frame:n}):n.type===`coordinator`&&D.push(n)}async function ne(e){if(c===null)throw Error(`not connected`);if(x.has(e))return;let t={type:`relay-connect`,"target-device":e};p({direction:`sent`,frame:t}),await c.send(t),x.add(e),j()}let re=rN([]);function ie(e){if(u.status!==`pending`)return;g!==null&&(clearTimeout(g),g=null);let t=mM(re,e);u=t.ok?{status:`negotiated`,version:t.version,sharedDomains:t.sharedDomains}:{status:`rejected`,reason:`no shared domains or version`},l.status===`connected`&&(l={...l,handshake:u})}function L(e,t){return e.redialAddress?.()??t}function R(e,t,r){if(!m){if(M(`disconnected before a response arrived`),k.rejectAll(`disconnected before a pong arrived`),n!==null&&v<n.maxAttempts){v+=1;let i=v;l={status:`reconnecting`,address:t,attempt:i,reason:e},j(),_=setTimeout(()=>{_=null,ce(t,r).catch(e=>{R(e instanceof Error?e.message:String(e),t,r)})},n.delayMs(i));return}l={status:`closed`,address:t,reason:e},j()}}async function ae(e,t,n){let r=!1;for await(let t of e.receive()){if(m)return;r||(r=!0,v=0),await te(t),await o?.(e,t),j()}s?.(e),l.status===`connected`&&R(`node closed the connection`,L(e,t),n)}async function oe(n){return n!==void 0&&dM(n),{type:`gossip`,peers:[await tM(e,{...n,[iM]:rM,[lM]:S.compute(),device:e.deviceId,addresses:[...a],"snapshot-seconds":Math.floor(t.now()/tN),"identity-key":e.identityKey})]}}async function se(e,t,n){c=e,w.reset(`the connection changed before the channel was ready`),x.clear(),re=rN(n),u={status:`pending`},l={status:`connected`,address:t,handshake:u},p({direction:`sent`,frame:re}),await c.send(re),j();let r=await oe();p({direction:`sent`,frame:r}),await c.send(r),j(),g=setTimeout(()=>{g=null,u.status===`pending`&&(u={status:`unanswered`},l.status===`connected`&&(l={...l,handshake:u}),j())},nN),ae(c,t,n).catch(r=>{l.status===`connected`&&R(r instanceof Error?r.message:String(r),L(e,t),n)})}async function ce(e,t){if(r===null)throw Error(`this session is already connected; there is nothing to dial`);g!==null&&(clearTimeout(g),g=null),l={status:`connecting`,address:e},j();let n=await r(e);if(m){await n.close();return}await se(n,e,t)}return{wireUpConnection:se,session:{events:h.stream,incomingManageRequests:T.stream,revocationAnnouncements:E.stream,coordinatorFrames:D.stream,incomingDataFrames:O.stream,async connect(e,t){if(c!==null)throw Error(`a session connects once; create a new one to reconnect`);v=0,await ce(e,t).catch(n=>{throw R(n instanceof Error?n.message:String(n),e,t),n})},async sendPing(){let e=ee(),t={type:`ping`};p({direction:`sent`,frame:t}),await e.send(t),j()},async sendPingMeasureRtt(e){let n=ee();return k.sendAndAwait(t.now(),async()=>{let e={type:`ping`};p({direction:`sent`,frame:e}),await n.send(e),j()},e)},setToken(e){y=e},async sendManageRequest(e,t,n,r,i){ee(),n!==void 0&&await ne(n);let a=N(e,t,r),o=a[`request-id`],s=new Promise((e,t)=>{C.set(o,{resolve:e,reject:t,expectedFrom:n})});p({direction:`sent`,frame:a});let c=(async()=>{try{await P(a,n!==void 0,n)}catch(e){throw C.delete(o),s.catch(()=>void 0),e}return j(),s})();return i===void 0?c:Promise.race([c,new Promise(e=>{setTimeout(()=>{C.delete(o)&&(n!==void 0&&(x.remove(n),w.forget(n)),e({result:`error`,code:`timeout`}))},i)})])},async sendRevocationAnnounce(e){ee();let t={type:`revocation-announce`,entries:[...e]};p({direction:`sent`,frame:t}),await P(t,!1),j()},async sendCoordinatorClaim(e){ee();let t={...e};p({direction:`sent`,frame:t}),await P(t,!1),j()},async sendGossipUpdate(e){ee();let t=await oe(e);p({direction:`sent`,frame:t}),await P(t,!1),j()},getTopologyPeers(){return S.compute()},async sendDataFrame(e,t){ee(),t!==void 0&&await ne(t),p({direction:`sent`,frame:e}),await P(e,t!==void 0,t),j()},async close(){m=!0,g!==null&&(clearTimeout(g),g=null),_!==null&&(clearTimeout(_),_=null),M(`connection closed before a response arrived`),w.reset(`the session closed before the channel was ready`),k.rejectAll(`connection closed before a pong arrived`),c!==null&&await c.close(),(l.status===`connected`||l.status===`connecting`||l.status===`reconnecting`)&&(l={status:`closed`,address:l.address,reason:`closed by you`}),j()}}}}function aN(e,t,n={now:()=>Date.now()},r=null,i=[],a,o){let{session:s}=iN(t,n,r,async t=>e.connect(t),a,i,o);return s}async function oN(e,t,n,r={}){let i=r.clock??{now:()=>Date.now()},a=null,o=new Promise(e=>{a=e}),s=!1,{session:c,wireUpConnection:l}=iN(t,i,null,null,e=>{s||(s=!0,a?.(e.device)),r.onPeerAdvert?.(e)},r.addresses,r.onFrame,r.onSessionEnd);return await l(e,r.label??`accepted`,n),{...c,peerDeviceId:o}}function sN(e){return e instanceof Error?e:Error(String(e))}function cN(e){let t=dO(e.selfDeviceId),n=new Set;async function r(t){let n;try{n=await e.shouldExpand(t)}catch(n){e.onExpansionFailed?.(t,[sN(n)]);return}if(!n){e.onExpansionDeclined?.(t);return}let r=[];for(let n of t.addresses)try{let r=await e.dial(n);e.onExpanded(t,n,r);return}catch(e){r.push(sN(e))}e.onExpansionFailed?.(t,r)}return{considerAdvert(e){let i=dO(e.device);i===t||n.has(i)||e.addresses.length===0||(n.add(i),r({device:e.device,addresses:e.addresses}))}}}var lN=/^[0-9a-f]{64}$/,uN=/^[A-Za-z0-9_-]+$/;function dN(e,t){if(!lN.test(e))throw Error(`expected ${t} to be a 64-character lowercase hex device-id, got ${JSON.stringify(e)}`)}function fN(e,t){if(dN(e,`a`),dN(t,`b`),e===t)throw Error(`a DM room path cannot name the same device twice (${e})`);return e<t?`${e}+${t}`:`${t}+${e}`}function pN(e){let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(0,t),r=e.slice(t+1);if(lN.test(n)&&uN.test(r))return{kind:`owner-named`,owner:n,localName:r}}let n=e.indexOf(`+`);if(n!==-1){let t=e.slice(0,n),r=e.slice(n+1);if(lN.test(t)&&lN.test(r)&&t!==r)return{kind:`dm`,participants:[t,r]}}throw Error(`${JSON.stringify(e)} is not a valid room-path`)}var mN=5,hN=1e3,gN=3e4,_N=2,vN={maxAttempts:mN,delayMs:e=>Math.min(hN*_N**(e-1),gN)},yN=4,bN=1024,xN=bN*bN*100,SN=new Uint8Array(yN);function CN(e){let t=Mg(e,hg),n=new Uint8Array(yN+t.length);return new DataView(n.buffer).setUint32(0,t.length),n.set(t,yN),n}function wN(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*TN(e){let t=new Uint8Array;try{for(;;){let n=await e.read();if(n.done)return;for(t=wN(t,n.value);t.length>=yN;){let e=new DataView(t.buffer,t.byteOffset).getUint32(0);if(e>104857600)throw Error(`frame of ${String(e)} bytes exceeds the ${String(xN)}-byte limit`);if(t.length<yN+e)break;if(e===0){t=t.slice(yN);continue}let n=t.slice(yN,yN+e);t=t.slice(yN+e);let r=ME.safeParse(b_(n,x_));r.success&&(yield r.data)}}}catch(t){throw await e.cancel(t),t}}function EN(e,t={opened:!1}){let n=e.writable.getWriter(),r=e.readable.getReader(),i=TN(r),a=t.opened?n.write(SN):Promise.resolve();return a.catch(()=>void 0),{send:async e=>{await a,await n.write(CN(e))},receive:()=>i,close:async()=>{await Promise.allSettled([n.close(),r.cancel()])}}}var DN=`/wire-mesh`,ON=8e3,kN=`the web console is a client only: it cannot listen`;async function AN(e){let t=e.incomingUnidirectionalStreams.getReader(),n=await t.read();if(t.releaseLock(),n.done)throw Error(`the node opened no announcement stream`);let r=n.value;if(!(r instanceof ReadableStream))throw Error(`the announcement stream is not a readable stream`);let i=[],a=r.getReader();for(;;){let e=await a.read();if(e.done)break;if(!(e.value instanceof Uint8Array))throw Error(`the announcement carried something other than bytes`);i.push(e.value)}let o=new Uint8Array(i.reduce((e,t)=>e+t.length,0)),s=0;for(let e of i)o.set(e,s),s+=e.length;return K_(o)}async function jN(e){let t,n=new Promise(e=>{t=setTimeout(()=>{e(`timed out`)},ON)});try{let t=await Promise.race([e.createBidirectionalStream(),n]);if(t===`timed out`)throw e.close(),Error(`this browser cannot open a stream to this node: it is waiting for flow-control credit the node never grants, which is how Safari behaves with the node's HTTP/3 library (fails-components/webtransport#490); reach the node over wss:// instead`);return t}finally{clearTimeout(t)}}function MN(e){return{async connect(t){if(typeof WebTransport>`u`)throw Error(`this browser does not support WebTransport`);let{url:n,sha256:r}=U_(t),i=new URL(n).host,a=q_(r,await e.recall(i)),o=new WebTransport(new URL(DN,n).toString(),{serverCertificateHashes:a.map(e=>({algorithm:`sha-256`,value:e}))});await o.ready;let s=EN(await jN(o),{opened:!0});o.closed.catch(()=>void 0).then(async()=>s.close());let c;return AN(o).then(async t=>{c=t,await e.remember(i,t)}).catch(()=>void 0),{...s,redialAddress:()=>c===void 0?t:Y_(t,c)}},async listen(){return Promise.reject(Error(kN))}}}var NN=1e3,PN=1002,FN=`the web console is a client only: it cannot listen`;function IN(e){let t=[],n=[],r=!1,i=null;function a(){r=!0;for(let e of n.splice(0))e.resolve({value:void 0,done:!0})}function o(e){i=e,r=!0;for(let t of n.splice(0))t.reject(e)}e.addEventListener(`message`,r=>{if(!(r.data instanceof ArrayBuffer)){o(Error(`expected a binary WebSocket message`)),e.close(PN,`protocol error`);return}let i;try{i=Yj(r.data)}catch(t){if(t instanceof Jj)return;o(t instanceof Error?t:Error(`frame body failed to decode: ${String(t)}`)),e.close(PN,`protocol error`);return}let a=n.shift();a?a.resolve({value:i,done:!1}):t.push(i)}),e.addEventListener(`close`,a),e.addEventListener(`error`,a);let s={[Symbol.asyncIterator](){return{next:async()=>c()}}};async function c(){let e=t.shift();return e===void 0?i===null?r?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})}):Promise.reject(i):Promise.resolve({value:e,done:!1})}return{async send(t){return r?Promise.reject(Error(`connection is closed`)):(e.send(Kj(t)),Promise.resolve())},receive:()=>s,async close(){return e.close(NN),Promise.resolve()}}}function LN(){return{async connect(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)return Promise.reject(Error(`not a WebSocket address: ${e}`));let n=new WebSocket(t);return n.binaryType=`arraybuffer`,new Promise((e,r)=>{n.addEventListener(`open`,()=>{e()}),n.addEventListener(`error`,()=>{r(Error(`connect to ${t.toString()} failed`))})}).then(()=>IN(n))},async listen(){return Promise.reject(Error(FN))}}}function RN(e){let t=LN(),n=MN(e);return{connect:async e=>H_(e)?n.connect(e):t.connect(e),listen:async(e,n)=>t.listen(e,n)}}var zN=[{urls:`stun:stun.cloudflare.com:3478`}],BN=`webrtc:signal`,VN={kind:`node`};function HN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.offer`}function UN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.answer`}function WN(e){return typeof e==`object`&&`verb`in e&&e.verb===`webrtc.ice-candidate`}function GN(e,t){return{verb:BN,params:{verb:`webrtc.offer`,"negotiation-id":e,sdp:t}}}function KN(e,t){return{verb:BN,params:{verb:`webrtc.answer`,"negotiation-id":e,sdp:t}}}function qN(e,t){return{verb:BN,params:{verb:`webrtc.ice-candidate`,"negotiation-id":e,...t===void 0?{}:{candidate:t}}}}function JN(e){return{candidate:e.candidate,...e.sdpMid===null?{}:{"sdp-mid":e.sdpMid},...e.sdpMLineIndex===null?{}:{"sdp-m-line-index":e.sdpMLineIndex},...e.usernameFragment===null?{}:{"username-fragment":e.usernameFragment}}}function YN(e){return{candidate:e.candidate,...e[`sdp-mid`]===void 0?{}:{sdpMid:e[`sdp-mid`]},...e[`sdp-m-line-index`]===void 0?{}:{sdpMLineIndex:e[`sdp-m-line-index`]},...e[`username-fragment`]===void 0?{}:{usernameFragment:e[`username-fragment`]}}}function XN(){let e=0;return()=>{let t=e;return e+=1,t}}async function ZN(e,t){if(e.token===void 0)return!1;let n=await JA(e.token,t);return n.ok?n.claims.capability===`webrtc:signal`&&n.claims.scope.kind===VN.kind:!1}function QN(e){let t=[],n=[],r=!1,i=null;function a(){r=!0;for(let e of n.splice(0))e.resolve({value:void 0,done:!0})}function o(e){i=e,r=!0;for(let t of n.splice(0))t.reject(e)}e.addEventListener(`message`,r=>{if(!(r.data instanceof ArrayBuffer)){o(Error(`expected a binary data channel message`)),e.close();return}let i;try{i=Yj(r.data)}catch(t){if(t instanceof Jj)return;o(t instanceof Error?t:Error(`frame body failed to decode: ${String(t)}`)),e.close();return}let a=n.shift();a?a.resolve({value:i,done:!1}):t.push(i)}),e.addEventListener(`close`,a),e.addEventListener(`error`,a);let s={[Symbol.asyncIterator](){return{next:async()=>c()}}};async function c(){let e=t.shift();return e===void 0?i===null?r?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})}):Promise.reject(i):Promise.resolve({value:e,done:!1})}return{async send(t){return e.readyState===`open`?(e.send(Kj(t)),Promise.resolve()):Promise.reject(Error(`data channel is not open (state: ${e.readyState})`))},receive:()=>s,async close(){return e.close(),Promise.resolve()}}}var $N=`wire-mesh`;function eP(e,t){for(let n of t.localTracks??[])e.addTrack(n);t.onRemoteTrack!==void 0&&e.addEventListener(`track`,t.onRemoteTrack)}function tP(e,t){e.addEventListener(`open`,()=>{t(QN(e))},{once:!0})}var nP=16,rP=36e5;async function iP(e,t){let n=new Uint8Array(nP);crypto.getRandomValues(n);let r=await tj({identity:e,clock:t,tokenId:n,bearer:e.deviceId,capability:BN,scope:VN,expires:t.now()+rP});if(!r.ok)throw Error(`could not mint a webrtc:signal token: ${r.reason}`);return r.token}function aP(e,t){let n={identity:t.identity,clock:t.clock,revocation:t.revocation},r=new Map,i=new Map,a=XN();async function o(t,n){let r=qN(t,n===null?void 0:JN(n));await e.sendManageRequest(r,VN,i.get(t))}async function s(a,s){if(!await ZN(a,n)){await a.respond({result:`error`,code:`unauthorized`});return}let c=s[`negotiation-id`];i.set(c,a.fromDevice);let l=new RTCPeerConnection({iceServers:[...t.iceServers]});r.set(c,l),eP(l,t),l.addEventListener(`icecandidate`,e=>{o(c,e.candidate)}),l.addEventListener(`datachannel`,e=>{e.channel.binaryType=`arraybuffer`,tP(e.channel,t.onIncomingConnection)}),await l.setRemoteDescription({type:`offer`,sdp:s.sdp});let u=await l.createAnswer();await l.setLocalDescription(u),await a.respond({result:`ok`}),await e.sendManageRequest(KN(c,u.sdp??``),VN,a.fromDevice)}async function c(e,t){let n=r.get(t[`negotiation-id`]);n!==void 0&&await n.setRemoteDescription({type:`answer`,sdp:t.sdp}),await e.respond({result:`ok`})}async function l(e,t){let n=r.get(t[`negotiation-id`]);n!==void 0&&await n.addIceCandidate(t.candidate===void 0?null:YN(t.candidate)),await e.respond({result:`ok`})}async function u(){for await(let t of e.incomingManageRequests){if(t.command.verb!==`webrtc:signal`)continue;let e=t.command.params;HN(e)?await s(t,e):UN(e)?await c(t,e):WN(e)&&await l(t,e)}}return u(),{async initiate(n){let s=a();i.set(s,n);let c=new RTCPeerConnection({iceServers:[...t.iceServers]});r.set(s,c),eP(c,t),c.addEventListener(`icecandidate`,e=>{o(s,e.candidate)});let l=c.createDataChannel($N);l.binaryType=`arraybuffer`;let u=new Promise((e,t)=>{tP(l,e),l.addEventListener(`error`,()=>{t(Error(`data channel failed to open`))},{once:!0})}),d=await c.createOffer();await c.setLocalDescription(d);let f=await e.sendManageRequest(GN(s,d.sdp??``),VN,n,await iP(t.identity,t.clock));if(f.result===`error`)throw r.delete(s),i.delete(s),c.close(),Error(`webrtc offer rejected: ${f.code}`);return u}}}var oP={frames:0,stage:void 0,handshake:void 0,issued:0,seen:new Set};function sP(e){return dO(e)}function cP(e,t){if(t.type===`gossip`)return e===`received`?t.peers.map(e=>({kind:`peer`,summary:`Peer seen:`,peer:sP(e.device)})):[{kind:`peer`,summary:`Advertised this console to the node`,peer:void 0}];if(t.type===`relay-connect`)return[{kind:`pairing`,summary:`Asked the node to pair this console with`,peer:sP(t[`target-device`])}];if(t.type===`relay-inbound`)return[{kind:`pairing`,summary:`Pairing established with`,peer:sP(t[`source-device`])}];if(t.type===`relay-data`){let n=e===`sent`?t[`to-device`]:t[`from-device`];return[{kind:`relay`,summary:e===`sent`?`Relayed a message to`:`Relayed message received from`,peer:n===void 0?void 0:sP(n)}]}return t.type===`close`?[{kind:`connection`,summary:`The node closed the connection`,peer:void 0}]:[]}function lP(e){return e.status===`reconnecting`?`reconnecting:${String(e.attempt)}`:e.status}function uP(e,t,n){let r=[],i=e=>{r.push({kind:`connection`,summary:e,peer:void 0})};if(lP(t)!==e.stage)switch(t.status){case`connecting`:i(`Connecting to ${t.address}`);break;case`connected`:i(`Connected to ${t.address}`);break;case`reconnecting`:i(`${e.stage?.startsWith(`reconnecting`)===!0?`Retry failed`:`Connection lost`} (${t.reason}); retrying, attempt ${String(t.attempt)}`);break;case`closed`:i(`Closed (${t.reason})`)}return t.status===`connected`&&n!==e.handshake&&(t.handshake.status===`negotiated`?i(`Handshake negotiated: ${t.handshake.sharedDomains.join(`, `)}`):t.handshake.status===`unanswered`?i(`The node does not answer handshakes (a relay-only node)`):t.handshake.status===`rejected`&&i(`Handshake rejected (${t.handshake.reason})`)),r}function dP(e){return e.status===`connected`?e.handshake.status:void 0}function fP(e,t,n){let r=dP(t.state),i=new Set(e.seen),a=[...uP(e,t.state,r),...t.frameLog.slice(e.frames).flatMap(e=>cP(e.direction,e.frame)).filter(e=>e.kind!==`peer`||e.peer===void 0||!i.has(e.peer)&&(i.add(e.peer),!0))].map((t,r)=>({...t,key:`activity-${String(e.issued+r)}`,at:n}));return{tracker:{frames:t.frameLog.length,stage:lP(t.state),handshake:r,issued:e.issued+a.length,seen:i},entries:a}}function pP(e){return e.map(e=>({key:`certificate-${e.key}`,at:e.at,kind:`certificate`,summary:`Certificate changed: ${e.node} announced certificates unlike the remembered ones`,peer:void 0}))}function mP(e,t){let[n,r]=(0,k.useState)({event:void 0,activity:[],statusSince:void 0});return(0,k.useEffect)(()=>{let n={cancelled:!1};return(async()=>{let i=oP;for await(let a of e.events){if(n.cancelled)return;let e=t.now(),o=fP(i,a,e),s=o.tracker.stage!==i.stage;i=o.tracker,r(t=>({event:a,activity:[...t.activity,...o.entries].slice(-500),statusSince:s?e:t.statusSince}))}})(),()=>{n.cancelled=!0}},[e,t]),n}var hP=`local-network-access`,gP=4,_P=255,vP=8,yP=32,bP=[`10.0.0.0/8`,`127.0.0.0/8`,`172.16.0.0/12`,`192.168.0.0/16`,`169.254.0.0/16`,`100.64.0.0/10`];function xP(e){let t=e.split(`.`);if(t.length!==gP)return;let n=0;for(let e of t){let t=/^\d{1,3}$/.test(e)?Number(e):NaN;if(!(t<=_P))return;n=n*2**vP+t}return n}function SP(e,t){let[n,r]=t.split(`/`),i=xP(n??``),a=Number(r);if(i===void 0)return!1;let o=2**(yP-a);return Math.floor(e/o)===Math.floor(i/o)}function CP(e){let t=e.replace(/^\[|\]$/g,``).toLowerCase(),n=xP(t);return n===void 0?t.includes(`:`)?t===`::1`||/^f[cd]/.test(t)||/^fe[89ab]/.test(t):t===`localhost`||t.endsWith(`.local`)||!t.includes(`.`):bP.some(e=>SP(n,e))}function wP(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`ws://${e}`).hostname}catch{return}}function TP(e){return typeof e==`object`&&!!e&&`name`in e&&typeof e.name==`string`}function EP(){if(`permissions`in navigator)return{query:async e=>{if(!TP(e))throw TypeError(`not a permission descriptor`);return navigator.permissions.query(e)}}}async function DP(e,t,n){let r=wP(e);if(r!==void 0&&CP(r)&&!CP(t)&&n!==void 0)try{let{state:e}=await n.query({name:hP});return e===`denied`?`Your browser blocked this page from reaching ${r}, a device on your local network. Allow "Local network access" for this site in the browser's site settings (the icon left of the address), then connect again.`:void 0}catch{return}}var OP=(0,k.createContext)(void 0);function kP(){let e=(0,k.useContext)(OP);if(e===void 0)throw Error(`usePeerNames must be used inside PeerNamesProvider`);return e}var AP={pongTimeoutMs:5e3,intervalMs:15e3};function jP(e,t,n=AP){let[r,i]=(0,k.useState)([]),[a,o]=(0,k.useState)(!1),s=(0,k.useRef)(!1),c=(0,k.useCallback)(()=>{e.sendPingMeasureRtt(n.pongTimeoutMs).then(e=>{s.current=!0,o(!1),i(t=>[...t,e].slice(-40))},e=>{e instanceof TM&&(o(!s.current),i(e=>[...e,void 0].slice(-40)))})},[e,n.pongTimeoutMs]);return(0,k.useEffect)(()=>{if(!t||a)return;c();let e=setInterval(c,n.intervalMs);return()=>{clearInterval(e)}},[t,a,c,n.intervalMs]),{samples:r,unresponsive:a,probe:c}}function MP(e,t,n){let[r,i]=(0,k.useState)(()=>e.now());return(0,k.useEffect)(()=>{if(!t)return;let r=setInterval(()=>{i(e.now())},n);return()=>{clearInterval(r)}},[e,t,n]),r}var NP=1e3,PP=60,FP=60,IP=24;function LP(e){let t=Math.floor(e/NP);if(t<1)return;if(t<PP)return`${String(t)} s`;let n=Math.floor(t/PP);if(n<FP)return`${String(n)} min`;let r=Math.floor(n/FP);return r<IP?`${String(r)} h`:`${String(Math.floor(r/IP))} d`}function RP(e){let t=LP(e);return t===void 0?`just now`:`${t} ago`}function zP(e){let t=LP(e);return t===void 0?`in under a second`:`in ${t}`}function BP(e){return`${String(Math.max(0,Math.ceil(e/NP)))} s`}function VP(e,t,n){if(n.length===0)return{kind:`first-use`,node:e,presented:t};let r=new Set(n),i=t.filter(e=>r.has(e));return i.length>0?{kind:`known`,node:e,trusted:i}:{kind:`changed`,node:e,remembered:n,presented:t}}function HP(e){if(H_(e))try{let{url:t,sha256:n}=U_(e);return{node:new URL(t).host,sha256:[...n]}}catch{return}}function UP(e,t){return{recall:e.recall,remember:async(n,r)=>{let i=VP(n,r.map(e=>uO(e)),(await e.recall(n)).map(e=>uO(e)));await e.remember(n,r),i.kind===`changed`&&t({node:n,remembered:i.remembered,presented:i.presented})}}}var WP=2;function GP(e){let t=[];for(let n=0;n<e.length;n+=WP)t.push(e.slice(n,n+WP).toUpperCase());return t.join(`:`)}var KP=/^([a-z][a-z0-9+.-]*):\/\//i,qP={ws:`ws:`,wss:`wss:`,http:`ws:`,https:`wss:`};function JP(e){if(H_(e))return e;let t=KP.exec(e);if(t===null)return`ws://${e}`;let n=qP[t[1]?.toLowerCase()??``];if(n===void 0)return e;let r=new URL(e);return r.protocol=n,r.hash=``,r.toString()}function YP({deviceHex:e}){return(0,z.jsx)(z.Fragment,{children:Nj(kP().labelOf(e))})}function XP(e){return JSON.stringify(e,(e,t)=>t instanceof Uint8Array?`<${String(t.byteLength)} bytes>`:t)}function ZP({activity:e,frameLog:t}){let[n,r]=(0,k.useState)(!1);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(um,{mt:`md`,label:`Show raw frames`,checked:n,onChange:e=>{r(e.currentTarget.checked)}}),n?(0,z.jsx)(km.ScrollContainer,{minWidth:0,h:384,"data-testid":`frame-log`,children:(0,z.jsxs)(km,{children:[(0,z.jsx)(km.Thead,{children:(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Th,{children:`direction`}),(0,z.jsx)(km.Th,{children:`frame`})]})}),(0,z.jsx)(km.Tbody,{children:t.map((e,t)=>(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Td,{children:e.direction}),(0,z.jsx)(km.Td,{children:XP(e.frame)})]},t))})]})}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Activity`}),e.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Nothing has happened yet.`}):(0,z.jsx)(km.ScrollContainer,{minWidth:0,h:384,"data-testid":`activity-log`,children:(0,z.jsx)(km,{children:(0,z.jsx)(km.Tbody,{children:[...e].reverse().map(e=>(0,z.jsxs)(km.Tr,{children:[(0,z.jsx)(km.Td,{children:new Date(e.at).toLocaleTimeString()}),(0,z.jsxs)(km.Td,{children:[e.summary,e.peer!==void 0&&(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)(YP,{deviceHex:e.peer})]})]})]},e.key))})})})]})]})}var QP=160,$P=32,eF=3,tF=2,nF=26;function rF(e){let t=e.at(-1);return t===void 0?e.length===0?`No round trips measured yet`:`Last ping got no pong`:`Round trip ${String(Math.round(t))} ms`}function iF({samples:e}){let t=e.filter(e=>e!==void 0),n=Math.max(1,...t),r=QP/39,i=(40-e.length)*r,a=e.map((e,t)=>({x:i+t*r,y:e===void 0?void 0:eF+nF*(1-e/n)})),o=a.filter(e=>e.y!==void 0).map(e=>`${e.x.toFixed(1)},${String(e.y)}`).join(` `);return(0,z.jsxs)(`div`,{"data-testid":`rtt-sparkline`,children:[(0,z.jsxs)(`svg`,{role:`img`,"aria-label":rF(e),width:QP,height:$P,viewBox:`0 0 ${String(QP)} ${String($P)}`,children:[(0,z.jsx)(`polyline`,{points:o,fill:`none`,stroke:`currentColor`,strokeWidth:1.5}),a.map(e=>e.y===void 0?null:(0,z.jsx)(`circle`,{cx:e.x,cy:e.y,r:tF,fill:`currentColor`},e.x)),a.filter(e=>e.y===void 0).map(e=>(0,z.jsx)(`line`,{x1:e.x,x2:e.x,y1:21,y2:29,stroke:`var(--mantine-color-red-6)`,strokeWidth:2},e.x))]}),(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:rF(e)})]})}function aF({state:e,statusSince:t,now:n,policy:r}){let i=t===void 0?void 0:t+r.delayMs(e.attempt),a=i===void 0?0:i-n;return(0,z.jsxs)(U,{size:`sm`,c:`orange`,"data-testid":`reconnect-status`,children:[a>0?`Retrying in ${BP(a)}`:`Retrying now`,` `,`(attempt `,e.attempt,` of `,r.maxAttempts,`). Last failure:`,` `,e.reason]})}function oF({state:e,statusSince:t,now:n,policy:r,health:i}){return e.status===`reconnecting`?(0,z.jsx)(aF,{state:e,statusSince:t,now:n,policy:r}):e.status===`connected`?(0,z.jsxs)(pl,{align:`flex-end`,gap:`md`,mb:`sm`,children:[(0,z.jsx)(iF,{samples:i.samples}),i.unresponsive&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`This node does not answer pings, so round trips are not measured automatically.`})]}):null}function sF(e){e?.focus()}function cF({deviceHex:e}){let t=kP(),n=t.labelOf(e),[r,i]=(0,k.useState)(void 0);return r===void 0?(0,z.jsxs)(pl,{gap:`xs`,wrap:`nowrap`,children:[(0,z.jsxs)(`div`,{children:[n.source===`self`&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`calls itself`}),(0,z.jsx)(U,{size:`sm`,fw:n.source===`petname`?`bold`:`normal`,fs:n.source===`self`?`italic`:`normal`,ff:n.source===`id`?`monospace`:`text`,children:n.primary}),n.matchesPetname&&(0,z.jsx)(_d,{size:`xs`,color:`orange`,variant:`light`,children:`same as a name you set`}),n.secondary!==void 0&&(0,z.jsx)(U,{size:`xs`,c:`dimmed`,ff:n.source===`self`?`monospace`:`text`,children:n.secondary})]}),(0,z.jsx)(zd,{value:e,children:({copied:e,copy:t})=>(0,z.jsx)(Zp,{label:e?`Copied`:`Copy device id`,children:(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Copy device id of ${n.primary}`,onClick:t,children:`⧉`})})}),(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Rename ${n.primary}`,onClick:()=>{i(t.petnameOf(e)??``)},children:`✎`})]}):(0,z.jsx)(`form`,{onSubmit:n=>{n.preventDefault(),t.rename(e,r).then(()=>{i(void 0)})},children:(0,z.jsxs)(pl,{gap:`xs`,wrap:`nowrap`,children:[(0,z.jsx)(Am,{size:`xs`,"aria-label":`Petname for ${n.primary}`,value:r,ref:sF,onChange:e=>{i(e.currentTarget.value)}}),(0,z.jsx)(rl,{type:`submit`,size:`sm`,"aria-label":`Save petname`,children:`✓`}),(0,z.jsx)(rl,{size:`sm`,variant:`subtle`,"aria-label":`Cancel rename`,onClick:()=>{i(void 0)},children:`×`})]})})}var lF=`q7ltm10`,uF=`q7ltm11`;function dF({columns:e,rows:t}){return(0,z.jsxs)(km,{striped:!0,className:uF,children:[(0,z.jsx)(km.Thead,{role:`rowgroup`,children:(0,z.jsx)(km.Tr,{role:`row`,children:e.map(e=>(0,z.jsx)(km.Th,{role:`columnheader`,children:e.headerless===!0?null:e.label},e.label))})}),(0,z.jsx)(km.Tbody,{role:`rowgroup`,children:t.map(t=>(0,z.jsx)(km.Tr,{role:`row`,children:e.map((e,n)=>(0,z.jsx)(km.Td,{role:`cell`,"data-label":e.label,children:t.cells[n]},e.label))},t.key))})]})}var fF=16,pF=1e3;function mF(e){let t=``;for(let n of e)t+=n.toString(fF).padStart(2,`0`);return t}function hF(e){if(e.state.status!==`connected`)return``;switch(e.state.handshake.status){case`pending`:return` · handshake pending`;case`negotiated`:return` · v${String(e.state.handshake.version)} · ${e.state.handshake.sharedDomains.join(`, `)}`;case`unanswered`:return` · handshake unanswered (relay-only node?)`;case`rejected`:return` · handshake rejected (${e.state.handshake.reason})`}return``}function gF(e){let{state:t}=e;switch(t.status){case`connecting`:return`connecting…`;case`connected`:return`connected${hF(e)}`;case`reconnecting`:return`reconnecting (attempt ${String(t.attempt)}, ${t.reason})…`;case`closed`:return`closed (${t.reason})`;case`idle`:return`idle`}return``}var _F=1e3,vF=[{label:`device`},{label:`addresses`},{label:`advertised`},{label:`actions`,headerless:!0}];function yF({address:e,session:t,clock:n,reconnectPolicy:r,certificateChanges:i,onClose:a,onMessagePeer:o,pageHost:s=window.location.hostname,permissions:c=EP()}){let{event:l,activity:u,statusSince:d}=mP(t,n),f=l?.state.status===`reconnecting`||l?.state.status===`closed`,[p,m]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{let t={value:!0};return f&&DP(e,s,c).then(n=>{t.value&&m({address:e,message:n})}),()=>{t.value=!1}},[f,e,s,c]);let h=f&&p?.address===e?p.message:void 0,{observeDirectory:g,selfName:_}=kP(),v=l?.state.status===`connected`;(0,k.useEffect)(()=>{l!==void 0&&g(l.directory)},[l,g]);let y=(0,k.useRef)(!1),[b,x]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{v&&(_!==void 0||y.current)&&(y.current=_!==void 0,t.sendGossipUpdate(_===void 0?void 0:jj(_)).then(()=>{x(void 0)},e=>{x(e instanceof Error?e.message:String(e))}))},[v,_,t]);let S=l===void 0?`idle`:gF(l),C=l?.directory??[],w=l?.frameLog??[],T=jP(t,v),E=MP(n,l?.state.status===`reconnecting`||C.length>0,_F),D=HP(JP(e))?.node,O=(0,k.useMemo)(()=>[...u,...pP(i.filter(e=>e.node===D))].sort((e,t)=>e.at-t.at),[u,i,D]);return(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,children:[(0,z.jsxs)(pl,{justify:`space-between`,mb:`xs`,children:[(0,z.jsx)(U,{fw:600,children:e}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,disabled:!v,onClick:T.probe,children:`Send ping`}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:a,children:`Disconnect`})]})]}),(0,z.jsx)(U,{fw:600,size:`sm`,mb:`sm`,children:S}),h===void 0?null:(0,z.jsx)(eu,{color:`yellow`,mb:`sm`,children:h}),b!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Could not publish your display name`,mb:`sm`,children:b}),l!==void 0&&(0,z.jsx)(oF,{state:l.state,statusSince:d,now:E,policy:r,health:T}),(0,z.jsx)(U,{fw:600,size:`sm`,children:`Peer directory`}),C.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`No gossip received yet.`}):(0,z.jsx)(dF,{columns:vF,rows:C.map(e=>({key:mF(e.device),cells:[(0,z.jsx)(cF,{deviceHex:mF(e.device)},`device`),e.advert.addresses.join(`, `),(0,z.jsx)(Zp,{label:`As the peer advertised it, by its own clock`,children:(0,z.jsx)(`span`,{children:RP(E-e.advert[`snapshot-seconds`]*pF)})},`advertised`),(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{o(e.device)},children:`Message`},`actions`)]}))}),(0,z.jsx)(ZP,{activity:O,frameLog:w})]})}var bF=[{label:`device`},{label:`addresses`},{label:`gossiped by`},{label:`actions`,headerless:!0}];function xF({peers:e,onConnect:t,onDismiss:n}){return e.length===0?null:(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,"data-testid":`discovered-peers`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mb:`xs`,children:`Discovered peers`}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,mb:`xs`,children:`Each node below was listed in the directory of a node you are connected to, which is the only thing vouching for it: the address it lists may not be a wire-mesh node at all. Nothing is dialled until you connect.`}),(0,z.jsx)(dF,{columns:bF,rows:e.map(e=>({key:e.key,cells:[(0,z.jsx)(cF,{deviceHex:mF(e.device)},`device`),e.addresses.join(`, `),(0,z.jsxs)(k.Fragment,{children:[e.via.claimedDevice!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:`claimed to be`}),(0,z.jsx)(cF,{deviceHex:e.via.claimedDevice})]}),(0,z.jsxs)(U,{size:`xs`,c:`dimmed`,children:[`over `,e.via.address]})]},`via`),(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{t(e.key)},children:`Connect`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,color:`red`,onClick:()=>{n(e.key)},children:`Dismiss`})]},`actions`)]}))})]})}function SF({label:e,hashes:t}){return(0,z.jsxs)(`div`,{children:[(0,z.jsx)(U,{size:`sm`,fw:600,children:e}),t.map(e=>(0,z.jsx)(Ld,{block:!0,children:GP(e)},e))]})}function CF({prompt:e}){let{assessment:t,decide:n}=e,r=t.kind===`changed`;return(0,z.jsx)(eu,{color:r?`red`:`blue`,title:r?`Certificate changed for ${t.node}`:`First connection to ${t.node}`,"data-testid":`certificate-prompt`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:r?`This address presents a certificate that shares nothing with the one remembered for this node. The node may have replaced its certificate, or something else may be answering at this address. Only continue if you expected the change.`:`This console has not connected to this node before. Connecting pins the certificate below as the one to expect from it from now on. Compare it with what the node's operator reports before you trust it.`}),r&&(0,z.jsx)(SF,{label:`Remembered`,hashes:t.remembered}),(0,z.jsx)(SF,{label:r?`Presented now`:`Certificate (SHA-256)`,hashes:t.presented}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:r?`red`:`blue`,onClick:()=>{n(!0)},children:r?`Trust the new certificate`:`Trust and connect`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{n(!1)},children:`Cancel`})]})]})})}function wF({prompts:e,changes:t,onDismissChange:n}){let r=t.filter(e=>!e.dismissed);return e.length===0&&r.length===0?null:(0,z.jsxs)(rm,{gap:`sm`,"data-testid":`certificate-trust`,children:[e.map(e=>(0,z.jsx)(CF,{prompt:e},e.key)),r.map(e=>(0,z.jsx)(eu,{color:`red`,title:`${e.node} announced different certificates`,withCloseButton:!0,closeButtonLabel:`Dismiss`,onClose:()=>{n(e.key)},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`The node is still reachable through the certificate you pinned, but it now announces certificates that share nothing with the ones remembered for it, and the announced set is what this console will pin from now on.`}),(0,z.jsx)(SF,{label:`Remembered`,hashes:e.remembered}),(0,z.jsx)(SF,{label:`Announced`,hashes:e.presented})]})},e.key))]})}function TF(e,t){let[n,r]=(0,k.useState)([]),[i,a]=(0,k.useState)([]),o=(0,k.useMemo)(()=>UP(e,e=>{a(n=>[...n,{...e,key:crypto.randomUUID(),at:t.now(),dismissed:!1}])}),[e,t]),s=(0,k.useRef)(new Map),c=(0,k.useRef)(new Map);(0,k.useEffect)(()=>{let e=c.current;return()=>{for(let{refuse:t}of[...e.values()])t()}},[]);let l=(0,k.useCallback)(async e=>{let t=`${e.node} ${[...e.presented].sort().join(`,`)}`,n=s.current.get(t);if(n!==void 0)return n.decision;let i=crypto.randomUUID(),a=new Promise(n=>{let a=!1,o=e=>{a||(a=!0,c.current.get(t)?.promptKey===i&&c.current.delete(t),s.current.get(t)?.promptKey===i&&s.current.delete(t),r(e=>e.filter(e=>e.key!==i)),n(e))};c.current.set(t,{promptKey:i,refuse:()=>{o(!1)}}),r(t=>[...t,{key:i,assessment:e,decide:o}])});return s.current.set(t,{promptKey:i,decision:a}),a},[]);return{prompts:n,changes:i,memory:o,confirmAddress:(0,k.useCallback)(async t=>{let n=HP(t);if(n===void 0)return t;let r=VP(n.node,n.sha256.map(e=>uO(e)),(await e.recall(n.node)).map(e=>uO(e)));if(r.kind===`known`)return Y_(t,n.sha256.filter(e=>r.trusted.includes(uO(e))));if(await l(r))return await e.remember(n.node,n.sha256),t},[e,l]),dismissChange:(0,k.useCallback)(e=>{a(t=>t.map(t=>t.key===e?{...t,dismissed:!0}:t))},[])}}function EF({store:e,children:t}){let[n,r]=(0,k.useState)(new Map),[i,a]=(0,k.useState)(new Map),[o,s]=(0,k.useState)(void 0),[c,l]=(0,k.useState)(void 0),u=(0,k.useRef)(Promise.resolve()),d=(0,k.useCallback)(async e=>{u.current=u.current.then(async()=>{try{await e(),l(void 0)}catch(e){l(e instanceof Error?e.message:String(e))}}),await u.current},[]);(0,k.useEffect)(()=>{Promise.all([e.petnames(),e.selfName()]).then(([e,t])=>{r(e),s(t)},e=>{l(e instanceof Error?e.message:String(e))})},[e]);let f=(0,k.useCallback)(async(t,n)=>d(async()=>{await e.setPetname(t,n),r(await e.petnames())}),[e,d]),p=(0,k.useCallback)(async t=>d(async()=>{await e.setSelfName(t),s(await e.selfName())}),[e,d]),m=(0,k.useCallback)(e=>{a(t=>{let n;for(let r of e){let e=Aj(r.advert),i=dO(r.device);t.get(i)!==e&&(n??=new Map(t),e===void 0?n.delete(i):n.set(i,e))}return n??t})},[]),h=(0,k.useMemo)(()=>new Set(n.values()),[n]),g=(0,k.useMemo)(()=>({labelOf:e=>Mj(e,n.get(e),i.get(e),h),petnameOf:e=>n.get(e),rename:f,selfName:o,setSelfName:p,observeDirectory:m}),[n,h,i,o,f,p,m]);return(0,z.jsxs)(OP.Provider,{value:g,children:[c!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Saved names are unavailable`,mb:`md`,children:c}),t]})}function DF(){let{selfName:e,setSelfName:t}=kP(),[n,r]=(0,k.useState)(void 0),i=n??e??``;return(0,z.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),t(i).then(()=>{r(void 0)})},children:(0,z.jsxs)(pl,{align:`flex-end`,wrap:`wrap`,children:[(0,z.jsx)(Am,{label:`Your display name`,description:`Shown to the peers you connect to, signed by this device's key. Leave empty to show only your short id.`,value:i,maxLength:64,onChange:e=>{r(e.currentTarget.value)},style:{flex:1,minWidth:`16rem`}}),(0,z.jsx)(Ed,{type:`submit`,variant:`light`,disabled:(kj(i)??``)===(e??``),children:`Save name`})]})})}function OF({onDismiss:e}){return(0,z.jsxs)(Nd,{withBorder:!0,padding:`md`,radius:`md`,"data-testid":`onboarding-intro`,children:[(0,z.jsx)(Lm,{order:2,size:`h4`,mb:`xs`,children:`Welcome to the wire-mesh console`}),(0,z.jsxs)(vf,{type:`ordered`,spacing:`xs`,size:`sm`,children:[(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Connect.`}),` `,`Enter a node's address in the Node field and press Connect. A console served by a node starts with that node's address filled in, so there is usually nothing to type. The status line shows the connection coming up.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`See who is here.`}),` `,`Once connected, the node's peer directory lists the devices it knows. Message opens a conversation with one. Devices appear under the name they chose for themselves, or a short id; use the pencil beside a device to give it a name of your own, which only this console keeps.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Discovered peers wait for you.`}),` `,`A node you are connected to can tell you about other nodes. Nothing vouches for those addresses except the node that listed them, and one may not be a wire-mesh node at all, so the console never dials one by itself. Each waits in the Discovered peers list until you press Connect or dismiss it.`]}),(0,z.jsxs)(vf.Item,{children:[(0,z.jsx)(U,{span:!0,fw:600,children:`Offline.`}),` `,`The console itself loads without a network, and conversations are kept on this device, so history stays readable. Sending needs a route to the peer, through a node or directly; a message that could not be sent stays with its reason until you retry or dismiss it.`]})]}),(0,z.jsx)(Ed,{mt:`md`,size:`xs`,onClick:e,children:`Got it`})]})}function kF(e,t){return e.sentAt===t.sentAt?uO(e.messageId).localeCompare(uO(t.messageId)):e.sentAt-t.sentAt}function AF(e,t){let n=new Set(e.map(e=>uO(e.messageId))),r=t.filter(e=>!n.has(uO(e.messageId)));return r.length===0?e:[...e,...r].sort(kF)}function jF(e,t,n){let r=e.get(t);return r===void 0?e:new Map(e).set(t,n(r))}function MF(e,t){return{roomPath:e,participants:t,direct:void 0,relay:void 0,via:void 0,token:void 0,status:`closed`,messages:[],notices:[],outgoing:[],pendingJoinRequest:void 0,unread:0}}function NF(e,t,n){let r=t===void 0?n===void 0?void 0:`hub`:`direct`;return{...e,direct:t,relay:n,via:r,status:r===void 0?`closed`:`connected`}}function PF(e,t){switch(t.type){case`direct-opened`:{let n=e.get(t.roomPath)??MF(t.roomPath,t.participants);return new Map(e).set(t.roomPath,{...NF(n,t.session,n.relay),participants:t.participants,notices:[]})}case`relay-opened`:{let n=e.get(t.roomPath)??MF(t.roomPath,t.participants);return new Map(e).set(t.roomPath,NF(n,n.direct,t.route))}case`direct-closed`:return jF(e,t.roomPath,e=>NF(e,void 0,e.relay));case`hub-closed`:{let n=e;for(let r of e.values())r.relay?.hub===t.hub&&(n=jF(n,r.roomPath,e=>NF(e,e.direct,void 0)));return n}case`restored`:return e.get(t.roomPath)===void 0?new Map(e).set(t.roomPath,{...MF(t.roomPath,t.participants),messages:AF([],t.messages)}):jF(e,t.roomPath,e=>({...e,messages:AF(e.messages,t.messages)}));case`notices`:return jF(e,t.roomPath,e=>({...e,notices:t.notices}));case`message`:return jF(e,t.roomPath,e=>{let n=AF(e.messages,[t.message]),r=n!==e.messages;return{...e,messages:n,unread:r&&t.message.direction===`received`?e.unread+1:e.unread}});case`read`:return jF(e,t.roomPath,e=>e.unread===0?e:{...e,unread:0});case`outgoing`:return jF(e,t.roomPath,e=>({...e,outgoing:e.outgoing.some(e=>e.localId===t.entry.localId)?e.outgoing.map(e=>e.localId===t.entry.localId?t.entry:e):[...e.outgoing,t.entry]}));case`outgoing-removed`:return jF(e,t.roomPath,e=>({...e,outgoing:e.outgoing.filter(e=>e.localId!==t.localId)}));case`join-request`:return jF(e,t.roomPath,e=>({...e,pendingJoinRequest:t.request}));case`join-request-settled`:return jF(e,t.roomPath,e=>({...e,pendingJoinRequest:void 0}));case`token`:return jF(e,t.roomPath,e=>({...e,token:t.token}))}return e}function FF(e,t){let n=pN(e);return n.kind===`dm`?n.participants.filter(e=>e!==t):n.owner===t?[]:[n.owner]}function IF(e,t){return e.participants.length===0?e.roomPath:e.participants.map(e=>Nj(t.labelOf(e))).join(`, `)}function LF(e){return e.toLowerCase().split(/\s+/).filter(e=>e!==``)}function RF(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e))}function zF(e,t){let n=LF(t);if(n.length===0)return[];let r=new TextDecoder,i=[];for(let t of e)t.messages.forEach((e,r)=>{RF(e.text,n)&&i.push({key:`${t.roomPath}/message/${String(r)}`,roomPath:t.roomPath,kind:`message`,text:e.text,at:e.sentAt,direction:e.direction})}),t.notices.forEach((e,a)=>{if(e.plaintext===void 0||e.claims===void 0)return;let o=r.decode(e.plaintext);RF(o,n)&&i.push({key:`${t.roomPath}/notice/${String(a)}`,roomPath:t.roomPath,kind:`notice`,text:o,at:e.claims[`posted-at`],direction:void 0})});return i.sort((e,t)=>t.at-e.at).slice(0,50)}function BF({conversations:e,onSelect:t}){let n=kP(),[r,i]=(0,k.useState)(``);if(e.length===0)return null;let a=zF(e,r),o=LF(r).length>0,s=new Map(e.map(e=>[e.roomPath,e]));return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`search-panel`,children:[(0,z.jsx)(Am,{type:`search`,label:`Search conversations and notices`,value:r,onChange:e=>{i(e.currentTarget.value)}}),o&&a.length===0&&(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Nothing matches.`}),a.map(e=>{let i=s.get(e.roomPath);return(0,z.jsx)(Sf,{label:(0,z.jsx)(nf,{highlight:LF(r),size:`sm`,children:e.text}),description:(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(_d,{size:`xs`,variant:`light`,children:e.kind}),(0,z.jsxs)(U,{size:`xs`,c:`dimmed`,children:[i===void 0?e.roomPath:IF(i,n),` · `,new Date(e.at).toLocaleString()]})]}),onClick:()=>{t(e.roomPath)}},e.key)})]})}var VF=16;function HF(){let e=new Uint8Array(VF);return crypto.getRandomValues(e),e}function UF(e){typeof e==`object`&&e&&`unref`in e&&typeof e.unref==`function`&&Reflect.apply(e.unref,e,[])}function WF(e,t){return{verb:e,params:{verb:`capability.request`,capability:e,...t===void 0?{}:{"valid-until":t}}}}var GF=class extends Error{capability;code;constructor(e,t){super(`capability request for "${e}" was refused (${t})`),this.name=`CapabilityRequestRefusedError`,this.capability=e,this.code=t}};async function KF(e,t,n,r,i,a,o){let s=await e.sendManageRequest(WF(t,a),n,r,o,i);if(s.result!==`ok`)throw new GF(t,s.code);let c=qE.safeParse(s);if(!c.success)throw Error(`capability request for "${t}" response was malformed`);return c.data}var qF=`manage:request`;async function JF(e,t){if(e.token===void 0)return{ok:!1,code:`token_required`};if(t.revocation===void 0)throw Error(`requireRequestToken needs a revocation view on the handler options`);let n=await JA(e.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.bearerDevice,...t.extraPredicateResolvers===void 0?{}:{extraPredicateResolvers:t.extraPredicateResolvers}});if(!n.ok)return{ok:!1,code:n.reason};if(n.claims.capability!==`manage:request`)return{ok:!1,code:`capability_mismatch`};let r=n.claims[`requests-capability`];return r!==void 0&&r!==t.capability?{ok:!1,code:`capability_mismatch`}:NO(n.claims.scope,e.scope)?{ok:!0}:{ok:!1,code:`scope_mismatch`}}function YF(e){return async function(t){let n=KE.safeParse(t.command.params);if(!n.success||n.data.capability!==e.capability){await t.respond({result:`error`,code:`malformed`});return}let r=n.data;if(e.requireRequestToken===!0){let n=await JF(t,e);if(!n.ok){await t.respond({result:`error`,code:n.code});return}}let i=r[`valid-until`];if(i!==void 0&&i<=e.clock.now()){await t.respond({result:`error`,code:`expired`});return}let a=!1,o=setTimeout(()=>{a||(a=!0,t.respond({result:`error`,code:`timeout`,message:`no decision within the capability-request timeout`}).catch(()=>void 0))},e.timeoutMs);UF(o),e.onRequest({scope:t.scope,requesterDevice:e.bearerDevice,async decide(n){if(a)return;if(a=!0,clearTimeout(o),n.kind===`reject`){await t.respond({result:`error`,code:`denied`,...n.reason===void 0?{}:{message:n.reason}});return}let r=await tj({identity:e.identity,clock:e.clock,tokenId:HF(),bearer:e.bearerDevice,capability:n.capability,scope:t.scope,expires:n.expires,...n.delegationsRemaining===void 0?{}:{delegationsRemaining:n.delegationsRemaining}});if(!r.ok){await t.respond({result:`error`,code:`mint_failed`});return}let i=r.token;await t.respond({result:`ok`,"granted-token":i,...n.extensions??{}})}})}}var XF=16,ZF=36e5,QF=[{verb:`room:member`,scopeKind:`room`},{verb:`room:join`,scopeKind:`room`},{verb:`room:invite`,scopeKind:`room`},{verb:`webrtc:signal`,scopeKind:`node`},{verb:`relay:use`,scopeKind:`node`},{verb:`pin:write`,scopeKind:`folder`},{verb:`exec:pty`,scopeKind:`folder`},{verb:`exec:proc`,scopeKind:`folder`},{verb:`group:member`,scopeKind:`group`},{verb:VA,scopeKind:`folder`},{verb:qF,scopeKind:`room`}],$F={[VA]:`grantsCapability`,[qF]:`requestsCapability`},eI={already_expired:`the grant would already have expired`,parent_malformed:`the grant it delegates from is malformed`,parent_bearer_mismatch:`the grant it delegates from is not held by this device`,expires_exceeds_parent:`it would outlast the grant it delegates from`,scope_does_not_narrow:`its scope is wider than the grant it delegates from`,capability_mismatch:`its capability differs from the grant it delegates from`,delegation_exceeds_parent:`it permits more delegation than its parent does`,links_exclusive:`it would carry both a parent grant and an authorising grant`,authorisation_malformed:`the grant authorising it is malformed`,authorisation_parent_forbidden:`a grant permission cannot be delegated from a parent grant`,authorisation_bearer_mismatch:`the grant authorising it is not held by this device`,authorisation_capability_mismatch:`the grant authorising it names a different capability`,authorisation_scope_does_not_narrow:`its scope is wider than the grant authorising it`,authorisation_exceeds_authoriser:`it would outlast the grant authorising it`,authorisation_delegation_exceeds:`it permits more delegation than the grant authorising it does`,authorisation_conditions_not_satisfied:`the grant authorising it does not allow this mint`};function tI(e,t){let n=(t??``).trim();if(n===``)return{ok:!0};let r=$F[e];if(r===void 0)return{ok:!1,error:`only ${VA} and ${qF} name a verb they cover`};let i=AD.safeParse(n);return i.success?{ok:!0,claim:r,verb:i.data}:{ok:!1,error:`the covered verb must look like subsystem:action, for example room:member`}}function nI(){let e=new Uint8Array(XF);return crypto.getRandomValues(e),e}async function rI(e,t){let n;try{n=pO(e.bearerHex.trim().toLowerCase())}catch{return{ok:!1,error:`the bearer must be a 64-character hex device-id`}}let r=AD.safeParse(e.capability.trim());if(!r.success)return{ok:!1,error:`the capability must look like subsystem:action, for example room:member`};if(e.scopeKind.trim()===``)return{ok:!1,error:`the scope needs a kind, for example room`};if(!Number.isFinite(e.lifetimeHours)||e.lifetimeHours<=0)return{ok:!1,error:`the lifetime must be more than zero hours`};if(e.delegationsRemaining!==void 0&&!(Number.isSafeInteger(e.delegationsRemaining)&&e.delegationsRemaining>=0))return{ok:!1,error:`further delegations must be a whole number, zero or more`};let i=tI(r.data,e.targetVerb);if(!i.ok)return i;let a=e.selfGrantBars??[];if(a.length>0&&r.data!==`manage:grant`)return{ok:!1,error:`only a ${VA} can bar its holder from granting to itself`};let o=[];for(let e of a){let t=AD.safeParse(e.trim());if(!t.success)return{ok:!1,error:`the barred verb "${e}" must look like subsystem:action`};o.push(MA(t.data,n))}let s=e.scopePath.trim(),c=await tj({identity:t.identity,clock:t.clock,tokenId:nI(),bearer:n,capability:r.data,scope:{kind:e.scopeKind.trim(),...s===``?{}:{path:s}},expires:Math.round(t.clock.now()+e.lifetimeHours*ZF),...e.delegationsRemaining===void 0?{}:{delegationsRemaining:e.delegationsRemaining},...e.parent===void 0?{}:{parent:e.parent},...e.authorisedBy===void 0?{}:{authorisedBy:e.authorisedBy},...i.claim===void 0||i.verb===void 0?{}:{[i.claim]:i.verb},...o.length===0?{}:{conditions:o}});return c.ok?{ok:!0,token:c.token}:{ok:!1,error:`refused: ${eI[c.reason]}`}}var iI=3e4;function aI(e){let{identity:t,clock:n,grants:r,revocations:i,announce:a}=e,[o,s]=(0,k.useState)([]),[c,l]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{let e={cancelled:!1,latestLoad:0},a=async()=>{e.latestLoad+=1;let a=e.latestLoad,o=await r.list(),c=await Promise.all(o.map(async e=>({...e,status:await lj(e.token,{identity:t,clock:n,revocation:i.view,...e.direction===`held`?{expectedBearer:t.deviceId}:{}})})));!e.cancelled&&a===e.latestLoad&&(s(c),l(void 0))},o=()=>{a().catch(t=>{e.cancelled||l(t instanceof Error?t.message:String(t))})};o();let c=[r.subscribe(o),i.subscribe(o)],u=setInterval(o,iI);return()=>{e.cancelled=!0,clearInterval(u);for(let e of c)e()}},[t,n,r,i]);let u=(0,k.useCallback)(async e=>{let i=await rI(e,{identity:t,clock:n});return i.ok?(await r.record(`issued`,i.token,n.now()),{ok:!0,code:sj(i.token)}):i},[t,n,r]),d=(0,k.useCallback)(async e=>{let a;try{a=cj(e)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let o=await lj(a,{identity:t,clock:n,revocation:i.view,expectedBearer:t.deviceId});return o.kind===`invalid`?{ok:!1,error:`this device cannot hold that grant: ${dj(o)}`}:(await r.record(`held`,a,n.now()),{ok:!0})},[t,n,r,i]),f=(0,k.useCallback)(async e=>{try{let t=await i.revoke(e.claims[`token-id`]);return{ok:!0,announced:await a(t)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},[i,a]);return(0,k.useMemo)(()=>({rows:o,loadError:c,mint:u,importCode:d,revoke:f}),[o,c,u,d,f])}function oI({label:e,children:t}){return(0,z.jsxs)(U,{size:`sm`,children:[(0,z.jsxs)(U,{span:!0,fw:600,children:[e,`:`]}),` `,t]})}function sI({row:e}){let{claims:t}=e,n=sj(e.token);return(0,z.jsxs)(rm,{gap:4,"data-testid":`grant-details`,children:[(0,z.jsx)(oI,{label:`Token id`,children:(0,z.jsx)(Ld,{children:e.tokenId})}),(0,z.jsx)(oI,{label:`Issuer`,children:(0,z.jsx)(YP,{deviceHex:dO(t.issuer)})}),(0,z.jsx)(oI,{label:`Bearer`,children:(0,z.jsx)(YP,{deviceHex:dO(t.bearer)})}),(0,z.jsxs)(oI,{label:`Allows`,children:[t.capability,` over `,t.scope.kind,t.scope.path===void 0?``:` ${t.scope.path}`]}),(0,z.jsx)(oI,{label:`Expires`,children:new Date(t.expires).toISOString()}),t[`not-before`]!==void 0&&(0,z.jsx)(oI,{label:`Not before`,children:new Date(t[`not-before`]).toISOString()}),t[`delegations-remaining`]!==void 0&&(0,z.jsx)(oI,{label:`Further delegations`,children:t[`delegations-remaining`]}),t.parent!==void 0&&(0,z.jsx)(oI,{label:`Delegated from`,children:`another grant (its parent rides inside this one)`}),(0,z.jsx)(oI,{label:`Status`,children:dj(e.status)}),(0,z.jsx)(df,{readOnly:!0,label:`Grant code`,description:`Paste this into the other device's grant import to give it this grant.`,value:n,autosize:!0,minRows:2,maxRows:4}),(0,z.jsx)(zd,{value:n,children:({copied:e,copy:t})=>(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:t,w:`fit-content`,children:e?`Copied`:`Copy grant code`})})]})}function cI(e,t){return e>t?zP(e-t):RP(t-e)}function lI({title:e,rows:t,other:n,now:r,onRevoke:i}){let[a,o]=(0,k.useState)(void 0),[s,c]=(0,k.useState)(void 0);return(0,z.jsxs)(`div`,{"data-testid":`grants-${e.toLowerCase()}`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`sm`,children:e}),t.length===0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`None.`}):(0,z.jsx)(dF,{columns:[{label:`capability`},{label:`over`},{label:n===`issuer`?`from`:`to`},{label:`expires`},{label:`status`},{label:`actions`,headerless:!0}],rows:t.map(e=>({key:`${e.direction}/${e.tokenId}`,cells:[e.claims.capability,`${e.claims.scope.kind}${e.claims.scope.path===void 0?``:` ${e.claims.scope.path}`}`,(0,z.jsx)(cF,{deviceHex:dO(e.claims[n])},`other`),cI(e.claims.expires,r),(0,z.jsx)(_d,{color:e.status.kind===`valid`?`green`:`red`,variant:`light`,children:dj(e.status)},`status`),(0,z.jsxs)(k.Fragment,{children:[(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o(a===e.tokenId?void 0:e.tokenId)},children:a===e.tokenId?`Hide`:`Inspect`}),i!==void 0&&e.status.kind===`valid`&&(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:s===e.tokenId?`filled`:`light`,onClick:()=>{s===e.tokenId?(c(void 0),i(e)):c(e.tokenId)},children:s===e.tokenId?`Confirm: revoke for good`:`Revoke`})]}),a===e.tokenId&&(0,z.jsx)(sI,{row:e})]},`actions`)]}))})]})}function uI({onImport:e}){let[t,n]=(0,k.useState)(``),[r,i]=(0,k.useState)(void 0);return(0,z.jsx)(`form`,{onSubmit:r=>{r.preventDefault(),e(t).then(e=>{i(e),e.ok&&n(``)})},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Add a grant you were given`}),(0,z.jsx)(df,{label:`Grant code`,value:t,onChange:e=>{n(e.currentTarget.value)},autosize:!0,minRows:2,maxRows:4,required:!0}),(0,z.jsx)(Ed,{type:`submit`,size:`xs`,w:`fit-content`,children:`Add grant`}),r?.ok===!1&&(0,z.jsx)(eu,{color:`red`,title:`Not added`,children:r.error}),r?.ok===!0&&(0,z.jsx)(eu,{color:`green`,title:`Grant added`,children:`It is listed under Held.`})]})})}var dI=24,fI=`root`,pI=`none`;function mI(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}function hI({delegable:e,onMint:t}){let[n,r]=(0,k.useState)(``),[i,a]=(0,k.useState)(``),[o,s]=(0,k.useState)(``),[c,l]=(0,k.useState)(``),[u,d]=(0,k.useState)(dI),[f,p]=(0,k.useState)(``),[m,h]=(0,k.useState)(fI),[g,_]=(0,k.useState)(pI),[v,y]=(0,k.useState)(``),[b,x]=(0,k.useState)(``),[S,C]=(0,k.useState)(void 0),w=e.find(e=>e.tokenId===m),T=e.find(e=>e.tokenId===g),E=e.filter(e=>e.claims.capability===VA),D=i===`manage:grant`||i===`manage:request`;function O(){if(m!==fI&&w===void 0){C({ok:!1,error:`the grant you chose to delegate from is no longer valid; choose another, or choose Root grant to mint without one`});return}if(g!==pI&&T===void 0){C({ok:!1,error:`the grant you chose to authorise this is no longer valid; choose another, or choose None to mint without one`});return}t({bearerHex:n,capability:i,scopeKind:o,scopePath:c,lifetimeHours:u,delegationsRemaining:f===``?void 0:f,parent:w?.token,authorisedBy:T?.token,targetVerb:D?v:``,selfGrantBars:i===`manage:grant`?mI(b):[]}).then(C,e=>{C({ok:!1,error:e instanceof Error?e.message:String(e)})})}return(0,z.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),O()},children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mt:`md`,children:`Mint a grant`}),(0,z.jsx)(Am,{label:`Bearer device-id`,description:`The device the grant is for: 64 hex characters, copied from a peer's directory row.`,value:n,onChange:e=>{r(e.currentTarget.value)},required:!0}),(0,z.jsx)(md,{label:`Capability`,description:`What it allows, as subsystem:action.`,data:QF.map(e=>e.verb),value:i,onChange:e=>{a(e);let t=QF.find(t=>t.verb===e);t!==void 0&&s(t.scopeKind)},required:!0}),(0,z.jsx)(Am,{label:`Scope kind`,value:o,onChange:e=>{s(e.currentTarget.value)},required:!0}),(0,z.jsx)(Am,{label:`Scope path`,description:`Leave empty for a scope with no path.`,value:c,onChange:e=>{l(e.currentTarget.value)}}),D&&(0,z.jsx)(Am,{label:`Covered verb`,description:i===`manage:grant`?`The one verb the holder may grant, as subsystem:action. Empty means any verb within the scope.`:`The one verb the holder may request, as subsystem:action. Empty means any verb within the scope.`,value:v,onChange:e=>{y(e.currentTarget.value)}}),i===`manage:grant`&&(0,z.jsx)(Am,{label:`Barred from granting to itself`,description:`Comma-separated verbs the holder may not grant to its own device, for example manage:grant to stop it passing on the right to grant.`,value:b,onChange:e=>{x(e.currentTarget.value)}}),(0,z.jsx)(Lp,{label:`Lasts (hours)`,min:0,value:u,onChange:e=>{d(typeof e==`number`?e:0)}}),(0,z.jsx)(Lp,{label:`Further delegations`,description:`How many times the bearer may pass it on. Empty leaves it unset.`,min:0,allowDecimal:!1,value:f,onChange:e=>{p(typeof e==`number`?e:``)}}),(0,z.jsx)($p,{label:`Delegate from`,description:`A grant you hold, which the new grant may only narrow. Root means none.`,allowDeselect:!1,data:[{value:fI,label:`Root grant (none)`},...e.map(e=>({value:e.tokenId,label:`${e.claims.capability} from ${Dj(dO(e.claims.issuer))}`}))],value:m,onChange:e=>{h(e??fI)}}),(0,z.jsx)($p,{label:`Authorised by`,description:`A manage:grant you hold that permits this mint; it may bar what you can grant. None means this grant is minted on your own authority.`,allowDeselect:!1,data:[{value:pI,label:`None`},...E.map(e=>({value:e.tokenId,label:`manage:grant from ${Dj(dO(e.claims.issuer))}`}))],value:g,onChange:e=>{_(e??pI)}}),(0,z.jsx)(Ed,{type:`submit`,size:`xs`,w:`fit-content`,children:`Mint grant`}),S?.ok===!1&&(0,z.jsx)(eu,{color:`red`,title:`Not minted`,children:S.error}),S?.ok===!0&&(0,z.jsx)(eu,{color:`green`,title:`Grant minted`,children:`It is listed under Issued, where Inspect shows its grant code.`})]})})}var gI=1e3;function _I(e){if(!e.ok)return{color:`red`,title:`Not revoked`,text:e.error};let{attempted:t,reached:n}=e.announced;return t===0?{color:`yellow`,title:`Revoked here only`,text:`No connection was open, so no node was told. This console no longer honours the grant.`}:n<t?{color:`yellow`,title:`Revoked, but not every node was told`,text:`Sent to ${String(n)} of ${String(t)} connected nodes. This console no longer honours the grant.`}:{color:`green`,title:`Revoked`,text:`Sent to ${String(n)} connected ${n===1?`node`:`nodes`}. This console no longer honours the grant.`}}function vI({grants:e,clock:t}){let n=MP(t,!0,gI),[r,i]=(0,k.useState)(void 0),a=r===void 0?void 0:_I(r),o=e.rows.filter(e=>e.direction===`held`),s=e.rows.filter(e=>e.direction===`issued`);return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`grants-panel`,children:[(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`A grant is a signed statement that one device may do something over something until a time. Revoking one you issued is recorded here, where this console stops honouring it at once, and sent to the nodes you are connected to. A node only passes it on if it relays revocations, which the hub does not.`}),e.loadError!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`Grants could not be read`,children:e.loadError}),(0,z.jsx)(lI,{title:`Held`,rows:o,other:`issuer`,now:n}),(0,z.jsx)(lI,{title:`Issued`,rows:s,other:`bearer`,now:n,onRevoke:t=>{e.revoke(t).then(i,e=>{i({ok:!1,error:e instanceof Error?e.message:String(e)})})}}),a!==void 0&&(0,z.jsx)(eu,{color:a.color,title:a.title,"data-testid":`revocation-report`,children:a.text}),(0,z.jsx)(hI,{delegable:o.filter(e=>e.status.kind===`valid`),onMint:e.mint}),(0,z.jsx)(uI,{onImport:e.importCode})]})}var yI=6e4;function bI(e,t){let n=URL.createObjectURL(new Blob([t],{type:`application/json`})),r=document.createElement(`a`);r.href=n,r.download=e,r.hidden=!0,document.body.append(r),r.click(),r.remove(),setTimeout(()=>{URL.revokeObjectURL(n)},yI)}var xI=`wire-mesh-console-identity.json`,SI=2;function CI(){location.reload()}function wI({identity:e,backup:t,save:n=bI,reload:r=CI}){let i=dO(e.deviceId),[a,o]=(0,k.useState)({kind:`idle`}),[s,c]=(0,k.useState)(!1);async function l(){try{n(xI,JSON.stringify(await t.export(),void 0,SI)),o({kind:`exported`})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}async function u(e){try{await t.restore(e),o({kind:`restored`})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}async function d(e){if(e!==null)try{o({kind:`confirm-restore`,backup:await OO(await e.text())})}catch(e){o({kind:`error`,message:e instanceof Error?e.message:String(e)})}}return(0,z.jsxs)(rm,{gap:`xs`,"data-testid":`identity-panel`,children:[(0,z.jsxs)(U,{size:`sm`,children:[`This device is `,(0,z.jsx)(Ld,{"data-testid":`own-device-id`,children:i}),` `,(0,z.jsx)(zd,{value:i,children:({copied:e,copy:t})=>(0,z.jsx)(Ed,{size:`compact-xs`,variant:`subtle`,onClick:t,children:e?`Copied`:`Copy device id`})})]}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Its key is ES256 (P-256) and lives in this browser. If this browser's storage is cleared or the device is lost, the identity is gone, along with every grant made to it. A backup file lets you keep it.`}),a.kind===`confirm-export`&&(0,z.jsx)(eu,{color:`orange`,title:`This file holds your private key`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`Anyone who has it can act as this device. Save it somewhere private, and do not send it to anyone. The console does not show the key or keep a copy of the file.`}),(0,z.jsx)(od,{label:`I understand, and I want a backup file`,checked:s,onChange:e=>{c(e.currentTarget.checked)}}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:`orange`,disabled:!s,onClick:()=>{l()},children:`Save backup file`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o({kind:`idle`})},children:`Cancel`})]})]})}),a.kind===`exported`&&(0,z.jsxs)(eu,{color:`green`,title:`Backup file handed to your browser`,children:[(0,z.jsx)(U,{size:`sm`,children:`The browser was asked to save it, and may have asked where. Check that the file is there before you rely on it.`}),(0,z.jsx)(U,{size:`sm`,children:`Keep it private. Restoring it on another browser makes that browser this device.`})]}),a.kind===`confirm-restore`&&(0,z.jsx)(eu,{color:`red`,title:`Replace this device's identity?`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsxs)(U,{size:`sm`,children:[`This device is now `,(0,z.jsx)(Ld,{children:i}),`. The backup is`,` `,(0,z.jsx)(Ld,{children:a.backup.deviceId}),`. Restoring makes this browser the backup's device the next time the console loads, and this identity, with the grants made to it, is gone unless you have a backup of it.`]}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,color:`red`,onClick:()=>{u(a.backup)},children:`Replace this identity`}),(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{o({kind:`idle`})},children:`Cancel`})]})]})}),a.kind===`restored`&&(0,z.jsx)(eu,{color:`green`,title:`Identity restored`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`Reload the console to run as the restored identity.`}),(0,z.jsx)(Ed,{size:`xs`,w:`fit-content`,onClick:r,children:`Reload now`})]})}),a.kind===`error`&&(0,z.jsx)(eu,{color:`red`,title:`That did not work`,children:a.message}),(a.kind===`idle`||a.kind===`exported`||a.kind===`error`)&&(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,variant:`light`,onClick:()=>{c(!1),o({kind:`confirm-export`})},children:`Back up this identity`}),(0,z.jsx)(Wd,{accept:`application/json,.json`,onChange:e=>{d(e)},children:e=>(0,z.jsx)(Ed,{size:`xs`,variant:`light`,color:`red`,...e,children:`Restore from a backup file`})})]})]})}function TI({identity:e,clock:t,grants:n,revocations:r,identityBackup:i,announceRevocation:a}){let o=aI({identity:e,clock:t,grants:n,revocations:r,announce:a});return(0,z.jsxs)(Zl,{multiple:!0,variant:`contained`,"data-testid":`identity-section`,children:[(0,z.jsxs)(Zl.Item,{value:`identity`,children:[(0,z.jsx)(Zl.Control,{children:`Identity`}),(0,z.jsx)(Zl.Panel,{children:(0,z.jsx)(wI,{identity:e,backup:i})})]}),(0,z.jsxs)(Zl.Item,{value:`grants`,children:[(0,z.jsx)(Zl.Control,{children:`Grants`}),(0,z.jsx)(Zl.Panel,{children:(0,z.jsx)(vI,{grants:o,clock:t})})]})]})}function EI({revocations:e,onFailure:t}){let n=(0,k.useSyncExternalStore)(e.subscribe,e.unreadable);return n.length===0?null:(0,z.jsx)(eu,{color:`red`,title:`Some stored revocations could not be loaded`,"data-testid":`unreadable-revocations`,children:(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsx)(U,{size:`sm`,children:`A grant that one of these revoked may read as valid until it is dealt with. Discarding an entry deletes it from this console's storage.`}),n.map(n=>(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsxs)(U,{size:`sm`,children:[n.key,`: `,n.reason]}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:()=>{e.discardUnreadable(n.key).catch(e=>{t(e instanceof Error?e.message:String(e))})},children:`Discard`})]},n.key))]})})}function DI(e){return e instanceof Error?e.message:String(e)}function OI(e){let[t,n]=(0,k.useState)(void 0),[r,i]=(0,k.useState)(void 0);(0,k.useEffect)(()=>{e.introDismissed().then(n,e=>{n(!1),i(DI(e))})},[e]);let a=(0,k.useCallback)(t=>{n(t),e.setIntroDismissed(t).then(()=>{i(void 0)},e=>{i(DI(e))})},[e]),o=(0,k.useCallback)(()=>{a(!0)},[a]),s=(0,k.useCallback)(()=>{a(!1)},[a]);return{visible:t===!1,ready:t!==void 0,error:r,dismiss:o,show:s}}function kI({conversations:e,selected:t,onSelect:n}){let r=kP();return e.length===0?null:(0,z.jsxs)(rm,{gap:0,"data-testid":`conversation-list`,children:[(0,z.jsx)(U,{fw:600,size:`sm`,mb:`xs`,children:`Conversations`}),e.map(e=>(0,z.jsx)(Sf,{active:e.roomPath===t,label:IF(e,r),description:e.status===`connected`?void 0:`offline`,rightSection:(0,z.jsxs)(pl,{gap:4,wrap:`nowrap`,children:[e.pendingJoinRequest!==void 0&&(0,z.jsx)(_d,{color:`blue`,size:`sm`,children:`request`}),e.unread>0&&(0,z.jsx)(_d,{size:`sm`,"aria-label":`${String(e.unread)} unread`,children:e.unread})]}),onClick:()=>{n(e.roomPath)}},e.roomPath))]})}function AI({placeholder:e,ariaLabel:t,submitLabel:n,onSubmit:r,onCancel:i,size:a,autoFocus:o}){let[s,c]=(0,k.useState)(``),[l,u]=(0,k.useState)(void 0);function d(){let e=s.trim();e!==``&&(u(void 0),Promise.resolve(r(e)).then(()=>{c(``)}).catch(e=>{u(e instanceof Error?e.message:String(e))}))}function f(e){e.key===`Enter`&&d(),e.key===`Escape`&&i?.()}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(pl,{gap:`xs`,flex:1,children:[(0,z.jsx)(Am,{flex:1,...a===void 0?{}:{size:a},placeholder:e,"aria-label":t,autoComplete:`off`,autoFocus:o,value:s,onChange:e=>{c(e.currentTarget.value)},onKeyDown:f}),(0,z.jsx)(Ed,{...a===void 0?{}:{size:a},onClick:d,children:n})]}),l!==void 0&&(0,z.jsx)(U,{size:`sm`,c:`red`,children:l})]})}var jI=`You`,MI=256,NI=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`});function PI({sentAt:e}){return(0,z.jsx)(U,{component:`time`,size:`xs`,c:`dimmed`,dateTime:new Date(e).toISOString(),children:NI.format(e)})}function FI({messages:e,outgoing:t,peerLabel:n,onRetry:r,onDiscard:i}){let a=(0,k.useRef)(null);return(0,k.useEffect)(()=>{let e=a.current;e!==null&&(e.scrollTop=e.scrollHeight)},[e,t]),(0,z.jsx)(Gs,{h:MI,viewportRef:a,children:(0,z.jsxs)(rm,{gap:4,children:[e.map((t,r)=>{let i=t.direction===`sent`,a=r===0||e[r-1]?.direction!==t.direction;return(0,z.jsxs)(rm,{gap:0,align:i?`flex-end`:`flex-start`,mt:a?`xs`:0,children:[a&&(0,z.jsx)(U,{size:`xs`,fw:600,c:`dimmed`,children:i?jI:n}),(0,z.jsx)(U,{size:`sm`,children:t.text}),(0,z.jsx)(PI,{sentAt:t.sentAt})]},uO(t.messageId))}),t.map(e=>(0,z.jsxs)(rm,{gap:0,align:`flex-end`,mt:`xs`,children:[(0,z.jsx)(U,{size:`xs`,fw:600,c:`dimmed`,children:jI}),(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:e.text}),e.status===`failed`?(0,z.jsxs)(pl,{gap:`xs`,children:[(0,z.jsx)(U,{size:`xs`,c:`red`,children:`Not sent: ${e.error}`}),(0,z.jsx)(Ed,{size:`compact-xs`,variant:`light`,onClick:()=>{r(e.localId)},children:`Retry`}),(0,z.jsx)(Ed,{size:`compact-xs`,variant:`subtle`,color:`gray`,onClick:()=>{i(e.localId)},children:`Dismiss`})]}):(0,z.jsx)(U,{size:`xs`,c:`dimmed`,children:e.status===`awaiting-approval`?`Waiting for ${n} to allow messages`:`Sending`})]},e.localId))]})})}function II(e){if(e.plaintext!==void 0)return new TextDecoder().decode(e.plaintext)}function LI({notices:e}){if(e.length===0)return null;let t=e.map((e,t)=>{let n=II(e);return(0,z.jsx)(H,{children:n===void 0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,fs:`italic`,children:`encrypted notice -- no key held for its epoch`}):(0,z.jsx)(U,{size:`sm`,children:n})},t)});return(0,z.jsxs)(rm,{gap:4,children:[t,(0,z.jsxs)(_d,{variant:`light`,color:`gray`,size:`sm`,w:`fit-content`,children:[e.length,` notice`,e.length===1?``:`s`]})]})}var RI=864e5;function zI(e){return e===`direct`?`direct`:e===`hub`?`via hub`:`offline`}function BI({view:e,onSend:t,onPostNotice:n,onRetry:r,onDiscard:i}){let a=kP();return(0,z.jsxs)(rm,{gap:`xs`,children:[(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsx)(U,{fw:600,"data-testid":`conversation-header`,children:IF(e,a)}),(0,z.jsx)(U,{size:`sm`,c:e.status===`connected`?`green`:`dimmed`,children:zI(e.via)})]}),e.pendingJoinRequest&&(0,z.jsx)(eu,{color:`blue`,title:`Message request`,children:(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsxs)(U,{size:`sm`,children:[(0,z.jsx)(YP,{deviceHex:e.pendingJoinRequest.requesterHex}),` `,`wants to message you`]}),(0,z.jsxs)(pl,{children:[(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{e.pendingJoinRequest?.decide({kind:`accept`,capability:`room:member`,expires:Date.now()+RI})},children:`Allow`}),(0,z.jsx)(Ed,{size:`xs`,color:`red`,variant:`light`,onClick:()=>{e.pendingJoinRequest?.decide({kind:`reject`})},children:`Deny`})]})]})}),(0,z.jsx)(FI,{messages:e.messages,outgoing:e.outgoing,peerLabel:IF(e,a),onRetry:r,onDiscard:i}),(0,z.jsx)(pl,{children:(0,z.jsx)(AI,{ariaLabel:`Message`,placeholder:`Message`,submitLabel:`Send`,onSubmit:t})}),(0,z.jsx)(Ud,{label:`Durable notices (encrypted, replicated)`,labelPosition:`center`}),(0,z.jsx)(LI,{notices:e.notices}),e.via===void 0?(0,z.jsx)(U,{size:`sm`,c:`dimmed`,children:`Durable notices can be posted while the conversation is connected.`}):(0,z.jsx)(pl,{children:(0,z.jsx)(AI,{ariaLabel:`Post a durable notice`,placeholder:`Post a durable notice`,submitLabel:`Post notice`,onSubmit:n})})]})}var VI=`room:member`;async function HI(e,t){let n=await JA(e,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.expectedBearer});if(!n.ok)return n;if(n.claims.scope.kind!==`room`)return{ok:!1,reason:`wrong_scope_kind`};if(n.claims.scope.path!==t.roomPath)return{ok:!1,reason:`wrong_scope_path`};let r=pN(t.roomPath),i=dO(n.rootIssuer);if(r.kind===`owner-named`){if(i!==r.owner)return{ok:!1,reason:`wrong_chain_root`}}else if(t.dmRootPolicy===`either-participant`){if(i!==r.participants[0]&&i!==r.participants[1])return{ok:!1,reason:`wrong_chain_root`}}else if(i!==dO(t.identity.deviceId))return{ok:!1,reason:`wrong_chain_root`};return{ok:!0,claims:n.claims,rootIssuerKey:n.rootIssuerKey}}async function UI(e,t,n,r){for(let i of await e.list()){let e=i.claims;if(i.direction!==`held`||e.capability!==`manage:request`)continue;let a=e[`requests-capability`];if((a===void 0||a===n)&&NO(e.scope,r)&&(await lj(i.token,t)).kind===`valid`)return i.token}}function WI(e){if(e instanceof GF)switch(e.code){case`denied`:return`the other side denied the request`;case`token_required`:return`the other side only accepts requests that present a request permission, and this device holds none that covers this one`;case`capability_mismatch`:return`the request permission presented does not cover this capability`;case`scope_mismatch`:return`the request permission presented does not cover this conversation`;default:return`the request permission presented was refused (${e.code})`}}function GI(e){return async function(t){if(t.command.verb!==e.capability){await t.respond({result:`error`,code:`malformed`});return}let n=JE.safeParse(t.command.params);if(!n.success){await t.respond({result:`error`,code:`malformed`});return}let r=n.data[`granted-token`],i=await JA(r,{identity:e.identity,clock:e.clock,revocation:e.revocation,expectedBearer:e.identity.deviceId});if(!i.ok){await t.respond({result:`error`,code:i.reason});return}if(i.claims.capability!==e.capability){await t.respond({result:`error`,code:`capability_mismatch`});return}if(!NO(i.claims.scope,t.scope)){await t.respond({result:`error`,code:`scope_mismatch`});return}await t.respond({result:`ok`}),e.onGrant({capability:e.capability,grantedToken:r,scope:t.scope,granterDevice:e.granterDevice})}}var KI=16;function qI(){let e=new Uint8Array(KI);return crypto.getRandomValues(e),e}var JI=3e5;function YI(e,t,n){return{verb:VI,params:{verb:`room.send`,"message-id":t,"sent-at":n,text:e}}}async function XI(e,t,n,r,i){let a=YI(n,qI(),Date.now());return e.sendManageRequest(a,{kind:`room`,path:t},i,r)}async function ZI(e,t,n,r){let i;try{i=await KF(e,VI,{kind:`room`,path:t},n,void 0,void 0,r)}catch(e){let t=WI(e);throw t===void 0?e:Error(t)}let a=fD.safeParse(i);if(!a.success)throw Error(`room.join response for ${t} was malformed`);return{token:a.data[`granted-token`],members:a.data.members.map(e=>e.device)}}function QI(e,t,n){async function r(e,r){let i=e.scope.path;if(i===void 0||e.token===void 0){await e.respond({result:`error`,code:`unauthorized`});return}if(!(await HI(e.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:t.peerDevice,roomPath:i})).ok){await e.respond({result:`error`,code:`unauthorized`});return}await e.respond({result:`ok`});let a=r[`message-id`],o=r[`sent-at`],s=r.text;a instanceof Uint8Array&&typeof o==`number`&&typeof s==`string`&&n.onMessage?.({roomPath:i,text:s,messageId:a,sentAt:o})}function i(e){return async n=>{if(n.kind===`reject`){let t={kind:`reject`,...n.reason===void 0?{}:{reason:n.reason}};await e.decide(t);return}let r=[...t.currentMembers?.()??[],t.peerDevice].map(e=>({device:e})),i={kind:`accept`,capability:n.capability,expires:n.expires,...n.delegationsRemaining===void 0?{}:{delegationsRemaining:n.delegationsRemaining},extensions:{members:r}};await e.decide(i)}}let a=YF({capability:VI,identity:t.identity,clock:t.clock,bearerDevice:t.peerDevice,timeoutMs:t.joinRequestTimeoutMs??JI,onRequest(e){let t=e.scope.path,r=n.onJoinRequest;if(t===void 0||r===void 0){e.decide({kind:`reject`,reason:`unsupported verb`});return}r({roomPath:t,requesterDevice:e.requesterDevice,decide:i(e)})}});async function o(e){if(e.scope.path===void 0){await e.respond({result:`error`,code:`missing_scope_path`});return}if(n.onJoinRequest===void 0){await e.respond({result:`error`,code:`unsupported_verb`});return}await a({...e,respond:async t=>{if(t.result===`ok`){let e=LD.safeParse(t[`granted-token`]);e.success&&n.onGrantIssued?.(e.data)}await e.respond(t)}})}let s=GI({capability:VI,identity:t.identity,clock:t.clock,revocation:t.revocation,granterDevice:t.peerDevice,onGrant(e){let t=e.scope.path,r=n.onRoomInvite;t!==void 0&&r!==void 0&&r({roomPath:t,granterDevice:e.granterDevice,token:e.grantedToken})}});async function c(e){if(e.scope.path===void 0){await e.respond({result:`error`,code:`missing_scope_path`});return}if(n.onRoomInvite===void 0){await e.respond({result:`error`,code:`unsupported_verb`});return}await s(e)}(async()=>{for await(let t of e.incomingManageRequests){if(t.command.verb!==`room:member`)continue;let e=t.command.params;typeof e==`object`&&`verb`in e&&(e.verb===`room.send`?await r(t,e):e.verb===`capability.request`?await o(t):e.verb===`capability.grant`?await c(t):e.verb===`room.rekey`&&n.onRekey!==void 0&&await n.onRekey(t))}})()}var $I=`room-key/`,eL=`room-token/`,tL=`room-key-delivered/`,nL=String(2**53-1).length;function rL(e,t){return`${$I}${e}/${String(t).padStart(nL,`0`)}`}function iL(e){return{get:async(t,n)=>e.get(rL(t,n)),set:async(t,n,r)=>{await e.set(rL(t,n),new Uint8Array(r))},currentEpoch:async t=>{let n=(await e.keys(`${$I}${t}/`)).sort().at(-1);return n===void 0?void 0:Number(n.slice(n.lastIndexOf(`/`)+1))}}}function aL(e,t,n,r){return{get:async i=>{let a=eL+i,o=await e.get(a);if(o===void 0)return;let s=LD.safeParse(b_(o,x_));if(s.success&&(await JA(s.data,{identity:t,clock:n,revocation:r,expectedBearer:t.deviceId})).ok)return s.data;await e.delete(a)},set:async(t,n)=>{await e.set(eL+t,new Uint8Array(Mg(n,hg)))},rooms:async()=>(await e.keys(eL)).map(e=>e.slice(11))}}function oL(e){return{isDelivered:async t=>await e.get(tL+t)!==void 0,markDelivered:async t=>{await e.set(tL+t,new Uint8Array([1]))}}}var sL=32,cL=256,lL=12,uL=4,dL=8,fL=new TextEncoder().encode(`wire-mesh/room-rekey/v1\0`);function pL(){return crypto.getRandomValues(new Uint8Array(sL))}function mL(e){let t=new TextEncoder().encode(e.room),n=new Uint8Array(uL);new DataView(n.buffer).setUint32(0,t.length,!1);let r=new Uint8Array(dL);new DataView(r.buffer).setBigUint64(0,BigInt(e.keyEpoch),!1);let i=new Uint8Array(fL.length+n.length+t.length+r.length),a=0;return i.set(fL,a),a+=fL.length,i.set(n,a),a+=n.length,i.set(t,a),a+=t.length,i.set(r,a),i}async function hL(e,t){let n=await crypto.subtle.importKey(`raw`,Uint8Array.from(e),`HKDF`,!1,[`deriveKey`]);return crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:Uint8Array.from(new Uint8Array),info:Uint8Array.from(mL(t))},n,{name:`AES-GCM`,length:cL},!1,[`encrypt`,`decrypt`])}async function gL(e,t){let n=crypto.getRandomValues(new Uint8Array(lL)),r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n},e,Uint8Array.from(t))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}async function _L(e,t){if(t.length<lL)throw Error(`ciphertext shorter than the AES-GCM IV it must carry`);let n=t.slice(0,lL),r=t.slice(lL);return new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:n},e,r))}async function vL(e,t){return gL(e,t)}async function yL(e,t){return _L(e,t)}async function bL(e){return crypto.subtle.importKey(`raw`,Uint8Array.from(e),`AES-GCM`,!1,[`encrypt`,`decrypt`])}async function xL(e,t){return gL(await bL(e),t)}async function SL(e,t){return _L(await bL(e),t)}var CL=`+aes256gcm`;function wL(e){return EL(e)?e:`${e}${CL}`}function TL(e){return EL(e)?e.slice(0,e.length-10):e}function EL(e){return e.endsWith(CL)}function DL(e,t){return{verb:VI,params:{verb:`room.rekey`,"key-epoch":e,"wrapped-key":t}}}async function OL(e,t,n,r,i,a){return e.sendManageRequest(DL(n,r),{kind:`room`,path:t},i,a)}function kL(e){return async function(t){if(t.command.verb!==`room:member`){await t.respond({result:`error`,code:`malformed`});return}let n=uD.safeParse(t.command.params);if(!n.success){await t.respond({result:`error`,code:`malformed`});return}if(t.scope.kind!==`room`||t.scope.path===void 0){await t.respond({result:`error`,code:`scope_mismatch`});return}let r=t.scope.path,i=await HI(e.ownRoomMemberToken,{identity:e.identity,clock:e.clock,revocation:e.revocation,expectedBearer:e.identity.deviceId,roomPath:r,dmRootPolicy:`either-participant`});if(!i.ok){await t.respond({result:`error`,code:i.reason});return}let a=e.identity.deriveSharedSecret;if(a===void 0){await t.respond({result:`error`,code:`ecdh_unsupported`});return}let o=n.data[`key-epoch`],s=Array.isArray(n.data[`wrapped-key`])?n.data[`wrapped-key`]:[n.data[`wrapped-key`]],c=o-s.length+1,l;try{let e=await a(i.rootIssuerKey);l=await Promise.all(s.map(async(t,n)=>yL(await hL(e,{room:r,keyEpoch:c+n}),t)))}catch{await t.respond({result:`error`,code:`unwrap_failed`});return}await t.respond({result:`ok`}),await e.onRekey({room:r,keyEpoch:o,contentKeys:l})}}function AL(e){return Uint8Array.from(e)}function jL(e){return AL(Mg(e,hg))}function ML(e){return jL({1:e.identityKey.alg,4:e.deviceId})}function NL(e,t){return Mg([`Signature1`,e,new Uint8Array,t],hg)}function PL(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function FL(e,t){let[n,,r,i]=e;if(r===null)return{ok:!1,reason:`malformed`};let a;try{a=b_(r,x_)}catch{return{ok:!1,reason:`malformed`}}let o=mD.safeParse(a);if(!o.success)return{ok:!1,reason:`malformed`};let s=o.data;if(t.expectedRoom!==void 0&&s.room!==t.expectedRoom)return{ok:!1,reason:`wrong_room`};if(!await t.identity.verify(s[`poster-key`],NL(n,r),i))return{ok:!1,reason:`bad_signature`};if(!PL(await t.identity.deriveDeviceId(s[`poster-key`][`public-key`]),s.poster))return{ok:!1,reason:`wrong_poster`};let c=s[`valid-until`];if(c!==void 0&&c<=t.clock.now())return{ok:!1,reason:`content_expired`};let l=s[`key-epoch`];if(EL(s[`content-type`])!==(l!==void 0))return{ok:!1,reason:`key_epoch_mismatch`};let u=await HI(s.token,{identity:t.identity,clock:t.clock,revocation:t.revocation,expectedBearer:s.poster,roomPath:s.room,...t.dmRootPolicy===void 0?{}:{dmRootPolicy:t.dmRootPolicy}});return u.ok?{ok:!0,claims:s}:{ok:!1,reason:u.reason}}async function IL(e){let t=jL({room:e.room,poster:e.identity.deviceId,"poster-key":e.identity.identityKey,token:e.token,"notice-id":e.noticeId,"posted-at":e.clock.now(),"content-type":e.contentType,content:e.content,...e.refs===void 0?{}:{refs:[...e.refs]},...e.validUntil===void 0?{}:{"valid-until":e.validUntil},...e.keyEpoch===void 0?{}:{"key-epoch":e.keyEpoch}}),n=ML(e.identity);return[n,{},t,await e.identity.sign(NL(n,t))]}var LL=16;function RL(e){return new Uint8Array(Mg(e,hg))}function zL(e){let{identity:t,storage:n,clock:r,revocation:i,roomKeys:a}=e;async function o(e){let i=await a.currentEpoch(e.room);if(i===void 0)throw Error(`no content key held for room ${e.room}: room.rekey this room before posting encrypted notices`);let o=await a.get(e.room,i);if(o===void 0)throw Error(`content key store is inconsistent: epoch ${String(i)} is current for room ${e.room} but holds no key`);let s=e.noticeId??crypto.getRandomValues(new Uint8Array(LL)),c=await xL(o,e.plaintext),l=await IL({identity:t,clock:r,room:e.room,token:e.token,noticeId:s,contentType:wL(e.contentType),content:c,keyEpoch:i}),{haveFrame:u}=await bM({identity:t,storage:n},RL(l));return{dataHave:u,notice:l,keyEpoch:i}}async function s(e,t){let r=await yM(n,e);if(!(await SM(n,{type:`data-entries`,peer:e,"from-seq":r,entries:[t]})).ok)throw Error(`gap rejecting entry for peer log (head ${String(r)})`)}async function c(e,t,r){let i=await CM(n,e,0),a=[];for(let e of i)a.push(await l(e,t,r));return a}async function l(e,n,o){let s=u(e);if(s===void 0)return{verified:!1,reason:`malformed`};let c=await FL(s,{identity:t,clock:r,revocation:i,expectedRoom:n,dmRootPolicy:o});if(!c.ok)return{verified:!1,reason:c.reason};let l=c.claims;if(!EL(l[`content-type`]))return{verified:!0,contentType:l[`content-type`],plaintext:l.content,claims:l};let d=l[`key-epoch`];if(d===void 0)return{verified:!1,reason:`key_epoch_mismatch`};let f=await a.get(l.room,d),p={verified:!0,contentType:TL(l[`content-type`]),claims:l};if(f===void 0)return p;try{let e=await SL(f,l.content);return{...p,plaintext:e}}catch{return p}}function u(e){try{let t=b_(e,x_),n=pD.safeParse(t);return n.success?n.data:void 0}catch{return}}return{postEncryptedNotice:o,ingestPeerEntry:s,readOwnNotices:async e=>c(t.deviceId,e,`either-participant`),readPeerNotices:async(e,t)=>c(e,t,`self`)}}var BL=32;function VL(e){let{senders:t,storage:n,identity:r,clock:i,revocation:a,roomKeys:o,onChange:s}=e,c=zL({identity:r,storage:n,clock:i,revocation:a,roomKeys:o});async function l(e,t){let r=await yM(n,t);await e.sendDataFrame({type:`data-request`,peer:t,"from-seq":r})}async function u(e){let t=await yM(n,r.deviceId);t!==0&&await e.sendDataFrame({type:`data-have`,peer:r.deviceId,"head-seq":t})}function d(e,t){if(e.type===`data-have`){l(t,e.peer).catch(()=>void 0);return}if(e.type===`data-entries`){(async()=>{(await SM(n,e)).ok&&(e.entries.length>=BL&&await l(t,e.peer).catch(()=>void 0),s())})();return}e.type===`data-request`&&(async()=>{let r=await xM(n,e,BL);r!==null&&await t.sendDataFrame(r)})().catch(()=>void 0)}return{handleFrame:d,async post(e){let{dataHave:n}=await c.postEncryptedNotice(e);await Promise.allSettled(t().map(async e=>e.sendDataFrame(n))),s()},async readRoom(e,t){let n=await c.readOwnNotices(e),r=await Promise.all(t.map(async t=>c.readPeerNotices(t,e)));return[...n,...r.flat()]},async sync(e,t){await u(e),await Promise.all(t.map(async t=>l(e,t)))},async pull(e){await Promise.allSettled(t().flatMap(t=>e.map(async e=>l(t,e))))},roomKeys:o}}async function HL(e){let{session:t,target:n,identity:r,clock:i,revocation:a,ownRoomMemberToken:o,roomPath:s,roomKeys:c,delivery:l}=e,u=s.split(`+`)[0]??``;if(u===``||dO(r.deviceId)!==u)return;let d=await c.currentEpoch(s);if(d!==void 0&&d!==1||await l.isDelivered(s))return;let f=await HI(o,{identity:r,clock:i,revocation:a,expectedBearer:r.deviceId,roomPath:s,dmRootPolicy:`either-participant`});if(!f.ok)throw Error(`own room token failed verification: ${f.reason}`);let p=r.deriveSharedSecret;if(p===void 0)throw Error(`this identity cannot derive ECDH shared secrets`);let m=d===void 0?pL():await c.get(s,1);if(m===void 0)throw Error(`room ${s} lost its epoch 1 key`);let h=await vL(await hL(await p(f.rootIssuerKey),{room:s,keyEpoch:1}),m);d===void 0&&await c.set(s,1,m);let g=await OL(t,s,1,h,n,o);if(g.result!==`ok`)throw Error(`room.rekey was refused: ${g.code}`);await l.markDelivered(s)}var UL=[`core/management`,`core/room`],WL=16;function GL(){let e=new Uint8Array(WL);return crypto.getRandomValues(e),e}function KL(e){if(e?.direct!==void 0)return{session:e.direct,target:void 0};if(e?.relay!==void 0)return{session:e.relay.hub,target:e.relay.peer};throw Error(`conversation is not connected`)}function qL(e,t,n,r,i){let{revocation:a,grants:o}=i,[s,c]=(0,k.useReducer)(PF,new Map),l=dO(e.deviceId),[u,d]=(0,k.useState)(void 0),f=(0,k.useCallback)(e=>{e.then(void 0,e=>{d(e instanceof Error?e.message:String(e))})},[]),p=(0,k.useRef)(s);(0,k.useEffect)(()=>{p.current=s},[s]);let m=(0,k.useRef)(new Set),h=(0,k.useRef)(new WeakSet),g=(0,k.useMemo)(()=>iL(r),[r]);function _(){return[...p.current.values()].flatMap(e=>e.participants.map(e=>pO(e)))}let v=(0,k.useRef)(()=>void 0),y=(0,k.useMemo)(()=>VL({senders:()=>[...new Set([...[...p.current.values()].flatMap(e=>[...e.direct===void 0?[]:[e.direct],...e.relay===void 0?[]:[e.relay.hub]]),...m.current])],storage:r,identity:e,clock:t,revocation:a,roomKeys:g,onChange:()=>{v.current()}}),[e,t,r,g,a]);function b(e){let t=p.current.get(e)?.participants;t!==void 0&&y.readRoom(e,t.map(e=>pO(e))).then(t=>{c({type:`notices`,roomPath:e,notices:[...t]})})}(0,k.useEffect)(()=>{v.current=()=>{for(let e of p.current.keys())b(e)}});let x=(0,k.useRef)(new Map),S=(0,k.useMemo)(()=>oL(r),[r]),C=(0,k.useMemo)(()=>aL(r,e,t,a),[r,e,t,a]);async function w(e,t){x.current.set(e,t),await C.set(e,t)}async function T(e){let t=x.current.get(e);if(t!==void 0)return t;let n=await C.get(e);return n!==void 0&&x.current.set(e,n),n}(0,k.useEffect)(()=>{let e=new AbortController;return(async()=>{let t=new Set([...await n.roomPaths(),...await C.rooms()]);for(let r of t){let t=await n.list(r);if(e.signal.aborted)return;let i=FF(r,l);c({type:`restored`,roomPath:r,participants:i,messages:t}),y.readRoom(r,i.map(e=>pO(e))).then(e=>{c({type:`notices`,roomPath:r,notices:[...e]})})}})(),()=>{e.abort()}},[n,C,y,l]);let E=(0,k.useRef)(new Map);async function D(n,r,i){let o=E.current.get(n);if(o!==void 0)return o;let s=HL({session:i.session,target:i.target,identity:e,clock:t,revocation:a,ownRoomMemberToken:r,roomPath:n,roomKeys:g,delivery:S}).finally(()=>{E.current.delete(n)});return E.current.set(n,s),s}function O(r){return{onMessage:e=>{let t={direction:`received`,text:e.text,messageId:e.messageId,sentAt:e.sentAt};f(n.append(r,t)),c({type:`message`,roomPath:r,message:t}),y.pull((p.current.get(r)?.participants??[]).map(e=>pO(e)))},onGrantIssued:e=>{f(o.record(`issued`,e,t.now()))},onJoinRequest:e=>{c({type:`join-request`,roomPath:r,request:{requesterHex:dO(e.requesterDevice),async decide(t){c({type:`join-request-settled`,roomPath:r}),await e.decide(t),(async()=>{let e=await T(r),t=p.current.get(r);e!==void 0&&t!==void 0&&await D(r,e,KL(t))})().catch(()=>void 0)}}})},onRekey:async n=>{let i=await T(r);if(i===void 0){await n.respond({result:`error`,code:`no_token`});return}await kL({identity:e,clock:t,revocation:a,ownRoomMemberToken:i,onRekey:async e=>{for(let[t,n]of e.contentKeys.entries())await g.set(r,e.keyEpoch-e.contentKeys.length+1+t,n);b(r)}})(n)}}}let A=(0,k.useCallback)(async(r,i)=>{let o={},u=await oN(r,e,UL,{clock:t,onFrame:(e,t)=>{o.current?.(t)}}),d=i??await u.peerDeviceId,f=dO(d),p=fN(l,f);if(s.get(p)?.direct!==void 0){await u.close();return}o.current=e=>{y.handleFrame(e,u)},c({type:`direct-opened`,roomPath:p,participants:[f],session:u}),c({type:`restored`,roomPath:p,participants:[f],messages:await n.list(p)}),y.sync(u,[d]).catch(()=>void 0),QI(u,{identity:e,clock:t,revocation:a,peerDevice:d,currentMembers:()=>[e.deviceId,d]},O(p)),(async()=>{for await(let e of u.events)e.state.status===`closed`&&c({type:`direct-closed`,roomPath:p})})()},[e,t,l,s,n,y]),j=(0,k.useCallback)(async n=>UI(o,{identity:e,clock:t,revocation:a,expectedBearer:e.deviceId},VI,{kind:`room`,path:n}),[o,e,t,a]),M=(0,k.useCallback)(async(e,r,i)=>{let a=s.get(e),{session:l,target:u}=KL(a),d=a?.token;if(d===void 0){i(`awaiting-approval`);let n=await ZI(l,e,u,await j(e));i(`sending`),d=n.token,await w(e,d),f(o.record(`held`,d,t.now())),c({type:`token`,roomPath:e,token:d}),D(e,d,{session:l,target:u}).catch(()=>void 0)}let p=await XI(l,e,r,d,u);if(p.result!==`ok`)throw Error(`send failed: ${p.code}`);let m={direction:`sent`,text:r,messageId:GL(),sentAt:t.now()};return await n.append(e,m),m},[s,t,n,e,g,j]),N=(0,k.useCallback)(async(e,t,n)=>{c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:`sending`}});try{let r=await M(e,n,r=>{c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:r}})});c({type:`message`,roomPath:e,message:r}),c({type:`outgoing-removed`,roomPath:e,localId:t})}catch(r){c({type:`outgoing`,roomPath:e,entry:{localId:t,text:n,status:`failed`,error:r instanceof Error?r.message:String(r)}})}},[M]),ee=(0,k.useCallback)(async(e,t)=>N(e,crypto.randomUUID(),t),[N]),P=(0,k.useCallback)(async(e,t)=>{let n=s.get(e)?.outgoing.find(e=>e.localId===t);n!==void 0&&await N(e,t,n.text)},[s,N]),F=(0,k.useCallback)((e,t)=>{c({type:`outgoing-removed`,roomPath:e,localId:t})},[]),I=(0,k.useCallback)(async(e,n)=>{let r=s.get(e),{session:i,target:a}=KL(r),l=r?.token??await T(e);l===void 0&&(l=(await ZI(i,e,a,await j(e))).token,await w(e,l),f(o.record(`held`,l,t.now())),c({type:`token`,roomPath:e,token:l})),await D(e,l,{session:i,target:a}),await y.post({room:e,token:l,contentType:`text/plain`,plaintext:new TextEncoder().encode(n)}),b(e)},[s,e,t,g,y,j]),te=(0,k.useCallback)(e=>{c({type:`read`,roomPath:e})},[]),ne=(0,k.useCallback)((e,t)=>{let r=fN(l,dO(t)),i=[dO(t)];c({type:`relay-opened`,roomPath:r,participants:i,route:{hub:e,peer:t}}),n.list(r).then(e=>{c({type:`restored`,roomPath:r,participants:i,messages:e})}),y.sync(e,[t]).catch(()=>void 0)},[l,n,y]),re=(0,k.useCallback)(n=>{let r=new Map;m.current.add(n),(async()=>{for await(let i of n.incomingManageRequests){let o=i.fromDevice;if(o===void 0)continue;let s=dO(o),c=r.get(s);if(c===void 0){c=fM(),r.set(s,c);let i=fN(l,s);ne(n,o),QI({incomingManageRequests:c.stream},{identity:e,clock:t,revocation:a,peerDevice:o,currentMembers:()=>[e.deviceId,o]},O(i))}c.push(i)}})()},[e,t,l,ne]),ie=(0,k.useCallback)(e=>{m.current.delete(e),c({type:`hub-closed`,hub:e})},[]),L=(0,k.useCallback)((e,t,n)=>{h.current.has(t)||(h.current.add(t),y.sync(e,_()).catch(()=>void 0)),y.handleFrame(n,e)},[y]);return{conversations:[...s.values()],persistenceFailure:u,openRelay:ne,watchHub:re,dropHub:ie,onHubFrame:L,attach:A,send:ee,retry:P,discard:F,postNotice:I,markRead:te}}function JL(e,t){let n=new Map(t.map(e=>[e,fM()]));return(async()=>{for await(let t of e)n.get(t.command.verb)?.push(t)})(),{stream:e=>{let t=n.get(e);if(t===void 0)throw Error(`the demux was not built to carry verb ${e}`);return t.stream}}}var YL=8787,XL=/^(localhost|127\.\d+\.\d+\.\d+)(:\d+)?$/;function ZL(e){return XL.test(e)}async function QL(e=YL){try{return await fetch(`http://127.0.0.1:${String(e)}/`,{mode:`no-cors`}),`ws://127.0.0.1:${String(e)}`}catch{return}}async function $L(e=typeof location>`u`?``:location.host){return ZL(e)?Promise.resolve(void 0):QL()}var eR=`ws://localhost:8787`,tR=[`core/management`,`core/exec`,`core/data`],nR=[`core/management`,`core/data`],rR=[BN,VI];function iR({identity:e,clock:t,messageStore:n,roomStorage:r,certificateMemory:i,nameStore:a,preferences:o,grants:s,revocations:c,identityBackup:l,discoverLocalNode:u=$L,defaultAddress:d=eR}){let[f,p]=(0,k.useState)(d),[m,h]=(0,k.useState)(nR),[g,_]=(0,k.useState)([]),[v,y]=(0,k.useState)([]),[b,x]=(0,k.useState)([]),[S,C]=(0,k.useState)(void 0),w=OI(o),T=TF(i,t),E=(0,k.useMemo)(()=>({revocation:c.view,grants:s}),[c,s]),D=qL(e,t,n,r,E),[O,A]=(0,k.useState)(),j=D.conversations.find(e=>e.roomPath===O)??D.conversations[0],{markRead:M}=D,N=j?.roomPath,ee=j?.unread??0;(0,k.useEffect)(()=>{N!==void 0&&ee>0&&M(N)},[N,ee,M]);let P=(0,k.useRef)(new Map),F=(0,k.useRef)(D.onHubFrame);(0,k.useEffect)(()=>{F.current=D.onHubFrame},[D.onHubFrame]);let I=(0,k.useRef)(D.watchHub);(0,k.useEffect)(()=>{I.current=D.watchHub},[D.watchHub]);let te=(0,k.useRef)(D.attach);(0,k.useEffect)(()=>{te.current=D.attach},[D.attach]);let ne=(0,k.useRef)(g);(0,k.useEffect)(()=>{ne.current=g},[g]);let re=(0,k.useRef)(new Set),ie=(0,k.useRef)(new Map),L=(0,k.useRef)(!1),R=()=>L.current;(0,k.useEffect)(()=>(L.current=!1,()=>{L.current=!0;for(let e of ne.current)e.session.close()}),[]);let ae=(0,k.useRef)(m);(0,k.useEffect)(()=>{ae.current=m},[m]);function oe(n,r){let i=JL(r.incomingManageRequests,rR),a=aP({sendManageRequest:async(...e)=>r.sendManageRequest(...e),incomingManageRequests:i.stream(BN)},{identity:e,clock:t,revocation:E.revocation,iceServers:zN,onIncomingConnection:e=>{te.current(e)}});(async()=>{for await(let e of r.revocationAnnouncements)try{await c.ingest(e)}catch(e){C(e instanceof Error?e.message:String(e))}})();let o={sendManageRequest:async(...e)=>r.sendManageRequest(...e),sendDataFrame:async e=>r.sendDataFrame(e),incomingManageRequests:i.stream(VI)};P.current.set(r,o),I.current(o),_(e=>[...e,{address:n,session:r,hub:o,negotiator:a}])}async function se(e,t){let n=mF(e.device);for(let t of e.addresses){let e=ie.current.get(t)??new Set;e.add(n),ie.current.set(t,e)}return new Promise(r=>{y(i=>[...i,{key:n,device:e.device,addresses:e.addresses,via:t,resolve:r}])})}function ce(e,t){y(n=>(n.find(t=>t.key===e)?.resolve(t),n.filter(t=>t.key!==e)))}function le(n){let r={current:null},i={current:null},a=aN(RN(T.memory),e,t,vN,[],e=>{r.current?.considerAdvert(e)},(e,t)=>{let n=i.current===null?void 0:P.current.get(i.current);n!==void 0&&F.current(n,e,t)});return i.current=a,r.current=cN({selfDeviceId:e.deviceId,shouldExpand:async e=>se(e,n),dial:de,onExpanded:(e,t,n)=>{oe(t,n),ue(e)},onExpansionDeclined:ue,onExpansionFailed:ue}),a}function ue(e){let t=mF(e.device);for(let n of e.addresses){let e=ie.current.get(n);e?.delete(t),e?.size===0&&ie.current.delete(n)}}async function de(e){let t=await T.confirmAddress(JP(e));if(t===void 0)throw Error(`the certificate of ${e} was not trusted`);if(R())throw Error(`the console was closed before the dial began`);let n=ie.current.get(e),[r]=n??[],i=le({address:e,claimedDevice:n?.size===1?r:void 0});if(await i.connect(t,ae.current),R())throw await i.close(),Error(`the console was closed while the dial was connecting`);return i}function fe(e){ne.current.some(t=>t.address===e)||re.current.has(e)||(re.current.add(e),T.confirmAddress(JP(e)).then(t=>{if(t===void 0||R())return;let n=le({address:e,claimedDevice:void 0});oe(e,n),n.connect(t,m).catch(()=>{})}).finally(()=>{re.current.delete(e)}))}let pe=(0,k.useRef)(fe);(0,k.useEffect)(()=>{pe.current=fe});let me=(0,k.useRef)(u);(0,k.useEffect)(()=>{me.current=u},[u]);let he=(0,k.useRef)(!1);(0,k.useEffect)(()=>{he.current||(he.current=!0,me.current().then(e=>{e!==void 0&&pe.current(e)}))},[]);function ge(e){e.preventDefault(),fe(f)}async function _e(e){let t=await Promise.allSettled(ne.current.map(async t=>t.session.sendRevocationAnnounce([e])));return{attempted:t.length,reached:t.filter(e=>e.status===`fulfilled`).length}}function ve(e){D.dropHub(e.hub),e.session.close(),_(t=>t.filter(t=>t.session!==e.session))}function ye(t,n){D.openRelay(t.hub,n),A(fN(dO(e.deviceId),dO(n))),t.negotiator.initiate(n).then(async e=>D.attach(e,n)).catch(e=>{x(t=>[...t,{key:crypto.randomUUID(),peer:mF(n),reason:e instanceof Error?e.message:String(e)}])})}return(0,z.jsx)(EF,{store:a,children:(0,z.jsxs)(rm,{className:lF,p:`md`,gap:`lg`,children:[(0,z.jsxs)(pl,{justify:`space-between`,children:[(0,z.jsx)(Lm,{order:1,children:`wire-mesh console`}),w.ready&&!w.visible&&(0,z.jsx)(Ed,{size:`xs`,variant:`subtle`,onClick:w.show,children:`How this works`})]}),w.error!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`The first-run intro's setting is unavailable`,children:w.error}),w.visible&&(0,z.jsx)(OF,{onDismiss:w.dismiss}),(0,z.jsx)(DF,{}),(0,z.jsxs)(`form`,{onSubmit:ge,children:[(0,z.jsxs)(pl,{align:`flex-end`,wrap:`wrap`,children:[(0,z.jsx)(Am,{label:`Node`,value:f,onChange:e=>{p(e.currentTarget.value)},required:!0,style:{flex:1,minWidth:`16rem`}}),(0,z.jsx)(Ed,{type:`submit`,children:`Connect`})]}),(0,z.jsx)(od.Group,{label:`Domains offered`,value:m,onChange:h,children:(0,z.jsx)(pl,{mt:`xs`,children:tR.map(e=>(0,z.jsx)(od,{value:e,label:e},e))})})]}),(0,z.jsx)(wF,{prompts:T.prompts,changes:T.changes,onDismissChange:T.dismissChange}),(0,z.jsx)(xF,{peers:v,onConnect:e=>{ce(e,!0)},onDismiss:e=>{ce(e,!1)}}),g.map(e=>(0,z.jsx)(yF,{address:e.address,session:e.session,clock:t,reconnectPolicy:vN,certificateChanges:T.changes,onClose:()=>{ve(e)},onMessagePeer:t=>{ye(e,t)}},e.address)),b.map(e=>(0,z.jsxs)(eu,{color:`yellow`,title:(0,z.jsxs)(z.Fragment,{children:[`No direct connection to `,(0,z.jsx)(YP,{deviceHex:e.peer})]}),withCloseButton:!0,onClose:()=>{x(t=>t.filter(t=>t.key!==e.key))},children:[e.reason,`. Messages go through the hub instead.`]},e.key)),D.persistenceFailure!==void 0&&(0,z.jsxs)(eu,{color:`red`,title:`Could not save to this console's storage`,children:[D.persistenceFailure,`. The conversation carries on, but what failed to save will be missing after a reload.`]}),S!==void 0&&(0,z.jsx)(eu,{color:`red`,title:`A revocation could not be stored`,children:S}),(0,z.jsx)(EI,{revocations:c,onFailure:C}),(0,z.jsx)(BF,{conversations:D.conversations,onSelect:A}),(0,z.jsx)(TI,{identity:e,clock:t,grants:s,revocations:c,identityBackup:l,announceRevocation:_e}),(0,z.jsx)(kI,{conversations:D.conversations,selected:j?.roomPath,onSelect:A}),j!==void 0&&(0,z.jsx)(BI,{view:j,onSend:async e=>D.send(j.roomPath,e),onPostNotice:async e=>D.postNotice(j.roomPath,e),onRetry:e=>{D.retry(j.roomPath,e)},onDiscard:e=>{D.discard(j.roomPath,e)}},j.roomPath)]})})}var aR=`modulepreload`,oR=function(e){return`/`+e},sR={},cR=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=oR(t,n),t=s(t),t in sR)return;sR[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:aR,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},lR=`false`,uR=`false`,dR=lR===`true`,fR=uR===`true`;function pR(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,dR||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await cR(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!fR){if(dR)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}function mR(e={}){let{immediate:t=!0,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,[c,l]=(0,k.useState)(!1),[u,d]=(0,k.useState)(!1),[f]=(0,k.useState)(()=>pR({immediate:t,onNeedReload:n,onOfflineReady(){d(!0),i?.()},onNeedRefresh(){l(!0),r?.()},onRegistered:a,onRegisteredSW:o,onRegisterError:s}));return{needRefresh:[c,l],offlineReady:[u,d],updateServiceWorker:f}}function hR(){let{offlineReady:[e,t],needRefresh:[n,r],updateServiceWorker:i}=mR();function a(){t(!1),r(!1)}return!e&&!n?null:(0,z.jsx)(Ef,{onClose:a,closeButtonProps:{"aria-label":`Dismiss`},title:n?`Update available`:`Ready to work offline`,pos:`fixed`,bottom:`1rem`,right:`1rem`,style:{zIndex:1e3},children:(0,z.jsx)(pl,{gap:`xs`,children:n?(0,z.jsx)(Ed,{size:`xs`,onClick:()=>{i(!0)},children:`Reload`}):void 0})})}var gR=`ws://localhost:8787`;function _R(e){return`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}`}function vR(e,t){return e?gR:_R(t)}var yR=await qm(),bR=await F_(yR),xR={now:()=>Date.now()},SR=gj(await qm()),CR=await xj({storage:await qm(),identity:bR,clock:xR}),wR=kO(yR),TR=Gj(await qm()),ER=await qm(),DR=hO(await qm()),OR=Rj(await qm()),kR=wj(await qm()),AR=vR(!1,window.location),jR=document.getElementById(`root`);if(jR===null)throw Error(`missing #root element`);(0,Rm.createRoot)(jR).render((0,z.jsx)(k.StrictMode,{children:(0,z.jsxs)(xn,{children:[(0,z.jsx)(iR,{identity:bR,clock:xR,messageStore:TR,roomStorage:ER,certificateMemory:DR,nameStore:OR,preferences:kR,grants:SR,revocations:CR,identityBackup:wR,defaultAddress:AR}),(0,z.jsx)(hR,{})]})}));
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<meta name="theme-color" content="#1971c2" />
|
|
11
11
|
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
|
|
12
12
|
<title>wire-mesh console</title>
|
|
13
|
-
<script type="module" crossorigin src="/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/assets/index-BYDmiOle.js"></script>
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/assets/index-BtvNxMjr.css">
|
|
15
15
|
<link rel="manifest" href="/manifest.webmanifest"></head>
|
|
16
16
|
<body>
|
package/dist/web-console/sw.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(n,o)=>{const r=e||("document"in self?document.currentScript.src:"")||location.href;if(s[r])return;let t={};const
|
|
1
|
+
if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(n,o)=>{const r=e||("document"in self?document.currentScript.src:"")||location.href;if(s[r])return;let t={};const d=e=>i(e,r),l={module:{uri:r},exports:t,require:d};s[r]=Promise.all(n.map(e=>l[e]||d(e))).then(e=>(o(...e),t))}}define(["./workbox-2fbc6a65"],function(e){"use strict";self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),e.precacheAndRoute([{url:"index.html",revision:"2ad6e46f3663bd04b9add3218a8441a5"},{url:"assets/workbox-window.prod.es5-Bd17z0YL.js",revision:null},{url:"assets/index-BtvNxMjr.css",revision:null},{url:"assets/index-BYDmiOle.js",revision:null},{url:"favicon.svg",revision:"e9eabed03a72f0df2b347884322f7dfb"},{url:"icons/icon-192x192.svg",revision:"e9eabed03a72f0df2b347884322f7dfb"},{url:"icons/icon-512x512.svg",revision:"e9eabed03a72f0df2b347884322f7dfb"},{url:"manifest.webmanifest",revision:"89b97e994ecf3ebc89bc570153e191ad"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wire-mesh",
|
|
3
|
-
"version": "3.6.
|
|
3
|
+
"version": "3.6.4",
|
|
4
4
|
"bin": {
|
|
5
5
|
"wire-mesh": "./dist/server.mjs"
|
|
6
6
|
},
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"@peculiar/x509": "2.1.0",
|
|
9
9
|
"cbor2": "2.3.0",
|
|
10
10
|
"reflect-metadata": "0.2.2",
|
|
11
|
-
"wire-mesh-core": "4.0.
|
|
11
|
+
"wire-mesh-core": "4.0.2",
|
|
12
12
|
"ws": "8.21.3"
|
|
13
13
|
},
|
|
14
14
|
"devDependencies": {
|
|
15
15
|
"@arethetypeswrong/cli": "0.18.5",
|
|
16
16
|
"@exadev/eslint-config": "2.18.0",
|
|
17
|
-
"@exadev/wire-mesh-web-console": "2.17.
|
|
17
|
+
"@exadev/wire-mesh-web-console": "2.17.3",
|
|
18
18
|
"@types/node": "26.4.1",
|
|
19
19
|
"@types/ws": "8.18.1",
|
|
20
20
|
"eslint": "10.10.0",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
"files": [
|
|
43
43
|
"dist"
|
|
44
44
|
],
|
|
45
|
+
"license": "MIT",
|
|
45
46
|
"optionalDependencies": {
|
|
46
47
|
"@fails-components/webtransport": "1.6.8",
|
|
47
48
|
"@fails-components/webtransport-transport-http3-quiche": "1.6.8"
|