@net-mesh/browser 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var we=class{constructor(e=()=>{}){this.detach=e}detach;buffered=[];waiting=null;ended=!1;push(e){if(this.ended)return;let t=this.waiting;if(t){this.waiting=null,t({value:e,done:!1});return}this.buffered.push(e)}end(){if(this.ended)return;this.ended=!0;let e=this.waiting;e&&(this.waiting=null,e({value:void 0,done:!0}))}next(){let e=this.buffered.shift();if(e!==void 0)return Promise.resolve({value:e,done:!1});if(this.ended)return Promise.resolve({value:void 0,done:!0});let{promise:t,resolve:r}=Promise.withResolvers();return this.waiting=r,t}return(){return this.detach(),this.end(),Promise.resolve({value:void 0,done:!0})}[Symbol.asyncIterator](){return this}};function at(n,e,t,r=[t]){return!n||!e||t.length===0||r.length===0||r[0]!==t||r.some(i=>i.length===0)?null:{bootstrapOk:!0,stunProbeFailed:!0,probed:t,probedAll:[...r]}}var z=class extends Error{constructor(e){super(e),this.name="LeafError"}},tt=class extends z{constructor(t){super(`wire: ${t}`);this.detail=t;this.name="WireError"}detail;kind="wire"},Oe=class extends z{constructor(t){super(`session: ${t}`);this.detail=t;this.name="SessionError"}detail;kind="session"},nt=class extends z{constructor(t){super(`control plane: ${t}`);this.detail=t;this.name="ControlPlaneError"}detail;kind="control-plane"},ge=class extends z{constructor(t){super(`identity: ${t}`);this.detail=t;this.name="IdentityError"}detail;kind="identity"},rt=class extends z{constructor(t,r){super(`ice configuration: the iceServers entry ${t} names this connection's peer RTC endpoint ${r}; a peer cannot be its own STUN server. Omit iceServers to use the STUN endpoint the anchor announces (the stun_addr field of GET /rtc/anchor), or name a STUN server that is not this peer`);this.entry=t;this.peerRtcAddr=r;this.name="IceServerConflictError"}entry;peerRtcAddr;kind="ice-server-conflict"},it=class extends z{constructor(t,r=null){super(r===null?`not the leader: this tab holds generation ${t}`:`not the leader: this tab holds generation ${t}, the leader holds ${r}`);this.presented=t;this.current=r;this.name="NotLeaderError"}presented;current;kind="not-leader"},oe=class extends z{constructor(t){super(`rtc: ${Ei(t)}`);this.failure=t;this.name="RtcError",this.kind=xi[t.type]}failure;kind},st=class extends z{constructor(t){super(`rpc: ${Ai(t)}`);this.failure=t;this.name="RpcError",this.kind=ki[t.type]}failure;kind},Ne=class extends z{constructor(t,r){super(t);this.cause=r;this.name="UnknownLeafError"}cause;kind="unknown"},Q=class extends z{},pe=class extends Q{constructor(t,r){super(r??`org:admission_denied:${vi[t]}`);this.coarse=t;this.name="OrgAdmissionDeniedError"}coarse;kind="org-admission-denied"},xe=class extends pe{kind="org-revoked";constructor(e="org:admission_denied:denied"){super("denied",e),this.name="OrgRevokedError"}},ke=class extends Q{kind="org-timeout";constructor(e="org:rpc:timeout"){super(e),this.name="OrgTimeoutError"}},D=class extends Q{kind="org-cancelled";constructor(e="org:rpc:cancelled"){super(e),this.name="OrgCancelledError"}},Z=class extends Q{constructor(t,r="org:rpc:leader_lost"){super(r);this.generation=t;this.name="OrgLeaderLostError"}generation;kind="org-leader-lost"},Ee=class extends Q{kind="org-session-lost";constructor(e="org:rpc:session_lost"){super(e),this.name="OrgSessionLostError"}},Fe=class extends Q{constructor(t,r="org:rpc:indeterminate"){super(r);this.deadlineMs=t;this.name="OrgIndeterminateError"}deadlineMs;kind="org-indeterminate"},Ve=class extends Q{constructor(t,r="org:rpc:refused"){super(r);this.status=t;this.name="OrgRefusedError"}status;kind="org-refused"},ve=class extends Q{kind="org-internal";constructor(e="org:rpc:internal"){super(e),this.name="OrgInternalError"}},We=class extends Q{kind="org-malformed";constructor(e="org:rpc:malformed"){super(e),this.name="OrgMalformedError"}},lt="org: the response sink is closed: the call was retired";var qn="org:",vi={denied:"denied","not-supported":"not_supported",unavailable:"unavailable"};function ot(n){let e=(n??"").trim();return e==="unavailable"?"unavailable":e==="not_supported"||e==="not-supported"?"not-supported":e==="\0"||e==="0"?"denied":e===""||e==="1"?"not-supported":e===""||e==="2"?"unavailable":"denied"}function Oi(n){switch(n){case"timeout":return new ke;case"revoked":return new xe;case"session-lost":return new Ee;case"leader-lost":return new Z("");case"cancelled":case"node-closed":case"replaced":return new D;case"resource-exhausted":return new pe("unavailable")}}function Wt(n){let e=n.message;switch(n.kind){case"admission-denied":return new pe(ot(n.coarse),e);case"revoked":return e===void 0?new xe:new xe(e);case"timeout":return e===void 0?new ke:new ke(e);case"cancelled":return e===void 0?new D:new D(e);case"leader-lost":return new Z(n.generation??"",e);case"session-lost":return e===void 0?new Ee:new Ee(e);case"indeterminate":return new Fe(n.deadlineMs??0,e);case"refused":return new Ve(n.status??0,e);case"malformed":return e===void 0?new We:new We(e);case"internal":return e===void 0?new ve:new ve(e);default:return new ve(`org:rpc:internal: unrecognized terminal kind ${JSON.stringify(n.kind)}`+(e===void 0?"":`: ${e}`))}}function ct(n){switch(n){case"timeout":case"cancelled":case"revoked":case"session-lost":case"leader-lost":case"node-closed":case"replaced":case"resource-exhausted":return n;default:return"replaced"}}function Nn(n){if(/^org: .+ is closed: the call was retired$/.test(n))return new D(n);if(/^org: .+ is closed: the call's byte budget refused the item and retired the call$/.test(n))return new pe("unavailable",n);if(n.startsWith(qn)){let t=n.slice(qn.length),r=t.indexOf(":");if(r<=0)return null;let i=t.slice(0,r),s=t.slice(r+1),o=s.indexOf(":"),a=o===-1?s:s.slice(0,o);if(a.length===0)return null;if(i==="admission_denied")return new pe(ot(a),n);if(i!=="rpc")return null;switch(a){case"revoked":return new xe(n);case"timeout":return new ke(n);case"cancelled":return new D(n);case"leader_lost":case"leader-lost":return new Z("",n);case"session_lost":case"session-lost":return new Ee(n);case"indeterminate":return new Fe(0,n);case"refused":case"server_error":case"capability_denied":return new Ve(0,n);case"malformed":case"codec_encode":case"codec_decode":return new We(n);case"internal":case"no_route":case"transport":return new ve(n);default:return null}}let e=/^rpc: refused \(9\): ([\s\S]*)$/.exec(n);return e?new pe(ot(e[1]),n):null}var xi={iceTimeout:"ice-timeout",udpBlocked:"udp-blocked",channelClosed:"channel-closed",unsupported:"rtc-unsupported"},ki={refused:"rpc-refused",timeout:"rpc-timeout",sessionLost:"session-lost",leaderLost:"leader-lost",indeterminate:"rpc-indeterminate",malformed:"rpc-malformed"},Wn="ICE did not connect inside the deadline (this does not establish that UDP is blocked)";function Ei(n){switch(n.type){case"iceTimeout":return Wn;case"udpBlocked":return`no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to ${n.evidence.probedAll.join(", ")} went unanswered`;case"channelClosed":return`the DataChannel closed: ${n.detail}`;case"unsupported":return`this browser refused the attempt: ${n.detail}`}}function Ai(n){switch(n.type){case"refused":return`refused (${n.status}): ${n.message}`;case"timeout":return"the call's deadline elapsed";case"sessionLost":return"the session carrying the call went away";case"leaderLost":return`the leader holding generation ${n.generation} was replaced`;case"indeterminate":return`the local deadline of ${n.deadlineMs}ms elapsed before the tab running the node answered; the remote operation may still have executed (it was not retried)`;case"malformed":return`the reply did not decode: ${n.detail}`}}function b(n){if(n instanceof z)return n;let e=Ri(n);return Un(e)??new Ne(e,n)}function Ri(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n!==null&&typeof n=="object"&&"message"in n){let e=n.message;if(typeof e=="string")return e}return String(n)}function Un(n){let e=Nn(n);if(e!==null)return e;let t=se(n,"rtc: ");if(t!==null){let l=$n(t);return l===null?null:new oe(l)}let r=se(n,"rpc: ");if(r!==null){let l=Bn(r);return l===null?null:new st(l)}let i=se(n,"wire: ");if(i!==null)return new tt(i);let s=se(n,"session: ");if(s!==null)return new Oe(s);let o=se(n,"control plane: ");if(o!==null)return new nt(o);let a=se(n,"identity: ");if(a!==null)return new ge(a);let d=se(n,"ice configuration: ");if(d!==null){let l=/^the iceServers entry (.+?) names this connection's peer RTC endpoint (.+?); a peer cannot be its own STUN server\./.exec(d);if(l)return new rt(l[1]??"",l[2]??"")}let c=/^not the leader: this tab holds generation (\d+)(?:, the leader holds (\d+))?$/.exec(n);if(c){let l=Number(c[1]),u=c[2]===void 0?null:Number(c[2]);return new it(l,u)}return null}function $n(n){if(n===Wn)return{type:"iceTimeout"};let e=/^no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to (.+) went unanswered$/.exec(n);if(e){let i=(e[1]??"").split(", "),s=i[0]??"",o=at(!0,!0,s,i);return o===null?null:{type:"udpBlocked",evidence:o}}let t=se(n,"the DataChannel closed: ");if(t!==null)return{type:"channelClosed",detail:t};let r=se(n,"this browser refused the attempt: ");return r!==null?{type:"unsupported",detail:r}:null}function Bn(n){let e=/^refused \((\d+)\): ([\s\S]*)$/.exec(n);if(e)return{type:"refused",status:Number(e[1]),message:e[2]??""};if(n==="the call's deadline elapsed")return{type:"timeout"};if(n==="the session carrying the call went away")return{type:"sessionLost"};let t=/^the leader holding generation (\d+) was replaced$/.exec(n);if(t)return{type:"leaderLost",generation:Number(t[1])};let r=/^the local deadline of (\d+)ms elapsed before the tab running the node answered; the remote operation may still have executed \(it was not retried\)$/.exec(n);if(r)return{type:"indeterminate",deadlineMs:Number(r[1])};let i=se(n,"the reply did not decode: ");return i!==null?{type:"malformed",detail:i}:null}function _i(n){return n instanceof oe&&n.failure.type==="udpBlocked"}function se(n,e){return n.startsWith(e)?n.slice(e.length):null}var Fn=["node_id","peer_node","channel_hash","origin_hash","stream_id","dialog","not_after","call_id","seq","generation","incarnation","version","from","to"];function me(n){let e;try{e=dt(n)}catch{return{type:"unknown",tag:null,raw:n}}if(e===null||typeof e!="object")return{type:"unknown",tag:null,raw:e};let t=e,r=typeof t.type=="string"?t.type:null;switch(r){case"connected":return{type:"connected",nodeIdHex:$(t,"node_id_hex"),peerNode:$(t,"peer_node"),rtcAddr:Bt(t,"rtc_addr"),rtcAddrs:Pi(t)};case"disconnected":return{type:"disconnected",reason:$(t,"reason")};case"channel_message":return{type:"channel_message",channelHash:$(t,"channel_hash"),originHash:$(t,"origin_hash"),payload:$t(t,"payload")};case"stream_data":return{type:"stream_data",peerNode:$(t,"peer_node"),incarnation:$(t,"incarnation"),streamId:$(t,"stream_id"),seq:Ut(t,"seq"),payload:$t(t,"payload")};case"announcement":return{type:"announcement",nodeId:$(t,"node_id"),capabilities:ji(t,"capabilities"),rtcAddr:Bt(t,"rtc_addr"),verified:t.verified===!0};case"signal":return{type:"signal",from:$(t,"from"),to:$(t,"to"),dialog:$(t,"dialog"),kind:$(t,"kind"),payload:$t(t,"payload"),notAfter:$(t,"not_after")};case"rpc_response":return{type:"rpc_response",callId:$(t,"call_id"),status:Ut(t,"status")};case"dropped":return{type:"dropped",reason:$(t,"reason"),subprotocol:Ut(t,"subprotocol")};case"rtc_failure":return{type:"rtc_failure",error:b($(t,"error"))};default:return{type:"unknown",tag:r,raw:t}}}var Ae=class{typed=new Map;any=new Set;queues=new Set;on(e,t){let r=this.typed.get(e)??new Set;this.typed.set(e,r);let i=t;return r.add(i),()=>{r.delete(i)}}onAny(e){return this.any.add(e),()=>{this.any.delete(e)}}events(){let e=new we(()=>this.queues.delete(e));return this.queues.add(e),e}deliver(e,t){this.dispatch(t?t(e):me(e))}dispatch(e){for(let t of this.typed.get(e.type)??[])Jn(t,e);for(let t of this.any)Jn(t,e);for(let t of this.queues)t.push(e)}close(){this.typed.clear(),this.any.clear();for(let e of[...this.queues])e.end();this.queues.clear()}};function Jn(n,e){try{n(e)}catch(t){console.error("[@net-mesh/browser] event listener threw",t)}}function dt(n){let e=Fn.join("|"),t=n.replace(new RegExp(`("(?:${e})"\\s*:\\s*)(\\d+)`,"g"),'$1"$2"');return JSON.parse(t)}function $(n,e){let t=n[e];return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):""}function Pi(n){let e=n.rtc_addrs;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.length>0);let t=Bt(n,"rtc_addr");return t===null?[]:[t]}function Bt(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:null}function Ut(n,e){let t=n[e];if(typeof t=="number")return t;if(typeof t=="string"){let r=Number(t);return Number.isFinite(r)?r:0}return 0}function ji(n,e){let t=n[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function $t(n,e){let t=n[e];return t instanceof Uint8Array?t:typeof t!="string"?new Uint8Array(0):Vn(t)}function Vn(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Jt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Re=class{live=new Set;add(e){this.live.add(e)}delete(e){this.live.delete(e)}retireAll(e){let t=[...this.live];this.live.clear();let r=[];for(let i of t)try{i.retire(e)}catch(s){r.push(s)}return r}},be=class{constructor(e,t,r){this.inner=e;this.onCancel=t;this.onDone=r}inner;onCancel;onDone;terminal=null;failure=null;handleDropped=!1;waiters=[];next(){if(this.failure!==null)return Promise.reject(this.failure);if(this.terminal!==null)return Promise.resolve(this.terminal);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),i={resolve:t,reject:r};return this.waiters.push(i),this.inner.next().then(s=>{Ue(this.waiters,i);let o=Ci(s);o.done&&this.complete(o),t(o)},s=>{Ue(this.waiters,i);let o=b(s);this.fail(o),r(o)}),e}cancel(){this.retire(new D)}retire(e){this.terminal!==null||this.failure!==null||(this.dropHandle(),this.complete({done:!0,error:e}))}[Symbol.asyncIterator](){let e=!1;return{next:async()=>{if(e)return{done:!0,value:void 0};let t=await this.next();if(t.error!==void 0)throw t.error;return t.value===void 0?(e=!0,{done:!0,value:void 0}):(t.done&&(e=!0),{done:!1,value:t.value})},return:async()=>(e=!0,this.cancel(),{done:!0,value:void 0})}}complete(e){if(this.terminal!==null)return;this.terminal=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.resolve(e)}fail(e){if(this.terminal!==null||this.failure!==null)return;this.failure=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.onCancel()}catch{}}}},_e=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;failure=null;handleDropped=!1;waiters=[];async send(e){if(this.failure!==null)throw this.failure;try{await this.inner.send(e)}catch(t){throw b(t)}}finish(){if(this.failure!==null)return Promise.reject(this.failure);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),i={reject:r};return this.waiters.push(i),this.inner.finish().then(s=>{Ue(this.waiters,i),this.onDone?.(),t(s)},s=>{Ue(this.waiters,i),this.onDone?.(),r(b(s))}),e}cancel(){this.retire(new D)}retire(e){if(this.failure!==null)return;if(this.failure=e,!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}},Pe=class{constructor(e,t){this.inner=e;this.onDone=t;this.stream=new be(e.stream(),()=>this.dropHandle(),()=>this.onDone?.()),this.sink={send:async r=>{if(this.failure!==null)throw this.failure;try{await this.inner.send(r)}catch(i){throw b(i)}},finishSending:async()=>{if(this.failure!==null)throw this.failure;try{await this.inner.finish_sending()}catch(r){throw b(r)}},cancel:()=>{this.retire(new D)}}}inner;onDone;handleDropped=!1;failure=null;sink;stream;retire(e){this.failure??=e,this.dropHandle(),this.stream.retire(e),this.onDone?.()}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}}},Ke=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.verdict??=ct(t),this.verdict),()=>(this.verdict??="replaced",this.verdict))}inner;retired;verdict=null;async send(e){if(this.verdict!==null)throw new D(lt);try{await this.inner.send(e)}catch(t){throw b(t)}}async close(){if(this.verdict!==null)throw new D(lt);try{await this.inner.close()}catch(e){throw b(e)}}},ze=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.settle(ct(t)),this.verdict),()=>(this.settle("replaced"),this.verdict))}inner;retired;verdict=null;waiters=[];next(){if(this.verdict!==null)return Promise.resolve({done:!0});let{promise:e,resolve:t}=Promise.withResolvers();return this.waiters.push(t),this.inner.next().then(r=>{Ue(this.waiters,t),t(Ii(r))},()=>{Ue(this.waiters,t),t({done:!0})}),e}[Symbol.asyncIterator](){return{next:async()=>{let e=await this.next();return e.done||e.value===void 0?{done:!0,value:void 0}:{done:!1,value:e.value}},return:async()=>({done:!0,value:void 0})}}settle(e){if(this.verdict!==null)return;this.verdict=e;let t=[...this.waiters];this.waiters.length=0;for(let r of t)r({done:!0})}},X=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;closed=!1;get service(){return this.inner.service()}close(){this.closed||(this.closed=!0,this.onDone?.(),this.inner.close())}retire(e){this.close()}};function ne(n){return{credentials:{membership:n.credentials.membership,dispatcher:n.credentials.dispatcher,...n.credentials.capabilityGrant===void 0?{}:{capabilityGrant:n.credentials.capabilityGrant},actingOrg:n.credentials.actingOrg,providerOwnerOrg:n.credentials.providerOwnerOrg,provider:n.credentials.provider,...n.credentials.proofTtlSecs===void 0?{}:{proofTtlSecs:n.credentials.proofTtlSecs}},...n.deadlineMs===void 0?{}:{deadlineMs:n.deadlineMs},...n.streamWindowInitial===void 0?{}:{streamWindowInitial:n.streamWindowInitial},...n.requestWindowInitial===void 0?{}:{requestWindowInitial:n.requestWindowInitial}}}function re(n){return{ownerOrg:n.ownerOrg}}function Xe(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new Ne("the caller attribution is not an OrgCaller object");let t=e;return{entity:String(t.entity??""),actingOrg:String(t.actingOrg??""),providerOrg:String(t.providerOrg??""),provider:String(t.provider??""),capability:String(t.capability??""),isSameOrg:t.isSameOrg===!0}}function ut(n){return async(e,t)=>await n(Xe(e),t)}function pt(n){return async(e,t,r)=>{await n(Xe(e),t,new Ke(r))}}function ft(n){return async(e,t)=>await n(Xe(e),new ze(t))}function ht(n){return async(e,t,r)=>{await n(Xe(e),new ze(t),new Ke(r))}}function Ue(n,e){let t=n.indexOf(e);t>=0&&n.splice(t,1)}function Ci(n){return n.done?n.error!==void 0?{done:!0,error:Wt(n.error)}:n.value===void 0?{done:!0}:{done:!0,value:n.value}:{done:!1,value:n.value}}function Ii(n){return n.done?{done:!0}:{done:!1,value:n.value}}var Ft=class extends Oe{constructor(e){super(e),this.name="StreamIdentityError"}},je=class{constructor(e,t,r="required"){this.inner=e;this.onClosed=t;if(this.wireId=Kn(()=>e.stream_id_hex()),this.peerId=Kn(()=>e.peer_node_hex()),r==="required"&&this.peerId===null)throw new Ft("the stream did not report a readable peer, so its frames cannot be attributed");e.on_message(i=>this.receive(i))}inner;onClosed;queues=new Set;listeners=new Set;pending=[];closed=!1;wireId;peerId;get peerNode(){return this.inner.peer_node_hex()}get reliability(){return this.inner.is_reliable()?"reliable":"fireAndForget"}get streamId(){return this.inner.stream_id_hex()}async send(e){if(this.closed)throw new Oe("the stream is closed");try{await this.inner.send(e)}catch(t){throw b(t)}}onMessage(e){this.listeners.add(e);let t=this.pending.splice(0,this.pending.length);for(let r of t)e(r);return()=>{this.listeners.delete(e)}}[Symbol.asyncIterator](){let e=new we(()=>this.queues.delete(e));this.queues.add(e);let t=this.pending.splice(0,this.pending.length);for(let r of t)e.push(r);return this.closed&&e.end(),e}close(){if(!this.closed){this.closed=!0;for(let e of[...this.queues])e.end();this.queues.clear(),this.listeners.clear(),this.onClosed?.(),this.inner.close()}}receive(e){let t=this.decode(e);if(!(t===null||this.closed)){if(this.queues.size===0&&this.listeners.size===0){this.pending.push(t);return}for(let r of this.listeners)try{r(t)}catch(i){console.error("[@net-mesh/browser] stream listener threw",i)}for(let r of this.queues)r.push(t)}}decode(e){if(e instanceof Uint8Array)return e;if(typeof e!="string")return console.error("[@net-mesh/browser] stream callback received",typeof e,"not the leaf event JSON"),null;let t=me(e);return t.type!=="stream_data"||!/^\d+$/.test(t.streamId)||this.wireId!==null&&BigInt(t.streamId)!==this.wireId||this.peerId!==null&&(!/^\d+$/.test(t.peerNode)||BigInt(t.peerNode)!==this.peerId)?null:t.payload}};function Kn(n){let e;try{e=n()}catch{return null}return e===void 0||!/^[0-9a-fA-F]{1,16}$/.test(e)?null:BigInt(`0x${e}`)}var zn="no verified announcement for",Hi="no live attempt with",Li="no verified offer from",Ti="is not the live attempt",Di=50,Mi=5e3;function qi(n){switch(n.type){case"direct":case"iceTimeout":case"udpBlocked":return!0;case"superseded":return n.liveDialog!==null;default:return!1}}var $e=class n{#e=new Map;#t=new Map;connect(e,t,r){let i=e.toLowerCase(),s=this.#e.get(i);if(s!==void 0)return s;let o=this.#t.get(i),a=(async()=>{if(o!==void 0){let c=await o.catch(()=>null);if(c!==null&&qi(c))return c}let d=await t();return d!=null?{type:"direct",peer:e,dialog:d}:r()})();return n.#r(this.#e,i,a)}accept(e,t){let r=e.toLowerCase(),i=this.#t.get(r);return i!==void 0?i:n.#r(this.#t,r,t())}static#r(e,t,r){e.set(t,r);let i=()=>{e.get(t)===r&&e.delete(t)};return r.then(i,i),r}};async function yt(n,e,t){let r;try{r=await e.offer(n)}catch(s){let o=b(s);if(o.message.includes(zn))return{type:"noAnnouncement",peer:n,detail:o.message};throw o}let i=await Xn(n,r,s=>s.state==="open",e,t);return i.type!=="direct"?i:Vt(n,r,e)}async function gt(n,e,t){let r=null,i=Date.now()+Mi;for(;;)try{r=await e.acceptOffer(n);break}catch(s){let o=b(s);if(o.message.includes(zn))return{type:"noAnnouncement",peer:n,detail:o.message};if(!o.message.includes(Li)||Date.now()>=i)throw o;await Yn()}return Xn(n,r,s=>s.direct,e,t)}async function Vt(n,e,t){let r;try{r=await t.handshake(n,e)}catch(i){let s=Gn(i,n,e);return s!==null?s:{type:"handshakeFailed",peer:n,dialog:e,detail:b(i).message}}return r!==e?{type:"superseded",peer:n,dialog:e,liveDialog:r}:{type:"direct",peer:n,dialog:e}}async function Xn(n,e,t,r,i){for(;;){let s;try{s=i(await r.candidate(n,e))}catch(o){let a=Gn(o,n,e);if(a!==null)return a;throw b(o)}if(s.dialog!==e)return{type:"superseded",peer:n,dialog:e,liveDialog:s.dialog};if(t(s))return{type:"direct",peer:n,dialog:e};if(s.state==="iceTimeout")return{type:"iceTimeout",peer:n,dialog:e};if(s.state==="udpBlocked")return{type:"udpBlocked",peer:n,dialog:e};if(s.state==="failed")return{type:"handshakeFailed",peer:n,dialog:e,detail:s.candidateError??"the attempt reached its terminal transition without installing a session"};await Yn()}}function Gn(n,e,t){let{message:r}=b(n);return r.includes(Ti)?{type:"superseded",peer:e,dialog:t,liveDialog:Ni(r)}:r.includes(Hi)?{type:"superseded",peer:e,dialog:t,liveDialog:null}:null}function Ni(n){return/\(dialog ([0-9a-f]{16}) is\)/.exec(n)?.[1]??null}async function Yn(){let n=Promise.withResolvers();setTimeout(n.resolve,Di),await n.promise}function zt(n){let e=n.trim().split(/\s+/);return e.some((t,r)=>t==="typ"&&e[r+1]==="srflx")}function Xt(n){return"candidate"in n?zt(n.candidate):"error"in n?n.error<Bi:!1}function Zn(n){if(n.some(Xt))return"answered";let e=n.some(r=>"candidate"in r);return n.some(r=>"ice"in r&&r.ice==="failed")&&!e?"notRun":"unanswered"}function Wi(n){return Zn(n)==="answered"}function er(n){let{bootstrapOk:e,stunProbe:t,probed:r}=n;return r===null?{type:"iceTimeout"}:mt({bootstrapOk:e,probes:[{probed:r,stunProbe:t}]})}function mt(n){let{bootstrapOk:e,probes:t}=n;if(t.length===0||t.some(s=>s.stunProbe.type!=="unanswered"))return{type:"iceTimeout"};let r=t.map(s=>s.probed),i=at(e,!0,r[0]??"",r);return i===null?{type:"iceTimeout"}:{type:"udpBlocked",evidence:i}}function Ui(n){return new oe(er(n))}var $i=2500,Bi=700,Kt=3478;async function tr(n,e={}){let t=nr(n);if(t===null)return{type:"notRun",reason:`not an address: ${n}`};let r=e.peerConnectionFactory??Fi();if(r===null)return{type:"unsupported",detail:"RTCPeerConnection is not available in this context"};let i=e.timeoutMs??$i,{promise:s,resolve:o}=Promise.withResolvers(),a;try{a=r({iceServers:[{urls:t}],iceCandidatePoolSize:0})}catch(f){return{type:"unsupported",detail:String(f)}}let d=!1,c=f=>{d||(d=!0,o(f))},l=null,u=setTimeout(()=>c({type:"unanswered",detail:l??"no answer inside the probe deadline"}),i),p=()=>{c({type:"unanswered",detail:l??"gathering completed with no reflexive candidate"})},y=!1;a.oniceconnectionstatechange=()=>{a.iceConnectionState==="failed"&&!y&&c({type:"notRun",reason:"the engine failed the probe connection before gathering any candidate"})},a.onicecandidate=f=>{let w=f.candidate;if(w===null){p();return}y=!0;let R=rr(w);R!==null&&c({type:"reflexive",address:R})},a.onicecandidateerror=f=>{let w=f.errorCode,R=`${w}: ${f.errorText} (${f.url})`;if(Xt({error:w})){c({type:"stunError",code:w,detail:R});return}l=R},a.onicegatheringstatechange=()=>{a.iceGatheringState==="complete"&&p()};try{a.createDataChannel("net-udp-probe"),await a.setLocalDescription(await a.createOffer())}catch(f){c({type:"unsupported",detail:String(f)})}try{return await s}finally{clearTimeout(u),a.onicecandidate=null,a.onicecandidateerror=null,a.oniceconnectionstatechange=null,a.onicegatheringstatechange=null,a.close()}}async function Gt(n,e={}){return Promise.all(n.map(async t=>({probed:t,stunProbe:await tr(t,e)})))}var Ji=3e3;async function Yt(n,e={}){let t=e.fetchImpl??globalThis.fetch;if(typeof t!="function")return!1;try{return await t(n,{method:"GET",mode:"no-cors",cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(e.timeoutMs??Ji)}),!0}catch{return!1}}function nr(n){let e=n.trim();if(e.length===0)return null;if(e.startsWith("stun:")||e.startsWith("stuns:"))return e;let t=/^\[([0-9a-fA-F:.]+)\](?::(\d+))?$/.exec(e);if(t)return`stun:[${t[1]??""}]:${t[2]??Kt}`;if((e.match(/:/g)?.length??0)>1)return`stun:[${e}]:${Kt}`;let r=/^([A-Za-z0-9._-]+)(?::(\d+))?$/.exec(e);return r===null?null:`stun:${r[1]??""}:${r[2]??Kt}`}function rr(n){return n.type==="srflx"?n.address??Qn(n.candidate):n.type!==null?null:zt(n.candidate)?Qn(n.candidate):null}function Qn(n){let e=n.split(" "),t=e[4]??"",r=e[5]??"";return r.length>0?`${t}:${r}`:t}function Fi(){return typeof RTCPeerConnection>"u"?null:n=>new RTCPeerConnection(n)}var Qt=new Map;async function Ge(n={}){if(n.wasm)return n.wasm;let e=n.wasmModule??new URL("./net_leaf.js",import.meta.url).href,t=`${e}|${String(n.wasmUrl??"")}`,r=Qt.get(t);if(r)return r;let i=Vi(e,n.wasmUrl);Qt.set(t,i);try{return await i}catch(s){throw Qt.delete(t),s}}async function Vi(n,e){let t=await import(n),r=Ki(t,n);return r.default&&await r.default(e===void 0?void 0:{module_or_path:e}),r}function Ki(n,e){if(n===null||typeof n!="object"||!("LeafNode"in n))throw new Error(`${e} is not a net-mesh-leaf module: no LeafNode export`);let t=n.LeafNode;if(typeof t!="function"||!("connect"in t))throw new Error(`${e} exports a LeafNode without a static connect()`);if(typeof t.connect!="function")throw new Error(`${e} exports a LeafNode whose connect is not callable`);return n}function Ce(n,e){if(typeof n=="string")return n;let t=typeof n=="object"&&n!==null?Object.prototype.toString.call(n):String(n);throw new TypeError(`${t} is not a ${e} id: a ${e} id crosses this boundary as 16 hex digits as a STRING \u2014 the spelling this boundary hands out; a ${typeof n} is refused rather than coerced, because a number cannot carry a u64 id`)}function sr(n){if(!/^\d+$/.test(n))throw new TypeError(`a decimal node id is digits only, got ${JSON.stringify(n)}`);let e=BigInt(n);if(e>0xffffffffffffffffn)throw new TypeError(`${n} does not fit in a u64 node id`);return e.toString(16).padStart(16,"0")}var St=class{constructor(e,t,r,i){this.inner=e;this.bootstrapUrl=t;this.failureTyping=r;this.nodeId=e.node_id_hex(),this.anchorRtcAddr=i,e.on_event(s=>this.ingest(s))}inner;bootstrapUrl;failureTyping;hub=new Ae;nodeId;closed=!1;streams=new Set;attempts=new $e;orgHandles=new Re;anchorRtcAddr;anchorRtcAddrs=[];bootstrapObserved=!1;nodeIdHex(){return this.nodeId}anchorIdHex(){return this.inner.anchor_id_hex()}originHashHex(){return this.inner.origin_hash_hex()}async enroll(){try{await this.inner.enroll()}catch(e){throw b(e)}}isEnrolled(){return this.inner.is_enrolled()}async call(e,t,r){try{return await this.inner.call(e,t,r)}catch(i){throw b(i)}}async subscribe(e){try{await this.inner.subscribe(e)}catch(t){throw b(t)}}async publish(e,t){try{await this.inner.publish(e,t)}catch(r){throw b(r)}}openStream(e){let t;try{t=this.inner.open_stream(e)}catch(i){throw b(i)}let r=new je(t,()=>this.streams.delete(r));return this.streams.add(r),r}async callOrg(e,t,r){try{return await this.inner.call_org(e,t,ne(r))}catch(i){throw b(i)}}async callOrgStreaming(e,t,r){try{let i=await this.inner.call_org_streaming(e,t,ne(r)),s=new be(i,()=>i.cancel(),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(i){throw b(i)}}async callOrgClientStream(e,t){try{let r=await this.inner.call_org_client_stream(e,ne(t)),i=new _e(r,()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(r){throw b(r)}}async callOrgDuplex(e,t){try{let r=await this.inner.call_org_duplex(e,ne(t)),i=new Pe(r,()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(r){throw b(r)}}serveOrg(e,t,r,i){try{let s=new X(this.inner.serve_org(e,t,ut(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgStreaming(e,t,r,i){try{let s=new X(this.inner.serve_org_streaming(e,t,pt(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgClientStream(e,t,r,i){try{let s=new X(this.inner.serve_org_client_stream(e,t,ft(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgDuplex(e,t,r,i){try{let s=new X(this.inner.serve_org_duplex(e,t,ht(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}async signal(e,t,r,i){try{await this.inner.signal(Ce(e,"peer"),Ce(t,"dialog"),r,i)}catch(s){throw b(s)}}async connectPeer(e){let t;try{t=Ce(e,"peer")}catch(r){throw b(r)}return this.attempts.connect(e,()=>{try{return this.inner.peer_direct_dialog(t)}catch(r){throw b(r)}},()=>yt(e,this.peerPrimitives(),Ie))}peerPrimitives(){return{offer:e=>this.inner.peer_offer(e),acceptOffer:e=>this.inner.peer_accept_offer(e),candidate:(e,t)=>this.inner.peer_candidate_in(e,t),handshake:(e,t)=>this.inner.peer_handshake_in(e,t)}}async handshakePeer(e,t){return Vt(e,t,this.peerPrimitives())}async acceptPeer(e){return this.attempts.accept(e,()=>gt(e,this.peerPrimitives(),Ie))}async peerAttempt(e){try{return Ie(await this.inner.peer_candidate(e))}catch(t){throw b(t)}}counters(){return vt(this.inner.counters_json())}rtcStats(){return or(this.inner.rtc_stats_json())}enableNetworkRetry(){try{this.inner.arm_network_retry()}catch(e){throw b(e)}}retryReport(){return ar(this.inner.retry_report())}async announce(e){try{await this.inner.announce([...e])}catch(t){throw b(t)}}async query(e){let t;try{t=await this.inner.query(e)}catch(r){throw b(r)}return Ot(t)}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}events(){return this.hub.events()}async refineIceFailure(e){return Zt(e,{bootstrapUrl:this.bootstrapUrl,bootstrapObserved:this.bootstrapObserved,anchorRtcAddr:this.anchorRtcAddr,anchorRtcAddrs:this.anchorRtcAddrs,failureTyping:this.failureTyping})}close(){if(this.closed)return;this.closed=!0;let e=[];for(let r of this.orgHandles.retireAll(new D("org:rpc:cancelled: the node is closed")))e.push(b(r));let t=[...this.streams];this.streams.clear();for(let r of t)try{r.close()}catch(i){e.push(b(i))}try{this.hub.close()}catch(r){e.push(b(r))}try{this.inner.close()}catch(r){e.push(b(r))}if(e.length>0)throw new AggregateError(e,`close: ${e.length} of this node's teardown steps failed`)}ingest(e){let t=me(e);t.type==="connected"&&(this.bootstrapObserved=!0,t.rtcAddr!==null&&(this.anchorRtcAddr=t.rtcAddr),t.rtcAddrs.length>0&&(this.anchorRtcAddrs=t.rtcAddrs)),this.hub.dispatch(t)}};async function zi(n){let e=wt(n),t=n.failureTyping??{},r=await Ge(n);try{let i=await r.LeafNode.connect(e);return new St(i,n.bootstrapUrl??null,t,n.anchorRtcAddr??null)}catch(i){throw await Zt(b(i),{bootstrapUrl:n.bootstrapUrl??null,bootstrapObserved:!1,anchorRtcAddr:n.anchorRtcAddr??null,failureTyping:t})}}function wt(n){return{credentialB64:Yi(n),origin:n.origin??Qi(),...n.bootstrapUrl===void 0?{}:{bootstrapUrl:n.bootstrapUrl},...n.iceServers?{iceServers:n.iceServers}:{},...Xi(n)}}function vt(n){let e=JSON.parse(n);if(e===null||typeof e!="object")return{};let t={};for(let[r,i]of Object.entries(e))t[r]=typeof i=="string"?i:String(i);return t}function Ie(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`peer_candidate did not answer an object: ${n}`);let t=e,r=t.state;if(r!=="gathering"&&r!=="open"&&r!=="iceTimeout"&&r!=="udpBlocked"&&r!=="failed")throw new TypeError(`peer_candidate answered an unknown state: ${String(r)}`);let i=t.candidateError;return{dialog:String(t.dialog??""),state:r,sent:Number(t.sent??0),applied:Number(t.applied??0),answered:t.answered===!0,direct:t.direct===!0,remainingMs:String(t.remainingMs??"0"),candidateError:typeof i=="string"?i:null}}function or(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`rtc_stats_json did not answer an object: ${n}`);let t={},r={};for(let[i,s]of Object.entries(e)){if(i==="not_applicable"){if(s===null||typeof s!="object")continue;for(let[o,a]of Object.entries(s))r[o]=String(a);continue}t[i]=typeof s=="string"?s:String(s)}return{counters:t,notApplicable:r}}function ar(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`retry_report did not answer an object: ${n}`);let t=e;return{armed:t.armed===!0,online:String(t.online??"0"),iceFailed:String(t.iceFailed??"0"),triggers:String(t.triggers??"0"),started:String(t.started??"0"),coalesced:String(t.coalesced??"0"),notEligible:String(t.notEligible??"0"),openEpisodes:Number(t.openEpisodes??0),owned:Number(t.owned??0),last:typeof t.last=="string"?t.last:null}}async function Zt(n,e){if(!(n instanceof oe)||n.failure.type!=="iceTimeout"||e.failureTyping.probeOnIceTimeout===!1)return n;let t=e.anchorRtcAddrs!==void 0&&e.anchorRtcAddrs.length>0?e.anchorRtcAddrs:e.anchorRtcAddr!==null?[e.anchorRtcAddr]:[];if(t.length===0)return n;let r=await Gt(t,e.failureTyping.stun);if(r.some(s=>s.stunProbe.type!=="unanswered"))return n;let i=e.bootstrapObserved||e.bootstrapUrl!==null&&await Yt(e.bootstrapUrl,e.failureTyping.bootstrap);return new oe(mt({bootstrapOk:i,probes:r}))}function Ot(n){let e=dt(n);if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let i={...r},s=i.capabilities,o=Gi(i.node_id);t.push({nodeId:o,peerIdHex:sr(o),entityId:bt(i.entity_id),capabilities:Array.isArray(s)?s.filter(a=>typeof a=="string"):[],rtcAddr:bt(i.rtc_addr),noisePubkey:bt(i.noise_pubkey),version:bt(i.version)})}return t}var ir=/^[0-9a-fA-F]{64}$/;function Xi(n){let{entitySecretHex:e,noiseSecretHex:t}=n;if(e===void 0){if(t!==void 0)throw new ge("noiseSecretHex was supplied without entitySecretHex: the leaf would generate the entity half, so the identity would not be the one you meant to inject");return{}}if(!ir.test(e))throw new ge(`entitySecretHex must be 32 bytes of hex (64 hex digits), got ${e.length} characters`);if(t===void 0)return{entitySecretHex:e};if(!ir.test(t))throw new ge(`noiseSecretHex must be 32 bytes of hex (64 hex digits), got ${t.length} characters`);return{entitySecretHex:e,noiseSecretHex:t}}function Gi(n){return typeof n=="string"?n:typeof n=="number"?String(n):""}function bt(n){return typeof n=="string"?n.length>0?n:null:typeof n=="number"?String(n):null}function Yi(n){if(n.credentialB64!==void 0)return n.credentialB64;let e=n.credential;if(typeof e=="string")return e;if(e instanceof Uint8Array)return Jt(e);throw new Error("connect() needs a credential: pass credentialB64 or credential")}function Qi(){let n=globalThis.location?.origin;if(typeof n=="string"&&n.length>0)return n;throw new Error("connect() needs an origin: there is no location.origin in this context")}function en(n){let e=me(n);return e.type!=="unknown"?e:Zi(e)??e}function tn(n){switch(n.type){case"leader_changed":case"subscription_restored":case"leader_lost":case"generation_fenced":case"not_leader":case"promotion_failed":return!0;default:return!1}}function Zi(n){let e=n.raw;if(e===null||typeof e!="object")return null;let t={...e};switch(n.tag){case"leader_changed":return{type:"leader_changed",generation:He(t.generation)};case"subscription_restored":return{type:"subscription_restored",channel:typeof t.channel=="string"?t.channel:""};case"leader_lost":{let r=Number(t.failed);return{type:"leader_lost",generation:He(t.generation),failed:Number.isFinite(r)?r:0}}case"generation_fenced":return{type:"generation_fenced",presented:He(t.presented),current:He(t.current)};case"not_leader":return{type:"not_leader",presented:He(t.presented),current:He(t.current)};case"promotion_failed":return{type:"promotion_failed",generation:He(t.generation),detail:typeof t.detail=="string"?t.detail:""};default:return null}}function He(n){return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):"0"}function nn(n){let e=n.MeshSession;if(!(e!==null&&(typeof e=="object"||typeof e=="function")&&"open"in e&&typeof e.open=="function"))throw new Error("this net-mesh-leaf bundle has no MeshSession: leader election and the follower proxy need a wasm build from Stage 5 slice 3 or later");return n}var xt=class{constructor(e){this.inner=e;this.streamGeneration=e.generation(),e.on_event(t=>this.hub.deliver(t,en)),this.hub.onAny(t=>{if(t.type==="leader_lost"||t.type==="not_leader"){this.orgHandles.retireAll(new Z(this.streamGeneration)),this.endStreams();return}let r=this.inner.generation();if(r===this.streamGeneration)return;let i=this.streamGeneration;this.streamGeneration=r,this.orgHandles.retireAll(new Z(i)),this.endStreams()})}inner;hub=new Ae;streams=new Set;attempts=new $e;streamGeneration;orgHandles=new Re;closed=!1;role(){return this.inner.role()==="leader"?"leader":"follower"}generation(){return this.inner.generation()}nodeIdHex(){return this.inner.node_id_hex()??null}fingerprint(){return this.inner.fingerprint()}scope(){return this.inner.scope()}interruptionMs(){return this.inner.interruption_ms()??null}async call(e,t,r){return await this.guard(()=>this.inner.call(e,t,r))}async subscribe(e){await this.guard(()=>this.inner.subscribe(e))}async unsubscribe(e){await this.guard(()=>this.inner.unsubscribe(e))}async publish(e,t){await this.guard(()=>this.inner.publish(e,t))}async announce(e){await this.guard(()=>this.inner.announce([...e]))}async query(e){return Ot(await this.guard(()=>this.inner.query(e)))}async counters(){return vt(await this.guard(()=>this.inner.counters_json()))}async enroll(){await this.guard(()=>this.inner.enroll())}async isEnrolled(){return await this.guard(()=>this.inner.is_enrolled())}async signal(e,t,r,i){await this.guard(()=>this.inner.signal(Ce(e,"peer"),Ce(t,"dialog"),r,i))}async connectPeer(e){return this.attempts.connect(e,async()=>{try{return await this.inner.peer_direct_dialog(e)??void 0}catch{return}},()=>yt(e,this.peerPrimitives(),Ie))}async acceptPeer(e){return this.attempts.accept(e,()=>gt(e,this.peerPrimitives(),Ie))}peerPrimitives(){return{offer:e=>this.guard(()=>this.inner.peer_offer(e)),acceptOffer:e=>this.guard(()=>this.inner.peer_accept_offer(e)),candidate:(e,t)=>this.guard(()=>this.inner.peer_candidate(e,t)),handshake:(e,t)=>this.guard(()=>this.inner.peer_handshake(e,t))}}async openStream(e){let t=this.inner.generation(),r=new je(await this.guard(()=>this.inner.open_stream(e)));return this.closed||this.inner.generation()!==t?(r.close(),r):(this.streams.add(r),r)}async callOrg(e,t,r){return await this.guard(()=>this.inner.call_org(e,t,ne(r)))}async callOrgStreaming(e,t,r){let i=this.inner.generation(),s;try{let o=await this.inner.call_org_streaming(e,t,ne(r));s=new be(o,()=>o.cancel(),()=>this.orgHandles.delete(s))}catch(o){throw b(o)}return this.closed||this.inner.generation()!==i?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new Z(i)),s):(this.orgHandles.add(s),s)}async callOrgClientStream(e,t){let r=this.inner.generation(),i;try{let s=await this.inner.call_org_client_stream(e,ne(t));i=new _e(s,()=>this.orgHandles.delete(i))}catch(s){throw b(s)}return this.closed||this.inner.generation()!==r?(i.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new Z(r)),i):(this.orgHandles.add(i),i)}async callOrgDuplex(e,t){let r=this.inner.generation(),i;try{let s=await this.inner.call_org_duplex(e,ne(t));i=new Pe(s,()=>this.orgHandles.delete(i))}catch(s){throw b(s)}return this.closed||this.inner.generation()!==r?(i.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new Z(r)),i):(this.orgHandles.add(i),i)}serveOrg(e,t,r,i){try{let s=new X(this.inner.serve_org(e,t,ut(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgStreaming(e,t,r,i){try{let s=new X(this.inner.serve_org_streaming(e,t,pt(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgClientStream(e,t,r,i){try{let s=new X(this.inner.serve_org_client_stream(e,t,ft(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}serveOrgDuplex(e,t,r,i){try{let s=new X(this.inner.serve_org_duplex(e,t,ht(r),re(i)),()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(s){throw b(s)}}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}onLifecycle(e){return this.hub.onAny(t=>{tn(t)&&e(t)})}events(){return this.hub.events()}close(){this.closed||(this.closed=!0,this.orgHandles.retireAll(new D("org:rpc:cancelled: the session is closed")),this.endStreams(),this.hub.close(),this.inner.close())}endStreams(){let e=[...this.streams];this.streams.clear();for(let t of e)t.close()}async guard(e){try{return await e()}catch(t){throw b(t)}}};async function es(n){let e=nn(await Ge(n)),t={...wt(n),...n.capabilities?{capabilities:[...n.capabilities]}:{},...n.subscriptions?{subscriptions:[...n.subscriptions]}:{},...n.dbName===void 0?{}:{dbName:n.dbName},...n.lockScope===void 0?{}:{lockScope:n.lockScope}};try{return new xt(await e.MeshSession.open(t))}catch(r){throw b(r)}}var lr=["invalid-data","version-mismatch","forbidden","not-ready","capacity","timeout","aborted","indeterminate","owner-lost","closed","action-rejected","result-expired"],h=class extends Error{code;constructor(e,t,r){super(t,r),this.name="StoreError",this.code=e}};function kt(n){return(n instanceof Error?n.message:String(n)).includes("stale stream handle")}var Et=Object.freeze({$hidden:!0});function At(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.keys(n).length===1&&n.$hidden===!0}function ts(n){return e=>At(e)?Et:n(e)}var cr=Object.freeze({"card-game":Object.freeze({"players.*.hand":"owner",deck:"nobody","deck.length":"everyone"})}),ns=/^(\*|[^.*]+)$/;function Le(n){let e;if(n==="open")e={};else if(typeof n=="string"){let i=cr[n];if(i===void 0)throw new h("invalid-data",`unknown visibility preset '${n}'`);e={...i}}else if(typeof n=="object"&&n!==null){let{preset:i,...s}=n;if(e={},i!==void 0){let o=cr[i];if(o===void 0)throw new h("invalid-data",`unknown visibility preset '${String(i)}'`);Object.assign(e,o)}Object.assign(e,s)}else throw new h("invalid-data","visibility is a preset name or an object of path \u2192 rule");let t=[],r=!1;for(let[i,s]of Object.entries(e)){let o=i.split(".");if(i.length===0||!o.every(c=>ns.test(c)))throw new h("invalid-data",`visibility path '${i}' is not dot-separated keys and '*'`);let a=o.length>1&&o[o.length-1]==="length";if(!(s==="everyone"||s==="nobody"||s==="owner"||Array.isArray(s)&&s.length>0&&s.every(c=>typeof c=="string"&&c.length>0)))throw new h("invalid-data",`visibility rule for '${i}' must be 'everyone', 'nobody', 'owner' or a non-empty list of audiences`);if(s==="owner"){if(!o.includes("*"))throw new h("invalid-data",`'owner' needs a '*' in the path to name the owner: '${i}'`);r=!0}t.push(Object.freeze({path:i,segments:Object.freeze(o),rule:s,counts:a}))}return t.sort((i,s)=>i.segments.length-s.segments.length),Object.freeze({rules:Object.freeze(t),perPlayer:r})}function dr(n,e,t){return n==="everyone"?!0:n==="nobody"||t===null?!1:n==="owner"?e[0]===t.peer:n.some(r=>t.audience.includes(r))}function rs(n,e){let t=[],r=(i,s,o,a)=>{if(s===e.length){t.push({keys:[...o],captures:[...a],value:i});return}if(typeof i!="object"||i===null)return;let d=e[s];if(d==="*"){let c=Array.isArray(i)?i.map((l,u)=>[u,l]):Object.entries(i);for(let[l,u]of c)r(u,s+1,[...o,l],[...a,String(l)]);return}Array.isArray(i)||!Object.prototype.hasOwnProperty.call(i,d)||r(i[d],s+1,[...o,d],a)};return r(n,0,[],[]),t}var rn=Symbol("drop");function is(n,e,t){let r=n;for(let i of e){let s=r.children.get(i);s===void 0&&(s={children:new Map},r.children.set(i,s)),r=s}r.value=t}function sn(n,e){if("value"in e)return e.value;if(e.children.size===0||typeof n!="object"||n===null)return n;if(Array.isArray(n)){let r=[];return n.forEach((i,s)=>{let o=e.children.get(s),a=o===void 0?i:sn(i,o);a!==rn&&r.push(a)}),r}let t={};for(let[r,i]of Object.entries(n)){let s=e.children.get(r),o=s===void 0?i:sn(i,s);o!==rn&&(t[r]=o)}return t}var ur="\0";function Te(n,e,t){if(n.rules.length===0)return e;let r={children:new Map},i=new Set,s=!1;for(let o of n.rules){if(o.counts)continue;let a=n.rules.find(c=>c.counts&&c.segments.length===o.segments.length+1&&c.segments.slice(0,-1).every((l,u)=>l===o.segments[u])),d=o.segments[o.segments.length-1]==="*";for(let c of rs(e,o.segments)){let l="",u=!1;for(let y=0;y<c.keys.length-1&&!u;y+=1)l=y===0?String(c.keys[0]):`${l}${ur}${String(c.keys[y])}`,u=i.has(l);if(u||dr(o.rule,c.captures,t))continue;let p=d?rn:Et;a!==void 0&&Array.isArray(c.value)&&dr(a.rule,c.captures,t)&&(p=c.value.map(()=>Et)),is(r,c.keys,p),i.add(c.keys.map(String).join(ur)),s=!0}}return s?sn(e,r):e}function pr(n,e,t){return n.visibility===void 0?e:Te(Le(n.visibility),e,t)}function ss(n,e,t,r){let i=pr(n,e,t);for(let s of r){let o=i;for(let d of s.split(".")){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,d)){o=void 0;break}o=o[d]}if(o!==void 0&&!At(o)&&!(Array.isArray(o)&&o.every(d=>At(d))))throw new Error(`'${s}' is visible to ${t===null?"nobody in particular":t.peer}`)}}function os(n){if(n.id.length===0)throw new h("invalid-data","a store definition needs a non-empty id");if(!Number.isSafeInteger(n.version)||n.version<1)throw new h("invalid-data",`store '${n.id}' needs a positive integer version, got ${String(n.version)}`);let e;try{e=n.empty()}catch(t){throw new h("invalid-data",`store '${n.id}' could not build its empty state: ${String(t)}`,{cause:t})}try{n.state(e)}catch(t){throw new h("invalid-data",`store '${n.id}': empty() is not a valid state, so a replica could not clear a projection with it: ${String(t)}`,{cause:t})}if(n.visibility!==void 0)try{Le(n.visibility)}catch(t){throw new h("invalid-data",`store '${n.id}': ${t instanceof Error?t.message:String(t)}`,{cause:t})}if(n.interest!==void 0){for(let[t,r]of Object.entries(n.interest))if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': interest maps a top-level collection name to a key function, got '${t}'`)}if(n.entities!==void 0)for(let[t,r]of Object.entries(n.entities)){if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': entities maps a top-level collection name to a per-entity parser, got '${t}'`);let i=e[t];if(i!==void 0&&!on(i))throw new h("invalid-data",`store '${n.id}': entities names '${t}', but empty().${t} is not a record of entities`)}return Object.freeze({...n})}function on(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var T=class extends Error{constructor(t,r){super(t);this.reason=t;this.at=r}reason;at};function De(n){let e=new an(n);try{return{ok:!0,value:e.document()}}catch(t){if(t instanceof T)return{ok:!1,reason:t.reason,at:t.at};throw t}}var an=class{constructor(e){this.src=e}src;i=0;document(){if(this.skipWhitespace(),this.i>=this.src.length)throw new T("empty",this.i);let e=this.value(0);if(this.skipWhitespace(),this.i!==this.src.length)throw new T("trailing-content",this.i);return e}value(e){let t=this.src.charCodeAt(this.i);switch(t){case 123:return this.object(e+1);case 91:return this.array(e+1);case 34:return this.string();default:break}if(t===45||t>=48&&t<=57)return this.number();if(this.src.startsWith("true",this.i))return this.i+=4,!0;if(this.src.startsWith("false",this.i))return this.i+=5,!1;if(this.src.startsWith("null",this.i))return this.i+=4,null;throw new T(Number.isNaN(t)?"unexpected-end":"literal",this.i)}object(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=Object.create(null);if(this.skipWhitespace(),this.peek()===125)return this.i+=1,t;for(;;){if(this.skipWhitespace(),this.peek()!==34)throw new T("unexpected-token",this.i);let r=this.i,i=this.string();if(Object.prototype.hasOwnProperty.call(t,i))throw new T("duplicate-key",r);if(this.skipWhitespace(),this.peek()!==58)throw new T("unexpected-token",this.i);this.i+=1,this.skipWhitespace(),t[i]=this.value(e),this.skipWhitespace();let s=this.peek();if(s===44){this.i+=1;continue}if(s===125)return this.i+=1,t;throw new T(s===-1?"unexpected-end":"unexpected-token",this.i)}}array(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=[];if(this.skipWhitespace(),this.peek()===93)return this.i+=1,t;for(;;){this.skipWhitespace(),t.push(this.value(e)),this.skipWhitespace();let r=this.peek();if(r===44){this.i+=1;continue}if(r===93)return this.i+=1,t;throw new T(r===-1?"unexpected-end":"unexpected-token",this.i)}}string(){this.i+=1;let e="";for(;;){if(this.i>=this.src.length)throw new T("unexpected-end",this.i);let t=this.src.charCodeAt(this.i);if(t===34)return this.i+=1,e;if(t===92){e+=this.escape();continue}if(t<32)throw new T("string-control-char",this.i);e+=this.src[this.i],this.i+=1}}escape(){this.i+=1;let e=this.src[this.i];switch(this.i+=1,e){case'"':return'"';case"\\":return"\\";case"/":return"/";case"b":return"\b";case"f":return"\f";case"n":return`
2
- `;case"r":return"\r";case"t":return" ";case"u":{let t=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t))throw new T("string-escape",this.i);return this.i+=4,String.fromCharCode(Number.parseInt(t,16))}default:throw new T("string-escape",this.i-1)}}number(){let e=this.i;if(this.peek()===45&&(this.i+=1),this.peek()===48){if(this.i+=1,this.isDigit(this.peek()))throw new T("number-grammar",e)}else if(this.isDigit(this.peek()))for(;this.isDigit(this.peek());)this.i+=1;else throw new T("number-grammar",e);if(this.peek()===46){if(this.i+=1,!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let t=this.src[this.i];if(t==="e"||t==="E"){this.i+=1;let i=this.peek();if((i===43||i===45)&&(this.i+=1),!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let r=Number(this.src.slice(e,this.i));if(!Number.isFinite(r))throw new T("number-not-finite",e);return r}isDigit(e){return e>=48&&e<=57}peek(){return this.i>=this.src.length?-1:this.src.charCodeAt(this.i)}skipWhitespace(){for(;;){let e=this.peek();if(e===32||e===9||e===10||e===13){this.i+=1;continue}return}}};var hr=1,G=32,fe=16,dn=16,as=32,ls=128,yr=256,gr=64,Se=1024*1024,ae=255,un=256,pn=8,Ye=64,cs=256,ds=18446744073709551615n,us=20,ps=["join","resume","resync","act","in","aud","alive","leave","int"],fs=["man","snap","delta","res","ok","no"],hs={join:{required:["v","k","q","def","ver","store","key","aud"],optional:["int"]},resume:{required:["v","k","q","h","aud"],optional:["int"]},int:{required:["v","k","q","h","int"],optional:[]},resync:{required:["v","k","q","h","g","have"],optional:[]},aud:{required:["v","k","q","h","aud"],optional:[]},alive:{required:["v","k","q","h"],optional:[]},leave:{required:["v","k","q","h"],optional:[]},act:{required:["v","k","q","h","s","name","in"],optional:[]},in:{required:["v","k","h","name","s","in"],optional:[]},man:{required:["v","k","h","inc","g","r","n","bytes"],optional:["q"]},snap:{required:["v","k","h","g","r","i","n","d"],optional:[]},delta:{required:["v","k","h","g","base","r","ops"],optional:[]},res:{required:["v","k","q","h","s","out"],optional:[]},ok:{required:["v","k","q","h"],optional:[]},no:{required:["v","k","code"],optional:["q","h","s","detail"]}},ys={join:["v","k","q","def","ver","store","key","aud","int"],resume:["v","k","q","h","aud","int"],int:["v","k","q","h","int"],resync:["v","k","q","h","g","have"],aud:["v","k","q","h","aud"],alive:["v","k","q","h"],leave:["v","k","q","h"],act:["v","k","q","h","s","name","in"],in:["v","k","h","name","s","in"],man:["v","k","q","h","inc","g","r","n","bytes"],snap:["v","k","h","g","r","i","n","d"],delta:["v","k","h","g","base","r","ops"],res:["v","k","q","h","s","out"],ok:["v","k","q","h"],no:["v","k","q","h","code","s","detail"]},ln=new Set(ps),fr=new Set(fs),gs=new Set(lr),ms=/^[A-Za-z0-9+/]+={0,2}$/;function B(n,e,t="invalid-data"){return{ok:!1,code:t,stage:n,reason:e}}var Rt=class{constructor(e){this.refusal=e}refusal};function L(n,e,t="invalid-data"){return new Rt(B(n,e,t))}function O(n){return n instanceof Rt}function U(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.codePointAt(t);r>65535&&(t+=1),e+=r<=127?1:r<=2047?2:r<=65535?3:4}return e}function Me(n,e){if(U(n)>e.maxBytes)return B("bytes","frame-too-large","capacity");let r=De(n);if(!r.ok)return B("json",r.reason);let i=r.value;if(typeof i!="object"||i===null||Array.isArray(i))return B("json","not-an-object");let s=i;if(s.v!==hr)return B("envelope","unknown-version");let o=s.k;if(typeof o!="string"||!(ln.has(o)||fr.has(o)))return B("envelope","unknown-kind");let a=o;if(!(e.as==="owner"?ln:fr).has(a))return B("direction",`wrong-direction:${a}`);let c=hs[a],l=new Set([...c.required,...c.optional]);for(let u of Object.keys(s))if(!l.has(u))return B("payload","unknown-field");for(let u of c.required)if(!Object.prototype.hasOwnProperty.call(s,u))return B("payload","missing-field");return bs(a,s)}function bs(n,e){let t=(c,l)=>{let u=e[c];return typeof u!="string"||u.length!==l||!ws(u)?L("payload",`non-canonical-hex:${c}`):u},r=c=>{let l=e[c];return typeof l!="string"||!mr(l)?L("payload",`non-canonical-decimal:${c}`):l},i=(c,l,u)=>{let p=e[c];return typeof p!="number"||!Number.isInteger(p)||p<l||p>u?L("payload",`bad-integer:${c}`):p},s=c=>{let l=e[c];return typeof l!="string"||l.length===0?L("payload",`bad-string:${c}`):l},o=c=>{let l=e[c];return typeof l!="object"||l===null||Array.isArray(l)?L("payload",`bad-object:${c}`):l},a=()=>{let c=e.aud;if(!Array.isArray(c))return L("payload","bad-audience");if(c.length>as)return L("payload","audience-too-many","capacity");let l=[];for(let u of c){if(typeof u!="string"||u.length===0)return L("payload","bad-audience-label");if(U(u)>ls)return L("payload","audience-label-too-long","capacity");l.push(u)}return l},d=c=>{if(!Object.prototype.hasOwnProperty.call(e,"int"))return c?L("payload","missing-field"):void 0;let l=e.int;if(!Array.isArray(l))return L("payload","bad-interest");if(l.length>yr)return L("payload","interest-too-many","capacity");let u=[];for(let p of l){if(typeof p!="string"||p.length===0)return L("payload","bad-interest-key");if(U(p)>gr)return L("payload","interest-key-too-long","capacity");u.push(p)}return u};switch(n){case"int":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);if(O(l))return l.refusal;let u=d(!0);return O(u)?u.refusal:{ok:!0,message:{k:n,q:c,h:l,int:u}}}case"join":{let c=t("q",fe);if(O(c))return c.refusal;let l=s("def");if(O(l))return l.refusal;let u=i("ver",0,Number.MAX_SAFE_INTEGER);if(O(u))return u.refusal;let p=s("store");if(O(p))return p.refusal;let y=s("key");if(O(y))return y.refusal;let f=a();if(O(f))return f.refusal;let w=d(!1);return O(w)?w.refusal:{ok:!0,message:w===void 0?{k:n,q:c,def:l,ver:u,store:p,key:y,aud:f}:{k:n,q:c,def:l,ver:u,store:p,key:y,aud:f,int:w}}}case"resume":case"aud":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);if(O(l))return l.refusal;let u=a();if(O(u))return u.refusal;if(n==="resume"){let p=d(!1);return O(p)?p.refusal:{ok:!0,message:p===void 0?{k:n,q:c,h:l,aud:u}:{k:n,q:c,h:l,aud:u,int:p}}}return{ok:!0,message:{k:n,q:c,h:l,aud:u}}}case"resync":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);if(O(l))return l.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("have");return O(p)?p.refusal:{ok:!0,message:{k:n,q:c,h:l,g:u,have:p}}}case"alive":case"leave":case"ok":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);return O(l)?l.refusal:{ok:!0,message:{k:n,q:c,h:l}}}case"act":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);if(O(l))return l.refusal;let u=r("s");if(O(u))return u.refusal;let p=s("name");if(O(p))return p.refusal;let y=o("in");return O(y)?y.refusal:{ok:!0,message:{k:n,q:c,h:l,s:u,name:p,in:y}}}case"in":{let c=t("h",G);if(O(c))return c.refusal;let l=s("name");if(O(l))return l.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("in");return O(p)?p.refusal:{ok:!0,message:{k:n,h:c,name:l,s:u,in:p}}}case"res":{let c=t("q",fe);if(O(c))return c.refusal;let l=t("h",G);if(O(l))return l.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("out");return O(p)?p.refusal:{ok:!0,message:{k:n,q:c,h:l,s:u,out:p}}}case"man":{let c=t("h",G);if(O(c))return c.refusal;let l=t("inc",dn);if(O(l))return l.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let y=i("n",1,ae);if(O(y))return y.refusal;let f=r("bytes");if(O(f))return f.refusal;if(BigInt(f)>BigInt(Se))return B("payload","snapshot-too-large","capacity");if(Object.prototype.hasOwnProperty.call(e,"q")){let w=t("q",fe);return O(w)?w.refusal:{ok:!0,message:{k:n,q:w,h:c,inc:l,g:u,r:p,n:y,bytes:f}}}return{ok:!0,message:{k:n,h:c,inc:l,g:u,r:p,n:y,bytes:f}}}case"snap":{let c=t("h",G);if(O(c))return c.refusal;let l=r("g");if(O(l))return l.refusal;let u=r("r");if(O(u))return u.refusal;let p=i("n",1,ae);if(O(p))return p.refusal;let y=i("i",0,p-1);if(O(y))return y.refusal;let f=e.d;return typeof f!="string"||!fn(f)?B("payload","non-canonical-base64:d"):{ok:!0,message:{k:n,h:c,g:l,r:u,i:y,n:p,d:f}}}case"delta":{let c=t("h",G);if(O(c))return c.refusal;let l=r("g");if(O(l))return l.refusal;let u=r("base");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let y=Ss(e.ops);return O(y)?y.refusal:{ok:!0,message:{k:n,h:c,g:l,base:u,r:p,ops:y}}}case"no":{let c=e.code;if(typeof c!="string"||!gs.has(c))return B("payload","unknown-code");let l=Object.prototype.hasOwnProperty.call(e,"q"),u=Object.prototype.hasOwnProperty.call(e,"h"),p=Object.prototype.hasOwnProperty.call(e,"s");if(!l&&!u)return B("payload","no-names-nothing");if(!l){if(c!=="closed"&&c!=="owner-lost")return B("payload","unsolicited-no-must-be-closed-or-owner-lost");if(p)return B("payload","unsolicited-no-carries-no-sequence")}let y={k:"no",code:c};if(l){let f=t("q",fe);if(O(f))return f.refusal;y.q=f}if(u){let f=t("h",G);if(O(f))return f.refusal;y.h=f}if(p){let f=r("s");if(O(f))return f.refusal;y.s=f}if(Object.prototype.hasOwnProperty.call(e,"detail")){let f=e.detail;if(typeof f!="string")return B("payload","bad-string:detail");if(U(f)>cs)return B("payload","detail-too-long","capacity");y.detail=f}return{ok:!0,message:y}}}}function Ss(n){if(!Array.isArray(n))return L("payload","bad-ops");if(n.length>un)return L("payload","ops-too-many","capacity");let e=[];for(let t of n){if(typeof t!="object"||t===null||Array.isArray(t))return L("payload","bad-op");let r=t,i=r.o;if(i!=="r"&&i!=="x")return L("payload","bad-op-kind");let s=i==="r"?["o","p","val"]:["o","p"];for(let d of Object.keys(r))if(!s.includes(d))return L("payload","unknown-field");if(i==="r"&&!Object.prototype.hasOwnProperty.call(r,"val"))return L("payload","missing-field");let o=r.p;if(!Array.isArray(o))return L("payload","bad-path");if(o.length>pn)return L("payload","path-too-deep","capacity");let a=[];for(let d of o){if(typeof d!="string"||d.length===0)return L("payload","bad-segment");if(U(d)>Ye)return L("payload","segment-too-long","capacity");a.push(d)}e.push(i==="r"?{o:i,p:a,val:r.val}:{o:i,p:a})}return e}function ws(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e),r=t>=48&&t<=57,i=t>=97&&t<=102;if(!r&&!i)return!1}return n.length>0}function mr(n){if(n.length===0||n.length>us)return!1;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t<48||t>57)return!1}return n.length>1&&n.charCodeAt(0)===48?!1:BigInt(n)<=ds}function fn(n){if(n.length===0)return!0;if(n.length%4!==0||!ms.test(n))return!1;let e=n.endsWith("==")?2:n.endsWith("=")?1:0;if(e===0)return!0;let t=n.charCodeAt(n.length-e-1),r=vs(t);return r<0?!1:(r&(e===2?15:3))===0}function vs(n){return n>=65&&n<=90?n-65:n>=97&&n<=122?n-97+26:n>=48&&n<=57?n-48+52:n===43?62:n===47?63:-1}function le(n){if(!mr(n))throw new RangeError(`not a canonical decimal: ${JSON.stringify(n)}`);return BigInt(n)}function hn(n,e){return cn(n,e,new Set)}function cn(n,e,t){if(n===null)return null;switch(typeof n){case"boolean":case"string":return null;case"number":return Number.isFinite(n)?null:`non-finite-number:${e}`;case"object":{let r=n;if(t.has(r))return`circular:${e}`;if("toJSON"in r)return`to-json-transform:${e}`;if(r instanceof Map||r instanceof Set||r instanceof WeakMap||r instanceof WeakSet)return`map-or-set:${e}`;if(Object.getOwnPropertySymbols(r).length>0)return`symbol-key:${e}`;t.add(r);try{if(Array.isArray(n)){for(let i=0;i<n.length;i+=1){let s=cn(n[i],`${e}[${i}]`,t);if(s!==null)return s}return null}for(let[i,s]of Object.entries(n)){let o=cn(s,`${e}.${i}`,t);if(o!==null)return o}return null}finally{t.delete(r)}}default:return`not-json:${e}`}}function Os(n){switch(n.k){case"act":case"in":return[["in",n.in]];case"res":return[["out",n.out]];case"delta":return n.ops.flatMap((e,t)=>e.o==="r"?[[`ops[${t}].val`,e.val]]:[]);default:return[]}}function _(n){for(let[o,a]of Os(n)){let d=hn(a,o);if(d!==null)throw new RangeError(`refusing to encode an invalid ${n.k}: ${d}`)}let e={v:hr,k:n.k},t=n;for(let o of ys[n.k]){if(o==="v"||o==="k"||!Object.prototype.hasOwnProperty.call(t,o))continue;let a=t[o];a!==void 0&&(e[o]=a)}let r=JSON.stringify(e),i=ln.has(n.k)?"owner":"replica",s=Me(r,{maxBytes:Number.MAX_SAFE_INTEGER,as:i});if(!s.ok)throw new RangeError(`refusing to encode an invalid ${n.k}: ${s.reason}`);return r}var xs=192,br=1024,Sr=197;function ks(n){return Math.floor((n-xs)/4)*3}function vr(n){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new h("capacity",`the transport reported no usable event size (${String(n)})`);if(Sr>n)throw new h("capacity",`the frozen envelopes need ${Sr} B and the transport allows ${n} B`);let e=ks(n);if(e<br)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk, below the ${br} B floor`);if(e*ae<Se)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk: ${ae} of them cover ${e*ae} B, below the ${Se} B snapshot bound`);return e}function Or(n,e){if(e<1)throw new h("capacity",`a chunk budget of ${e} B cannot carry anything`);try{let s=hn(n,"state");if(s!==null)throw new h("invalid-data",`the projected state is not JSON: ${s}`)}catch(s){throw s instanceof h?s:new h("invalid-data",`the projected state is not JSON: ${String(s)}`,{cause:s})}let t;try{t=JSON.stringify(n)}catch(s){throw new h("invalid-data","the projected state is not JSON",{cause:s})}if(t===void 0)throw new h("invalid-data","the projected state is not JSON");let r=new TextEncoder().encode(t);if(r.length>Se)throw new h("capacity",`the projection is ${r.length} B and the bound is ${Se} B`);let i=[];for(let s=0;s<r.length;s+=e)i.push(Es(r.subarray(s,s+e)));if(i.length>ae)throw new h("capacity",`the projection needs ${i.length} chunks and the bound is ${ae}`);return{bytes:r.length,n:i.length,pieces:i}}var wr=32768;function Es(n){let e="";for(let t=0;t<n.length;t+=wr)e+=String.fromCharCode(...n.subarray(t,t+wr));return btoa(e)}function xr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var gn=1e4,As=8*1024*1024;function V(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,fatal:e}}var yn=class{constructor(e,t){this.manifest=e;this.openedAt=t;this.pieces=new Array(e.n),this.encoded=new Array(e.n)}manifest;openedAt;pieces;encoded;admitted=0;held=0;closed=!1;get bytesHeld(){return this.held}get bytesReserved(){return this.closed?0:Math.max(Number(this.manifest.bytes),this.held)}get have(){return this.admitted}get reclaimed(){return this.closed}reclaim(){this.closed=!0,this.pieces.fill(void 0),this.encoded.fill(void 0),this.admitted=0,this.held=0}expired(e){return e-this.openedAt>=gn}accept(e,t,r){if(this.closed)return V("chunk-wrong-assembly",!1);if(this.expired(r))return this.reclaim(),V("deadline",!0,"timeout");let i=this.manifest;if(e.h!==i.h||e.g!==i.g||e.r!==i.r||e.n!==i.n)return V("chunk-wrong-assembly",!1);if(!Number.isInteger(e.i)||e.i<0||e.i>=i.n)return V("chunk-index",!1);if(!fn(e.d))return V("chunk-non-canonical",!1);let s=this.encoded[e.i];if(s!==void 0)return s===e.d?{ok:!0,done:!1,have:this.admitted}:(this.reclaim(),V("chunk-conflict",!0));let o=xr(e.d),a=Number(i.bytes);if(this.held+o.length>a)return this.reclaim(),V("byte-total-mismatch",!0);if(this.encoded[e.i]=e.d,this.pieces[e.i]=o,this.admitted+=1,this.held+=o.length,this.admitted<i.n)return{ok:!0,done:!1,have:this.admitted};if(this.held!==a)return this.reclaim(),V("byte-total-mismatch",!0);let d=new Uint8Array(this.held),c=0;for(let p of this.pieces){if(p===void 0)return this.reclaim(),V("byte-total-mismatch",!0);d.set(p,c),c+=p.length}let l=new TextDecoder("utf-8",{fatal:!0}),u;try{let p=De(l.decode(d));if(!p.ok)return this.reclaim(),V("assembled-not-json",!0);u=p.value}catch{return this.reclaim(),V("assembled-not-json",!0)}try{t(u)}catch{return this.reclaim(),V("assembled-invalid",!0)}return this.reclaim(),{ok:!0,done:!0,document:u}}},_t=class n{constructor(e=As){this.maxTotalBytes=e}maxTotalBytes;live=new Map;static key(e,t){return`${e}/${t}`}get bytesHeld(){let e=0;for(let t of this.live.values())e+=t.bytesHeld;return e}get bytesReserved(){let e=0;for(let t of this.live.values())e+=t.bytesReserved;return e}get size(){return this.live.size}get(e,t){return this.live.get(n.key(e,t))}open(e,t){if(!Number.isInteger(e.n)||e.n<1||e.n>ae)return V("manifest-chunk-count",!0);let r=Number(e.bytes);if(!Number.isSafeInteger(r)||r<0||r>Se)return V("manifest-bytes",!0,"capacity");let i=n.key(e.h,e.g),s=this.live.get(i),o=s?.bytesReserved??0;if(this.bytesReserved-o+r>this.maxTotalBytes)return V("assembly-too-large",!0,"capacity");s?.reclaim(),this.live.delete(i);let a=new yn(e,t);return this.live.set(i,a),a}reclaim(e,t){let r=n.key(e,t);this.live.get(r)?.reclaim(),this.live.delete(r)}reclaimHandle(e){for(let[t,r]of[...this.live])t.startsWith(`${e}/`)&&(r.reclaim(),this.live.delete(t))}sweep(e){let t=0;for(let[r,i]of[...this.live])i.expired(e)&&(i.reclaim(),this.live.delete(r),t+=1);return t}clear(){for(let e of this.live.values())e.reclaim();this.live.clear()}};function ce(n,e){if(Object.is(n,e))return e;if(Array.isArray(e)){let t=e;if(!Array.isArray(n))return Er(t,void 0);let r=Er(t,n);return n.length===t.length&&Rs(n,r)?n:r}if(kr(e)){if(!kr(n))return Ar(e,void 0);let t=Ar(e,n),r=Object.keys(e);return r.length===Object.keys(n).length&&r.every(i=>Rr(n,i)&&Object.is(n[i],t[i]))?n:t}return e}function Pt(n,e){let t=Object.keys(e);if(t.length===0)return n;let r=!1,i={...n};for(let s of t){let o=_r(n,s),a=ce(o,e[s]);Object.is(o,a)||(Object.defineProperty(i,s,{value:a,enumerable:!0,writable:!0,configurable:!0}),r=!0)}return r?Object.freeze(i):n}function kr(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Rs(n,e){for(let t=0;t<e.length;t+=1)if(!Object.is(n[t],e[t]))return!1;return!0}function Er(n,e){let t=new Array(n.length);for(let r=0;r<n.length;r+=1)t[r]=ce(e?.[r],n[r]);return Object.freeze(t)}function Rr(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function _r(n,e){if(n!==void 0)return Rr(n,e)?n[e]:void 0}function Ar(n,e){let t={};for(let r of Object.keys(n))Object.defineProperty(t,r,{value:ce(_r(e,r),n[r]),enumerable:!0,writable:!1,configurable:!1});return Object.freeze(t)}var _s=["__proto__","constructor","prototype"],Ps=new Set(_s);function de(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,resync:e}}function Pr(n,e,t){if(e.length>un)return de("ops-too-many",!1,"capacity");for(let a of e){if(a.p.length>pn)return de("path-too-deep",!1,"capacity");for(let d of a.p){if(U(d)>Ye)return de("segment-too-long",!1,"capacity");if(Ps.has(d))return de("segment-forbidden",!1)}if(a.o==="x"&&a.p.length===0)return de("root-remove",!1)}let r=n,i=new WeakSet;for(let a of e){if(a.p.length===0){a.o==="r"&&(r=a.val);continue}if(!Ir(r))return de("parent-not-object",!0);let d=Hr(r,i);r=d;let c=js(d,a.p.slice(0,-1),i);if(c===jr)return de("missing-parent",!0);if(c===Cr)return de("parent-not-object",!0);let l=c,u=a.p[a.p.length-1];if(a.o==="x"){if(!Object.prototype.hasOwnProperty.call(l,u))return de("missing-key",!0);delete l[u];continue}l[u]=a.val}let s;try{s=t(r)}catch{return de("invalid-state",!0)}let o=ce(n,s);return{ok:!0,next:o,changed:!Object.is(o,n)}}var jr=Symbol("missing-parent"),Cr=Symbol("parent-not-object");function js(n,e,t){let r=n;for(let i of e){let s=r;if(!Object.prototype.hasOwnProperty.call(s,i))return jr;let o=s[i];if(!Ir(o))return Cr;let a=Hr(o,t);s[i]=a,r=a}return r}function Ir(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Hr(n,e){if(e.has(n))return n;let t=Object.assign(Object.create(null),n);return e.add(t),t}var he=class{#e;#t=new Set;#r=new Set;#n;#i;#b=0;#l=null;#o=0;#u=!1;constructor(e){this.#e=e.definition,this.#n=ce(void 0,this.#d(e.initialState)),this.#i=Object.freeze({phase:e.phase??"ready",stale:!1,error:null})}getState(){return this.#n}get revision(){return this.#b}get inTransaction(){return this.#l!==null&&this.#l.active}subscribe(e,t,r){let i=t===void 0?this.#y(e):this.#O(e,t,r);this.#t.add(i);let s=!0;return()=>{s&&(s=!1,this.#t.delete(i))}}getStatus(){return this.#i}subscribeStatus(e){this.#r.add(e);let t=!0;return()=>{t&&(t=!1,this.#r.delete(e))}}setStatus(e){let t=this.#i,r={phase:e.phase??t.phase,stale:e.stale??t.stale,error:e.error===void 0?t.error:e.error};if(!(r.phase===t.phase&&r.stale===t.stale&&Object.is(r.error,t.error))){this.#i=Object.freeze(r);for(let i of[...this.#r])this.#r.has(i)&&jt(()=>i(this.#i,t))}}transact(e,t){if(this.#a(),this.#l!==null)throw new h("action-rejected","a store transaction is already open on this store; handlers are synchronous and must not nest");let r={staged:this.#n,active:!0};this.#l=r;try{let i=e(this.#c(r,t));if(Cs(i))throw new h("action-rejected","a store handler returned a thenable; handlers are synchronous so that a throw can discard the whole transaction");return this.#m(r.staged),i}finally{r.active=!1,this.#l=null}}applyOwnerUpdate(e){this.#a();let t=this.#l;if(t!==null&&t.active){t.staged=this.#f(t.staged,e);return}let r=this.#f(this.#n,e);this.#m(r)}applySnapshot(e){this.#a();let t=this.#l;if(t!==null&&t.active){t.staged=this.#d(e);return}this.#m(this.#d(e))}applyEntities(e,t){this.#a();let r=this.#e.entities?.[e];if(r===void 0||!Object.prototype.hasOwnProperty.call(this.#e.entities,e))throw new h("invalid-data",`store '${this.#e.id}' declares no per-entity parser for '${e}'; declare it in \`entities\` or write through setState`);let i=this.#l,s=i!==null&&i.active?i.staged:this.#n,o=s[e];if(o!==void 0&&!on(o))throw new h("invalid-data",`store '${this.#e.id}': '${e}' is not an entity map in the current state`);let a=[];for(let p of Object.keys(t)){if(p.length===0)throw new h("invalid-data",`store '${this.#e.id}': an entity id in '${e}' is empty`);let y=t[p];if(y===void 0){a.push([p,void 0]);continue}try{a.push([p,this.runReadOnly(()=>r(y))])}catch(f){throw f instanceof h?f:new h("invalid-data",`entity '${e}.${p}' failed the '${this.#e.id}' entity validator: ${String(f)}`,{cause:f})}}if(i!==null&&i.active){let p={...o??{}};for(let[y,f]of a)f===void 0?delete p[y]:mn(p,y,f);i.staged=Pt(s,{[e]:p});return}let d=!1,c=[];for(let[p,y]of a){let f=o!==void 0&&Object.prototype.hasOwnProperty.call(o,p),w=f?o[p]:void 0;if(y===void 0){f&&(d=!0),c.push([p,void 0]);continue}let R=ce(w,y);Object.is(w,R)||(d=!0),c.push([p,R])}if(!d)return;let l={...o??{}};for(let[p,y]of c)y===void 0?delete l[p]:mn(l,p,y);let u={...s};mn(u,e,Object.freeze(l)),this.#p(Object.freeze(u))}applyDelta(e){this.#a();let t=Pr(this.#n,e,r=>this.#d(r));return t.ok&&t.changed&&this.#h(t.next),t}runReadOnly(e){this.#o+=1;try{return e()}finally{this.#o-=1}}close(){this.#u||(this.#u=!0,this.setStatus({phase:"closed",stale:!0}),this.#t.clear(),this.#r.clear())}#c(e,t){return{peer:t,getState:()=>(this.#w(e),e.staged),setState:r=>{if(this.#w(e),this.#o>0)throw new h("action-rejected","a read-only store callback may not write state; validators, authorize, project and update functions run with setters fenced");e.staged=this.#f(e.staged,r)}}}#f(e,t){let r=typeof t=="function"?this.runReadOnly(()=>t(e)):t;return Pt(e,r)}#m(e){this.#h(this.#d(e))}#h(e){let t=ce(this.#n,e);Object.is(t,this.#n)||this.#p(t)}#p(e){let t=this.#n;this.#n=e,this.#b+=1;for(let r of[...this.#t])this.#t.has(r)&&r.notify(e,t)}#d(e){try{return this.runReadOnly(()=>this.#e.state(e))}catch(t){throw t instanceof h?t:new h("invalid-data",`state failed the '${this.#e.id}' validator: ${String(t)}`,{cause:t})}}#y(e){return{notify:(t,r)=>{jt(()=>e(t,r))}}}#O(e,t,r){let i=r?.equality??Object.is,s=this.runReadOnly(()=>e(this.#n));return r?.fireImmediately===!0&&jt(()=>t(s,s)),{notify:o=>{let a=this.runReadOnly(()=>e(o)),d=s;i(a,d)||(s=a,jt(()=>t(a,d)))}}}#w(e){if(!e.active)throw new h("action-rejected","this store transaction has already ended; its context cannot read or write from a later turn")}#a(){if(this.#u)throw new h("closed","this store handle is closed")}};function Cs(n){return n===null||typeof n!="object"&&typeof n!="function"?!1:typeof n.then=="function"}function jt(n){try{n()}catch(e){console.error("[@net-mesh/browser] store listener threw",e)}}function mn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}var Is=32,Hs=64*1024,Ls=6e4,Ts=2048,Ds=(1n<<64n)-1n,Ms="";function Lr(n,e){return`${n}${Ms}${bn(e)}`}function bn(n){if(n===null||typeof n=="boolean")return String(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new h("invalid-data","a canonical request cannot contain a non-finite number");return String(n)}if(typeof n=="string")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(i=>bn(i)).join(",")}]`;let e=n;return`{${Object.keys(e).sort().map(i=>`${JSON.stringify(i)}:${bn(e[i])}`).join(",")}}`}function qs(n){return new TextEncoder().encode(n).byteLength}function vn(n){return qs(n)>Ts}function Tr(n){if(vn(n))throw new h("invalid-data","this canonical form needs the digest path");return{form:"inline",value:n}}async function Dr(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t=new Uint8Array(e),r="";for(let i of t)r+=i.toString(16).padStart(2,"0");return{form:"digest",value:r}}function Ns(n,e){return n.form===e.form&&n.value===e.value}var Sn=class{constructor(e=Is,t=Hs,r=Ls){this.maxEntries=e;this.maxBytes=t;this.maxAgeMs=r}maxEntries;maxBytes;maxAgeMs;#e=0n;#t=new Map;#r=0;get floor(){return this.#e.toString()}get size(){return this.#t.size}get bytesHeld(){return this.#r}disposition(e,t,r){if(this.expire(r),e>=Ds)return{kind:"exhausted"};let i=this.#t.get(e.toString());return i!==void 0?Ns(i.binding,t)?{kind:"replay",outcome:i.outcome}:{kind:"conflict"}:e<=this.#e?{kind:"expired"}:{kind:"execute"}}retain(e,t,r,i){let s=Ws(t,r);this.#t.set(e.toString(),{s:e,binding:t,outcome:r,bytes:s,at:i}),this.#r+=s,this.evict(i)}expire(e){for(let t of this.ordered()){if(e-t.at<this.maxAgeMs)break;this.drop(t)}}evict(e){for(this.expire(e);this.#t.size>this.maxEntries||this.#r>this.maxBytes;){let t=this.ordered()[0];if(t===void 0)return;this.drop(t)}}drop(e){this.#t.delete(e.s.toString()),this.#r-=e.bytes,e.s>this.#e&&(this.#e=e.s)}ordered(){return[...this.#t.values()].sort((e,t)=>e.s<t.s?-1:e.s>t.s?1:0)}};function Ws(n,e){let t=e.kind==="result"?JSON.stringify(e.out):e.code;return U(n.value)+U(t)}var wn=class{#e=new Map;#t=0;get dropped(){return this.#t}admit(e,t){let r=this.#e.get(e);return r!==void 0&&t<=r?(this.#t+=1,!1):(this.#e.set(e,t),!0)}latest(e){let t=this.#e.get(e);return t===void 0?null:t.toString()}},Ct=class{#e=new Map;#t=new Map;ledger(e){let t=this.#e.get(e);return t===void 0&&(t=new Sn,this.#e.set(e,t)),t}inputs(e){let t=this.#t.get(e);return t===void 0&&(t=new wn,this.#t.set(e,t)),t}forget(e){this.#e.delete(e),this.#t.delete(e)}get size(){return this.#e.size}};var Us=32,$s=256,Mr=6e4,Wr=256;function ye(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var Bs="0".repeat(16),Js="0".repeat(32),It=class{constructor(e){this.deps=e;if(this.chunkBytes=vr(e.maxEventBytes),this.incarnation=e.newIncarnation(),this.incarnation.length!==dn)throw new h("invalid-data","newIncarnation must return 16 lowercase hex");let t=(typeof e.project=="function"?1:0)+(typeof e.projectFor=="function"?1:0),r=e.definition.visibility;if(t>1||t===0&&r===void 0)throw new h("invalid-data","a host needs one of `project` and `projectFor`, or a definition that declares `visibility`");this.visibility=r===void 0?null:Le(r),this.perPlayer=typeof e.projectFor=="function"||this.visibility?.perPlayer===!0,this.core=new he({definition:e.definition,initialState:e.definition.empty()})}deps;handles=new Map;counters={};chunkBytes;incarnation;core;pending=0;ledgers=new Ct;deferred=new Map;revisionBeforeCommit=0;perPlayer;visibility;warned=new Set;warnOnce(e){if(!(this.deps.warn===void 0||this.warned.has(e))){this.warned.add(e);try{this.deps.warn(e)}catch{}}}viewKey(e,t){return this.perPlayer?JSON.stringify([e,t]):JSON.stringify(t)}get sparseViews(){return this.sparseViewCount}sparseViewCount=0;snapshotCounters(){return{...this.counters}}get handleCount(){return this.handles.size}handle(e){return this.handles.get(e)}commit(e){let t=this.core.inTransaction,r=this.core.getState();if(t||(this.revisionBeforeCommit=this.core.revision),this.core.applySnapshot(e),t)return this.accept([]);let i=this.core.getState();return Object.is(r,i)?this.accept([]):this.accept(this.propagate(r,i))}commitEntities(e,t){let r=this.core.inTransaction,i=this.core.getState();if(r||(this.revisionBeforeCommit=this.core.revision),this.core.applyEntities(e,t),r)return this.accept([]);let s=this.core.getState();return Object.is(i,s)?this.accept([]):this.accept(this.propagate(i,s))}propagate(e,t){let r=[],i=String(this.core.revision),s=new Map,o=new Map,a;for(let d of[...this.handles.values()]){if(this.deferred.has(d.h))continue;if(!this.permitsRead(d.peer,d.audience)){this.forget(d.h,"refused"),r.push(this.no(d.peer,d.h,"closed",null));continue}let c=this.viewKey(d.peer,d.audience),l;if(this.interestFns.length>0&&d.interest!==null){let y=s.get(c);if(y===void 0){if(a===void 0&&(a=this.entityDelta(e,t)),y=a===null?void 0:this.sparseInterestDiff(d.peer,d.audience,a),y===void 0){let f=this.project(d.peer,d.audience,e),w=this.project(d.peer,d.audience,t);y=f===null||w===null?null:this.interestDiff(f,w)}else this.sparseViewCount+=1;s.set(c,y)}l=y===null?null:this.interestOps(y,d.interest)}else if(l=o.get(c),l===void 0){let y=this.project(d.peer,d.audience,e),f=this.project(d.peer,d.audience,t);l=y===null||f===null?null:qr(y,f),o.set(c,l)}if(l===null){this.forget(d.h),r.push(this.no(d.peer,d.h,"closed",null));continue}if(l.length===0)continue;let u=Nr({k:"delta",h:d.h,g:String(d.generation),base:String(d.revision),r:i,ops:l},this.deps.maxEventBytes);if(u!==null){r.push({peer:d.peer,h:d.h,frame:u}),this.handles.set(d.h,{...d,revision:this.core.revision});continue}let p=this.install(d,null);if(p===null){this.forget(d.h),r.push(this.no(d.peer,d.h,"closed",null));continue}r.push(...p)}return r}getState(){return this.core.getState()}subscribe(e){return this.core.subscribe((t,r)=>{e(t,r)})}get currentRevision(){return this.core.revision}localRead(e,t){return this.permitsRead(e,t)}localView(e,t,r=null){let i=this.project(e,t);return i===null?null:this.filterInterest(i,r)}localAct(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,e))return{outcome:{kind:"refusal",code:"invalid-data"},dispatched:this.refuse("local-act-unknown-name")};if(!this.permitsAction(r,e,t))return{outcome:{kind:"refusal",code:"forbidden"},dispatched:this.refuse("local-act-forbidden")};let i=this.deps.definition.actions[e],s=this.core.getState();this.revisionBeforeCommit=this.core.revision;let o;try{let c=this.deps.actions[e];o={kind:"result",out:this.core.transact(u=>{let p=i.output(c(i.input(t),u)),y=_({k:"res",q:Bs,h:Js,s:"1",out:p});if(U(y)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return p},r)}}catch(c){o={kind:"refusal",code:c instanceof h&&c.code==="capacity"?"capacity":"action-rejected"}}let a=this.core.getState(),d=Object.is(s,a)?[]:this.propagate(s,a);return{outcome:o,dispatched:o.kind==="refusal"?this.refuse(`local-act-${o.code}`,d):this.accept(d)}}localInput(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,e))return this.refuse("local-in-unknown-name");if(!this.permitsInput(r,e,t))return this.refuse("local-in-forbidden");let i=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(o=>{let a=this.deps.definition.inputs[e],d=this.deps.inputs[e];d(a(t),o)},r)}catch{return this.refuse("local-in-rejected")}let s=this.core.getState();return this.accept(Object.is(i,s)?[]:this.propagate(i,s))}receive(e,t,r=this.deps.now()){let i=Me(e,{maxBytes:this.deps.maxEventBytes,as:"owner"});if(!i.ok)return this.refuse(i.reason,[]);let s=i.message;if(s.k==="join")return this.join(s,t,r);let o=this.bind(s.h,t,r);if(typeof o=="string")return this.refuse(o,[this.no(t,s.h,"closed",Ks(s))]);switch(s.k){case"alive":return this.handles.set(o.h,{...o,lastSeen:r}),this.accept([{peer:t,h:o.h,frame:_({k:"ok",q:s.q,h:o.h})}]);case"leave":return this.forget(o.h,"left"),this.accept([{peer:t,h:o.h,frame:_({k:"ok",q:s.q,h:o.h})}]);case"int":return this.interestChange(s,o,t,r);case"act":return this.action(s,o,t,r);case"in":return this.input(s,o,t,r);case"resync":{if(!this.permitsRead(t,o.audience))return this.refuse("resync-forbidden",[this.no(t,o.h,"forbidden",s.q)]);let a={...o,lastSeen:r};this.handles.set(o.h,a);let d=this.install(a,s.q);return d===null?(this.forget(o.h),this.refuse("resync-projection-capacity",[this.no(t,o.h,"capacity",s.q)])):this.accept(d)}case"aud":case"resume":{if(!this.permitsRead(t,s.aud))return this.refuse(`${s.k}-forbidden`,[this.no(t,o.h,"forbidden",s.q)]);let a={...o,audience:[...s.aud],interest:s.k==="resume"&&s.int!==void 0?[...s.int]:o.interest,lastSeen:r};if(this.handles.set(a.h,a),!this.deps.canProject())return this.deferred.set(a.h,{q:s.q,peer:t}),this.accept([]);let d=this.install(a,s.q);return d===null?(this.forget(a.h),this.refuse(`${s.k}-projection-capacity`,[this.no(t,a.h,"capacity",s.q)])):this.accept(d)}default:return this.refuse("unreachable-kind")}}action(e,t,r,i){let s=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,s))return this.refuse("act-unknown-name",[this.no(r,t.h,"invalid-data",e.q)]);let o;try{o=Lr(s,e.in)}catch{return this.refuse("act-uncanonical",[this.no(r,t.h,"invalid-data",e.q)])}if(!vn(o))return this.decide(e,t,r,i,Tr(o));if(this.pending>=Us)return this.refuse("act-pending-bound",[this.no(r,t.h,"capacity",e.q)]);this.pending+=1;let a=Dr(o).then(d=>{let c=this.deps.now(),l=this.bind(e.h,r,c);return typeof l=="string"?this.refuse(l,[this.no(r,e.h,"closed",e.q)]):this.decide(e,l,r,c,d)}).catch(()=>this.refuse("act-digest-failed",[this.no(r,e.h,"indeterminate",e.q)])).finally(()=>{this.pending-=1});return{out:[],refused:null,deferred:a}}decide(e,t,r,i,s){let o=this.ledgers.ledger(t.h),a=le(e.s),d=o.disposition(a,s,i);switch(d.kind){case"exhausted":return this.refuse("act-sequence-exhausted",[this.no(r,t.h,"capacity",e.q)]);case"conflict":return this.refuse("act-binding-mismatch",[this.no(r,t.h,"invalid-data",e.q)]);case"expired":return this.refuse("act-result-expired",[this.no(r,t.h,"result-expired",e.q)]);case"replay":return this.permitsAction(r,e.name,e.in)?(this.renew(t,i),this.accept([this.reply(t,r,e.q,a,d.outcome)])):this.refuse("act-forbidden-replay",[this.no(r,t.h,"forbidden",e.q)]);case"execute":break}if(!this.permitsAction(r,e.name,e.in))return o.retain(a,s,{kind:"refusal",code:"forbidden"},i),this.renew(t,i),this.refuse("act-forbidden",[this.no(r,t.h,"forbidden",e.q)]);let c=this.deps.definition.actions[e.name],l=this.core.getState();this.revisionBeforeCommit=this.core.revision;let u;try{let f=this.deps.actions[e.name];u={kind:"result",out:this.core.transact(R=>{let P=c.input(e.in),M=c.output(f(P,R)),H=_({k:"res",q:e.q,h:t.h,s:e.s,out:M});if(U(H)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return M},r)}}catch(f){u={kind:"refusal",code:f instanceof h&&f.code==="capacity"?"capacity":"action-rejected"}}o.retain(a,s,u,i),this.renew(t,i);let p=this.core.getState(),y=Object.is(l,p)?[]:this.propagate(l,p);return this.accept([this.reply(t,r,e.q,a,u),...y])}input(e,t,r,i){let s=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,s))return this.refuse("in-unknown-name");if(!this.ledgers.inputs(t.h).admit(s,le(e.s)))return this.refuse("in-stale-sequence");if(!this.permitsInput(r,s,e.in))return this.refuse("in-forbidden");let o=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(d=>{let c=this.deps.definition.inputs[s],l=this.deps.inputs[s];l(c(e.in),d)},r)}catch{return this.refuse("in-rejected")}this.renew(t,i);let a=this.core.getState();return this.accept(Object.is(o,a)?[]:this.propagate(o,a))}reply(e,t,r,i,s){let o=s.kind==="result"?_({k:"res",q:r,h:e.h,s:i.toString(),out:s.out}):_({k:"no",q:r,h:e.h,code:s.code,s:i.toString()});return{peer:t,h:e.h,frame:o}}permitsAction(e,t,r){let i={type:"action",peer:e,name:t,input:r};try{return this.deps.authorize(i)===!0}catch{return!1}}permitsInput(e,t,r){let i={type:"input",peer:e,name:t,input:r};try{return this.deps.authorize(i)===!0}catch{return!1}}renew(e,t){let r=this.handles.get(e.h);r!==void 0&&this.handles.set(e.h,{...r,lastSeen:t})}forget(e,t="dropped"){let r=this.handles.get(e);this.handles.delete(e),this.ledgers.forget(e),this.deferred.delete(e),r!==void 0&&(this.presenceChanged(r.peer,t),this.membershipChanged())}present=new Set;localPlayers=new Set;pendingEvents=[];areas=new Map;areasAt=-1;ending=!1;get wantsEvents(){return this.deps.onEvent!==void 0||this.deps.areaOf!==void 0}isPresent(e){if(this.localPlayers.has(e))return!0;for(let t of this.handles.values())if(t.peer===e)return!0;return!1}presenceChanged(e,t,r=[]){if(!this.wantsEvents||this.ending)return;let i=this.isPresent(e),s=this.present.has(e);i!==s&&(i?(this.present.add(e),this.pendingEvents.push(Object.freeze({type:"join",peer:e,audience:Object.freeze([...r])}))):(this.present.delete(e),this.areas.delete(e),this.pendingEvents.push(Object.freeze({type:"leave",peer:e,reason:t??"dropped"}))))}localPresence(e,t,r=[],i="left"){t?this.localPlayers.add(e):this.localPlayers.delete(e),this.presenceChanged(e,t?null:i,r)}detectAreas(){let e=this.deps.areaOf;if(e===void 0||this.ending||this.areasAt===this.core.revision&&[...this.present].every(r=>this.areas.has(r)))return;this.areasAt=this.core.revision;let t=this.core.getState();for(let r of this.present){let i;try{let a=this.core.runReadOnly(()=>e(t,r));i=typeof a=="string"?a:null}catch{i=null}let s=this.areas.has(r),o=s?this.areas.get(r)??null:null;this.areas.set(r,i),(s?o!==i:i!==null)&&this.pendingEvents.push(Object.freeze({type:"area",peer:r,from:o,to:i}))}}drainEvents(){let e=[];if(!this.wantsEvents)return this.accept(e);for(let t=0;;t+=1){this.pendingEvents.length===0&&this.detectAreas();let r=this.pendingEvents.shift();if(r===void 0)break;if(t>=Wr){this.pendingEvents.length=0,this.counters["event-rounds-bound"]=(this.counters["event-rounds-bound"]??0)+1;break}let i=this.deps.onEvent;if(i===void 0)continue;let s=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(a=>i(r,a),r.peer)}catch{this.counters["event-rejected"]=(this.counters["event-rejected"]??0)+1;continue}let o=this.core.getState();Object.is(s,o)||e.push(...this.propagate(s,o))}return this.accept(e)}membership=new Set;membershipChanged(){for(let e of[...this.membership])try{e()}catch{}}onMembership(e){return this.membership.add(e),()=>{this.membership.delete(e)}}peers(){return[...new Set([...this.handles.values()].map(e=>e.peer))]}reauthorize(){let e=[];for(let t of[...this.handles.values()])this.permitsRead(t.peer,t.audience)||(this.forget(t.h,"refused"),e.push(this.no(t.peer,t.h,"closed",null)));return this.accept(e)}resumeDeferred(e=this.deps.now()){if(!this.deps.canProject())return this.accept([]);let t=[];for(let[r,i]of[...this.deferred]){this.deferred.delete(r);let s=this.bind(r,i.peer,e);if(typeof s=="string"){this.counters[`deferred-${s}`]=(this.counters[`deferred-${s}`]??0)+1;continue}let o=this.install(s,i.q);if(o===null){this.forget(r),t.push(this.no(i.peer,r,"capacity",i.q));continue}t.push(...o)}return this.accept(t)}get deferredCount(){return this.deferred.size}get ledgerCount(){return this.ledgers.size}accept(e,t=null){return{out:e,refused:null,deferred:t}}sweep(e){let t=[];for(let[r,i]of[...this.handles])e-i.lastSeen>=Mr&&(this.forget(r,"expired"),t.push({h:r,peer:i.peer}));return t}farewell(){this.ending=!0,this.pendingEvents.length=0;let e=[];for(let[t,r]of[...this.handles])this.forget(t),e.push(this.no(r.peer,t,"owner-lost",null));return e}get incarnationHex(){return this.incarnation}join(e,t,r){if(e.store!==this.deps.store)return this.refuse("join-other-store",[]);if(e.def!==this.deps.definition.id)return this.refuse("join-wrong-definition",[this.no(t,null,"version-mismatch",e.q)]);if(e.ver!==this.deps.definition.version)return this.refuse("join-wrong-version",[this.no(t,null,"version-mismatch",e.q)]);if(this.handles.size>=$s)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);if(!this.permitsRead(t,e.aud))return this.refuse("join-forbidden",[this.no(t,null,"forbidden",e.q)]);let i=this.newHandle();if(i===null||i.length!==G||this.handles.has(i))return this.refuse("join-handle-unusable",[this.no(t,null,"owner-lost",e.q)]);let s={h:i,inc:this.incarnation,peer:t,audience:[...e.aud],interest:e.int===void 0?null:[...e.int],generation:0,revision:this.core.revision,lastSeen:r};this.handles.set(i,s);let o=this.install(s,e.q);return o===null?(this.forget(i),this.refuse("join-projection-capacity",[this.no(t,null,"capacity",e.q)])):(this.presenceChanged(t,null,e.aud),this.membershipChanged(),this.accept(o))}install(e,t){let r=this.project(e.peer,e.audience),i=r===null?null:this.filterInterest(r,e.interest);if(i===null)return null;let s;try{s=Or(i,this.chunkBytes)}catch{return null}let o=e.generation+1;this.handles.set(e.h,{...e,generation:o,revision:this.core.revision});let a=String(o),d=String(this.core.revision),c=[{peer:e.peer,h:e.h,frame:_(t===null?{k:"man",h:e.h,inc:e.inc,g:a,r:d,n:s.n,bytes:String(s.bytes)}:{k:"man",q:t,h:e.h,inc:e.inc,g:a,r:d,n:s.n,bytes:String(s.bytes)})}];for(let l=0;l<s.n;l+=1)c.push({peer:e.peer,h:e.h,frame:_({k:"snap",h:e.h,g:a,r:d,i:l,n:s.n,d:s.pieces[l]})});return c}permitsRead(e,t){let r={type:"read",peer:e,audience:[...t]};try{return this.deps.authorize(r)===!0}catch{return!1}}newHandle(){try{return this.deps.newHandle()}catch{return null}}get interestFns(){return this.#e??=Object.entries(this.deps.definition.interest??{}).map(([e,t])=>[e,t]),this.#e}#e;interestKey(e,t,r){try{let i=this.core.runReadOnly(()=>e(t,r));return typeof i=="string"?i:null}catch{return null}}filterInterest(e,t){if(t===null||this.interestFns.length===0)return e;let r=new Set(t),i={...e};for(let[s,o]of this.interestFns){let a=i[s];if(!ye(a))continue;let d={};for(let[c,l]of Object.entries(a)){let u=this.interestKey(o,l,c);(u===null||r.has(u))&&(d[c]=l)}i[s]=d}return i}entityDelta(e,t){if(this.deps.project!==void 0||this.deps.projectFor!==void 0)return null;let r=this.deps.definition.entities;if(r===void 0)return null;let i=new Set(this.interestFns.map(([d])=>d)),s=e,o=t,a=[];for(let d of new Set([...Object.keys(s),...Object.keys(o)])){let c=Object.prototype.hasOwnProperty.call(s,d)?s[d]:void 0,l=Object.prototype.hasOwnProperty.call(o,d)?o[d]:void 0;if(Object.is(c,l))continue;if(!i.has(d)||!Object.prototype.hasOwnProperty.call(r,d)||!ye(c)||!ye(l))return null;let u=[];for(let p of new Set([...Object.keys(c),...Object.keys(l)])){let y=Object.prototype.hasOwnProperty.call(c,p)?c[p]:void 0,f=Object.prototype.hasOwnProperty.call(l,p)?l[p]:void 0;Object.is(y,f)||u.push(p)}a.push({collection:d,ids:u,before:c,after:l})}return{collections:a}}sparseInterestDiff(e,t,r){let i=Object.freeze({peer:e,audience:Object.freeze([...t])}),s=(y,f,w)=>{Object.defineProperty(y,f,{value:w,enumerable:!0,writable:!0,configurable:!0})},o={},a={};for(let{collection:y,ids:f,before:w,after:R}of r.collections){let P={},M={};for(let H of f)Object.prototype.hasOwnProperty.call(w,H)&&s(P,H,w[H]),Object.prototype.hasOwnProperty.call(R,H)&&s(M,H,R[H]);s(o,y,P),s(a,y,M)}let d=this.visibility===null?o:Te(this.visibility,o,i),c=this.visibility===null?a:Te(this.visibility,a,i),l=new Map(this.interestFns),u=this.deps.definition.entities,p=[];for(let{collection:y,ids:f}of r.collections){let w=d[y],R=c[y];if(!ye(w)||!ye(R))return;let P=u[y],M=l.get(y),H=(k,E)=>{if(k===void 0||!E)return{ok:!0,value:k};try{return{ok:!0,value:this.core.runReadOnly(()=>P(k))}}catch{return{ok:!1,value:void 0}}};for(let k of f){let E=H(Object.prototype.hasOwnProperty.call(w,k)?w[k]:void 0,d!==o),j=H(Object.prototype.hasOwnProperty.call(R,k)?R[k]:void 0,c!==a);if(!E.ok||!j.ok)return;Object.is(E.value,j.value)||E.value!==void 0&&j.value!==void 0&&JSON.stringify(E.value)===JSON.stringify(j.value)||p.push({collection:y,id:k,before:E.value,after:j.value,beforeKey:E.value===void 0?null:this.interestKey(M,E.value,k),afterKey:j.value===void 0?null:this.interestKey(M,j.value,k)})}}return{rest:[],entities:p,whole:[]}}interestDiff(e,t){let r=new Set(this.interestFns.map(([d])=>d)),i=d=>{let c={};for(let[l,u]of Object.entries(d))r.has(l)||(c[l]=u);return c},s=qr(i(e),i(t)),o=[],a=[];for(let[d,c]of this.interestFns){let l=e[d],u=t[d];if(!ye(l)||!ye(u)){JSON.stringify(l)!==JSON.stringify(u)&&a.push({collection:d,after:u});continue}for(let p of new Set([...Object.keys(l),...Object.keys(u)])){let y=Object.prototype.hasOwnProperty.call(l,p)?l[p]:void 0,f=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0;Object.is(y,f)||y!==void 0&&f!==void 0&&JSON.stringify(y)===JSON.stringify(f)||o.push({collection:d,id:p,before:y,after:f,beforeKey:y===void 0?null:this.interestKey(c,y,p),afterKey:f===void 0?null:this.interestKey(c,f,p)})}}return{rest:s,entities:o,whole:a}}interestOps(e,t){let r=new Set(t),i=o=>o===null||r.has(o),s=[...e.rest];for(let o of e.entities){let a=o.before!==void 0&&i(o.beforeKey);o.after!==void 0&&i(o.afterKey)?s.push({o:"r",p:[o.collection,o.id],val:o.after}):a&&s.push({o:"x",p:[o.collection,o.id]})}for(let o of e.whole){let a=this.filterInterest({[o.collection]:o.after},t);s.push({o:"r",p:[o.collection],val:a[o.collection]})}return s}interestChange(e,t,r,i){let s={...t,interest:[...e.int],lastSeen:i};this.handles.set(s.h,s);let o={peer:r,h:t.h,frame:_({k:"ok",q:e.q,h:t.h})};if(this.interestFns.length===0||this.deferred.has(t.h))return this.accept([o]);let a=this.project(r,t.audience);if(a===null)return this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)]);let d=this.filterInterest(a,t.interest),c=this.filterInterest(a,s.interest),l=[];for(let[f]of this.interestFns){let w=d[f],R=c[f];if(!(!ye(w)||!ye(R))){for(let P of Object.keys(R))Object.prototype.hasOwnProperty.call(w,P)||l.push({o:"r",p:[f,P],val:R[P]});for(let P of Object.keys(w))Object.prototype.hasOwnProperty.call(R,P)||l.push({o:"x",p:[f,P]})}}if(l.length===0)return this.accept([o]);let u=String(this.core.revision),p=t.revision===this.core.revision?Nr({k:"delta",h:t.h,g:String(t.generation),base:u,r:u,ops:l},this.deps.maxEventBytes):null;if(p!==null)return this.accept([{peer:r,h:t.h,frame:p},o]);let y=this.install(s,null);return y===null?(this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)])):this.accept([...y,o])}project(e,t,r=this.core.getState()){try{let i=Object.freeze({peer:e,audience:Object.freeze([...t])}),s=this.deps.projectFor!==void 0?this.deps.projectFor(r,i):this.deps.project!==void 0?this.deps.project(r,t):r;this.visibility===null&&s===r&&this.warnOnce(`store '${this.deps.definition.id}': every player receives the full state. Declare \`visibility: 'open'\` on the definition if that is intended, or rules for what is secret.`);let o=this.visibility===null?s:Te(this.visibility,s,i);if(o===r)return r;try{return this.deps.definition.state(o)}catch(a){throw this.warnOnce(`store '${this.deps.definition.id}': a projection failed the state validator, so the player got empty() \u2014 ${a instanceof Error?a.message:String(a)}`+(this.visibility===null?"":" (a hidden field is the HIDDEN marker: wrap its parser with hiddenOr)")),a}}catch{try{return this.deps.definition.empty()}catch{return null}}}bind(e,t,r){let i=this.handles.get(e);return i===void 0?"handle-unknown":r-i.lastSeen>=Mr?(this.forget(e,"expired"),"handle-expired"):i.peer!==t?"handle-foreign-peer":i}no(e,t,r,i){return{peer:e,h:t,frame:_(i===null?{k:"no",h:t,code:r}:t===null?{k:"no",q:i,code:r}:{k:"no",q:i,h:t,code:r})}}refuse(e,t=[]){return this.counters[e]=(this.counters[e]??0)+1,{out:t,refused:e,deferred:null}}};function qr(n,e){let t=[];for(let r of Object.keys(e)){let i=e[r];if(Object.prototype.hasOwnProperty.call(n,r)&&Object.is(n[r],i))continue;let s=Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0,o=s===void 0?null:Vs(r,s,i);if(o!==null){t.push(...o);continue}s!==void 0&&JSON.stringify(s)===JSON.stringify(i)||t.push({o:"r",p:[r],val:i})}for(let r of Object.keys(n))Object.prototype.hasOwnProperty.call(e,r)||t.push({o:"x",p:[r]});return t}var Fs=128;function Vs(n,e,t){let r=a=>typeof a=="object"&&a!==null&&!Array.isArray(a);if(!r(e)||!r(t))return null;let i=[],s=Math.min(Fs,Math.max(1,Math.floor(Object.keys(t).length/2))),o=a=>U(a)<=Ye&&!["__proto__","constructor","prototype"].includes(a);for(let a of Object.keys(t)){let d=t[a];if(!(Object.prototype.hasOwnProperty.call(e,a)&&(Object.is(e[a],d)||JSON.stringify(e[a])===JSON.stringify(d)))&&(!o(a)||(i.push({o:"r",p:[n,a],val:d}),i.length>s)))return null}for(let a of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,a)&&(!o(a)||(i.push({o:"x",p:[n,a]}),i.length>s)))return null;return i}function Nr(n,e){let t;try{t=_(n)}catch{return null}return U(t)<=e?t:null}function Ks(n){return"q"in n&&typeof n.q=="string"?n.q:null}var Jr=5e3,Ur=500;function Be(n){let e=/^\d+$/.test(n),t=/^(0x)?[0-9a-f]{1,16}$/i.test(n);try{if(e)return BigInt(n).toString(16).padStart(16,"0");if(t)return BigInt(n.startsWith("0x")?n:`0x${n}`).toString(16).padStart(16,"0")}catch{return null}return null}function xn(n,e){let t=Be(n),r=Be(e);return t!==null&&t===r}var On=new WeakMap,Ht=new WeakMap;function zs(n){try{let e=JSON.parse(n);return e!==null&&typeof e=="object"&&e.k!=="join"&&typeof e.h=="string"?e.h:null}catch{return null}}var Fr=new WeakMap;function Lt(n){return Fr.get(n)}function $r(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var Br=new TextEncoder,Xs=new TextDecoder;function kn(n){let e=n.streamId??`store/${n.definition.id}`,t=n.store??n.definition.id,r=On.get(n.transport)??new Set;if(r.has(t))throw new h("invalid-data",`a store named ${t} is already hosted on this transport: name each store of one definition, or a join for that name is ambiguous`);r.add(t),On.set(n.transport,r);let i=new It({definition:n.definition,store:t,authorize:n.authorize,project:n.project,projectFor:n.projectFor,onEvent:n.onEvent,areaOf:n.areaOf,warn:n.dev===!0?v=>console.warn(`[@net-mesh/browser] ${v}`):typeof n.dev=="function"?n.dev:void 0,actions:n.actions,inputs:n.inputs,maxEventBytes:n.maxEventBytes,now:n.now??(()=>Date.now()),newHandle:n.newHandle??(()=>$r(16)),newIncarnation:n.newIncarnation??(()=>$r(8)),canProject:n.canProject??(()=>!0)});if(n.definition.visibility!==void 0){let v=Te(Le(n.definition.visibility),n.initialState,null);try{n.definition.state(v)}catch(A){throw new h("invalid-data",`store '${n.definition.id}': the state validator rejects a view with secrets hidden \u2014 wrap each field a rule hides with hiddenOr(\u2026): ${A instanceof Error?A.message:String(A)}`,{cause:A})}}i.commit(n.initialState);let s=new Map,o=null,a=new Map,d={},c=!1,l=null;async function u(v){let A=s.get(v);if(A!==void 0)return A;let C=a.get(v);if(C!==void 0)return C;let F=Promise.resolve(n.transport.openStream({reliability:"reliable",peer:v,label:e})).then(g=>{if(a.delete(v),c){try{g.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return s.set(v,g),g}).catch(g=>{throw a.delete(v),g});return a.set(v,F),F}async function p(v){for(let A of v){if(c)return;let C=Br.encode(A.frame),q=await u(A.peer);try{await q.send(C)}catch(F){if(c)return;if(!kt(F))throw F;if(s.get(A.peer)===q){s.delete(A.peer),a.delete(A.peer),d["reopened-stream"]=(d["reopened-stream"]??0)+1;try{q.close()}catch{}}await(await u(A.peer)).send(C)}}}function y(v){v.catch(()=>{d["send-failed"]=(d["send-failed"]??0)+1})}function f(v){y(p(v.out)),v.deferred!==null&&y(v.deferred.then(A=>f(A))),R()}let w=!1;function R(){if(!(w||c)){w=!0;try{let v=i.drainEvents();v.out.length>0&&y(p(v.out))}finally{w=!1}}}let P=Ht.get(n.transport)??new Set;P.add(i),Ht.set(n.transport,P);let M=n.transport.onEvent(v=>{if(v.type!=="stream_data")return;let A=v.peerNode;if(typeof A!="string"||A.length===0){d["no-authenticated-peer"]=(d["no-authenticated-peer"]??0)+1;return}let C=v.payload;if(C===void 0){d["no-payload"]=(d["no-payload"]??0)+1;return}let q=v.streamId;if(o!==null&&q!==void 0&&q!==o){d["foreign-stream"]=(d["foreign-stream"]??0)+1;return}let F;try{F=Xs.decode(C)}catch{d["undecodable-frame"]=(d["undecodable-frame"]??0)+1;return}let g=Be(A);if(g===null){d["unusable-peer"]=(d["unusable-peer"]??0)+1;return}let m=Ht.get(n.transport);if(m!==void 0&&m.size>1){let x=zs(F);if(x!==null&&i.handle(x)===void 0){let I=!1;for(let W of m)W!==i&&W.handle(x)!==void 0&&(I=!0);if(I||m.values().next().value!==i){d["sibling-handle"]=(d["sibling-handle"]??0)+1;return}}}let S=i.receive(F,g);q!==void 0&&o===null&&S.refused===null&&(o=q),f(S)}),H=n.schedule??((v,A)=>{let C=setInterval(v,A);return()=>{clearInterval(C)}}),k=H(()=>{if(c)return;let v=(n.now??(()=>Date.now()))(),A=i.sweep(v);A.length>0&&y(p(A.filter(C=>s.has(C.peer)).map(C=>({peer:C.peer,h:C.h,frame:_({k:"no",h:C.h,code:"closed"})})))),f(i.resumeDeferred(v))},Jr);async function E(){c=!0,k(),M();let v=i.farewell();await Promise.all(v.map(async A=>{let C=s.get(A.peer);if(C===void 0){d["farewell-unreachable"]=(d["farewell-unreachable"]??0)+1;return}try{await j(Promise.resolve(C.send(Br.encode(A.frame))))}catch{d["farewell-failed"]=(d["farewell-failed"]??0)+1}}));for(let A of s.values())try{A.close()}catch{d["stream-close-failed"]=(d["stream-close-failed"]??0)+1}s.clear(),a.clear(),On.get(n.transport)?.delete(t),Ht.get(n.transport)?.delete(i)}function j(v){return new Promise((A,C)=>{let q=()=>{m(),C(new h("timeout","the farewell did not flush before the deadline"))},F=H(q,Ur),g=setTimeout(q,Ur),m=()=>{F(),clearTimeout(g)};v.then(()=>{m(),A()},S=>{m(),C(S instanceof Error?S:new Error(String(S)))})})}let Y=n.transport.nodeIdHex()??i.incarnationHex,ee=new Set,ie={authority:Y,definition:n.definition,getState:()=>i.getState(),subscribe:v=>i.subscribe(v),setState:v=>{f(i.commit(v))},setEntities:(v,A)=>{f(i.commitEntities(v,A))},setEntity:(v,A,C)=>{let q={};Object.defineProperty(q,A,{value:C,enumerable:!0,writable:!0,configurable:!0}),f(i.commitEntities(v,q))},counts:()=>({handles:i.handleCount,ledgers:i.ledgerCount,deferred:i.deferredCount,sparseViews:i.sparseViews}),counters:()=>({...i.snapshotCounters(),...d}),close:()=>{if(l===null){l=E();for(let v of[...ee])v();ee.clear()}return l}};return Fr.set(ie,{owner:i,peer:Be(Y)??Y,maxEventBytes:n.maxEventBytes,dispatched:f,isClosed:()=>c,onClose:v=>{ee.add(v)}}),ie}var Gs=3,Tt=class{constructor(e){this.deps=e;this.#d=[...e.audience],this.#a=e.interest===void 0?null:[...e.interest]}deps;#e="joining";#t=null;#r=null;#n=null;#i=null;#b=null;#l=0n;#o=null;#u=!1;#c=null;#f=null;#m=0;#h=0;#p=null;#d;#y=0;#O=new _t;#w={};#a;get interest(){return this.#a===null?null:[...this.#a]}set interest(e){this.#a=e===null?null:[...e]}get desired(){return[...this.#d]}get waiters(){return this.#y}get state(){return this.#e}get handle(){return this.#t}get installed(){return this.#n===null?null:this.#n.toString()}get revision(){return this.#i===null?null:this.#i.toString()}get retired(){return this.#l.toString()}get skipped(){return this.#o===null?null:this.#o.toString()}get dropped(){return{...this.#w}}join(){if(this.#e==="closed")throw new h("closed","a closed replica cannot join again");this.#h+=1,this.#y=1,this.#E();let e=this.deps.newQ();return this.#c=e,this.#f=this.deps.now(),this.#m=0,this.#e="joining",this.deps.core.setStatus({phase:"connecting",stale:this.#v()}),{kind:"join",q:e,frame:_({k:"join",q:e,def:this.deps.definition.id,store:this.deps.store,ver:this.deps.definition.version,key:this.deps.key,aud:[...this.#d],...this.#a===null?{}:{int:[...this.#a]}})}}setAudience(e){if(this.#e==="closed")throw new h("closed","a closed replica cannot change audience");this.#h+=1;let t=[...e];if(this.#e==="installing"&&Qs(t,this.#d))return this.#y+=1,[];this.#d=t;let r=this.#t;if(this.#g(),this.#n=null,this.#i=null,this.#o=null,this.#u=!1,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:"syncing",stale:!1,error:null}),r===null)return this.#y=1,[this.join()];let i=this.deps.newQ();return this.#c=i,this.#f=this.deps.now(),this.#y=1,this.#e="installing",[{kind:"aud",q:i,frame:_({k:"aud",q:i,h:r,aud:t})}]}reconnect(){if(this.#e==="closed")throw new h("closed","a closed replica cannot reconnect");this.#h+=1;let e=this.#t;if(this.#g(),e===null)return[this.join()];let t=this.deps.newQ();return this.#c=t,this.#e="installing",this.deps.core.setStatus({phase:"reconnecting",stale:this.#v()}),[{kind:"resume",q:t,frame:_({k:"resume",q:t,h:e,aud:[...this.#d],...this.#a===null?{}:{int:[...this.#a]}})}]}cancelWaiter(){this.#y>0&&(this.#y-=1),!(this.#y>0)&&this.#e==="installing"&&this.cancel()}receive(e){if(this.#e==="closed")return this.#s("closed");let t=Me(e,{maxBytes:this.deps.maxEventBytes,as:"replica"});if(!t.ok)return this.#s(t.reason);let r=t.message;if("h"in r&&r.h!==void 0&&this.#t!==null&&r.h!==this.#t)return this.#s("foreign-handle");switch(r.k){case"man":return this.#A(r);case"snap":return this.#R(r);case"delta":return this.#P(r);case"no":return this.#j(r.code,r.q);case"ok":case"res":return this.#s("unimplemented-kind")}}tick(){let e=this.deps.now();if(this.#e==="installing"&&this.#p!==null)return this.#p.expired(e)?this.#k("assembly-deadline"):[];if(this.#f===null||e-this.#f<gn)return[];if(this.#e!=="joining"&&this.#e!=="installing")return[];if(this.#m>=Gs)return this.#f=null,this.#e="fenced",this.#c=null,this.#g(),this.#S("failed",new h("timeout",`no store named ${this.deps.store} answered the join`)),[];let t=this.#m,r=this.join();return this.#m=t+1,[r]}cancel(){this.#e!=="closed"&&(this.#h+=1,this.#g(),this.#c=null,this.#e="fenced",this.#o=null,this.#u=!1,this.#S("failed"))}#A(e){let t=le(e.g),r=e.q!==void 0&&e.q===this.#c;if(e.q!==void 0&&!r)return this.#s("stale-correlation");if(t<=this.#l)return this.#s("stale-generation");if(r){if(this.#e!=="joining"&&this.#e!=="installing"&&this.#e!=="fenced")return this.#s("unexpected-manifest")}else{if(this.#e==="fenced")return this.#s("fenced");if(this.#e!=="ready")return this.#o=this.#o===null?t:Ys(this.#o,t),this.#s("mid-transition")}if(this.#t===null)this.#t=e.h,this.#r=e.inc;else if(this.#r!==null&&e.inc!==this.#r)return this.#s("foreign-incarnation");this.#g(),this.#l=t;let i={h:e.h,g:e.g,r:e.r,n:e.n,bytes:e.bytes},s=this.#O.open(i,this.deps.now());return"accept"in s?(this.#b=t,this.#p=s,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),{out:[],dropped:null}):{out:this.#k(s.reason),dropped:s.reason}}#R(e){let t=this.#p;if(t===null)return this.#s("no-open-assembly");let r=this.#h,i=t.accept({h:e.h,g:e.g,r:e.r,n:e.n,i:e.i,d:e.d},s=>this.deps.definition.state(s),this.deps.now());return this.#h!==r?this.#s("superseded-installation"):i.ok?i.done?this.#_(i.document,e.g,e.r,r):{out:[],dropped:null}:i.fatal?{out:this.#k(i.reason),dropped:i.reason}:this.#s(i.reason)}#_(e,t,r,i){return this.deps.core.applySnapshot(e),this.#b=null,this.#p=null,this.#O.reclaim(this.#t,t),this.#h!==i?(this.#n=null,this.#i=null,this.#S("failed"),this.#s("superseded-installation")):(this.#n=le(t),this.#i=le(r),this.#c=null,this.#e="ready",this.deps.core.setStatus({phase:"ready",stale:!1,error:null}),{out:this.#C(),dropped:null})}#P(e){if(this.#e!=="ready")return this.#u=!0,this.#s("not-ready");let t=le(e.g),r=this.#n;if(r===null||t!==r)return r!==null&&t>r?{out:this.#x("generation-ahead"),dropped:"generation-ahead"}:this.#s("stale-generation");if(this.#i===null||le(e.base)!==this.#i)return{out:this.#x("gap"),dropped:"gap"};let i=this.deps.core.applyDelta(e.ops);return i.ok?(this.#i=le(e.r),{out:[],dropped:null}):{out:this.#x(i.reason),dropped:i.reason}}#j(e,t){if(e==="owner-lost")return this.#g(),this.#e="closed",this.#t=null,this.#S("closed"),{out:[],dropped:"owner-lost"};if(e==="closed"){let r=this.#e==="fenced";return this.#E(),r?(this.#S("failed"),{out:[],dropped:"closed-while-fenced"}):(this.#S("connecting"),{out:[this.join()],dropped:"closed"})}return t===void 0||t!==this.#c?this.#s("stale-correlation"):(this.#g(),this.#c=null,this.#e="fenced",this.#S("failed",new h(e,`the request was refused: ${e}`)),{out:[],dropped:`refused-${e}`})}#k(e){return this.#g(),this.#b=null,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),this.#x(e)}#x(e){let t=this.#t;if(t===null)return[];let r=this.deps.newQ();return this.#c=r,this.#f=this.deps.now(),this.#e="installing",this.#o=null,this.#u=!1,this.deps.core.setStatus({phase:this.#v()?"reconnecting":"syncing",stale:this.#v()}),[{kind:"resync",q:r,frame:_({k:"resync",q:r,h:t,g:this.#n===null?"0":this.#n.toString(),have:this.#i===null?"0":this.#i.toString()})}]}#C(){let e=this.#o,t=this.#u;return!t&&(e===null||this.#n===null||e<=this.#n)?(this.#o=null,this.#u=!1,[]):this.#x(t?"behind":"skipped-refresh")}#E(){this.#g(),this.#t=null,this.#r=null,this.#n=null,this.#i=null,this.#l=0n,this.#o=null,this.#u=!1,this.#c=null}#g(){this.#p!==null&&(this.#p.reclaim(),this.#p=null),this.#t!==null&&this.#O.reclaimHandle(this.#t),this.#b=null}#v(){return this.#n!==null}#S(e,t=null){this.#n=null,this.#i=null,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:e,stale:!1,error:t})}#s(e){return this.#w[e]=(this.#w[e]??0)+1,{out:[],dropped:e}}};function Ys(n,e){return n>e?n:e}function Qs(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Kr=2e4,En=1e4,Zs=6e4,eo=1e3,An=64,Vr=new TextEncoder,to=new TextDecoder;function Qe(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function Rn(n){let e=n.transport.nodeIdHex();if(e!==null&&xn(e,n.host))throw new h("invalid-data","a replica cannot join the node it runs on: hold the hostStore handle instead");let t=n.streamId??`store/${n.definition.id}`,r=n.now??(()=>Date.now()),i=n.schedule??((g,m)=>{let S=setInterval(g,m);return()=>{clearInterval(S)}}),s=new he({definition:n.definition,initialState:n.definition.empty()}),o=new Tt({definition:n.definition,core:s,maxEventBytes:n.maxEventBytes,now:r,newQ:()=>(n.newQ??(()=>Qe(8)))(),audience:n.audience,store:n.store??n.definition.id,key:n.key,...n.interest===void 0?{}:{interest:n.interest}}),a=new Map,d=new Map,c=0n,l=!1,u=null,p=null,y=[],f=null;async function w(){if(u!==null)return u;if(p!==null)return p;let g=Be(n.host);return g===null?Promise.reject(new h("invalid-data",`the host id is not a node id: ${n.host}`)):(p=Promise.resolve(n.transport.connectPeer?.(g)).catch(()=>{}).then(()=>n.transport.openStream({reliability:"reliable",peer:g,label:t})).then(m=>{if(p=null,l){try{m.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return u=m,m}).catch(m=>{throw p=null,m}),p)}async function R(g){for(let m of g){if(l)return;let S=Vr.encode(m),x=await w();try{await x.send(S)}catch(I){if(l)return;if(!kt(I))throw I;if(u===x){u=null,p=null;try{x.close()}catch{}}await(await w()).send(S)}}}function P(g){let m=g instanceof h?g:new h("indeterminate",`the transport could not carry a store frame: ${String(g)}`);for(let S of y.splice(0,y.length))S.reject(m);E(m);for(let[S,x]of[...a])a.delete(S),x.reject(m)}function M(g){R(g).catch(P)}let H=g=>g.map(m=>m.frame);function k(g){if(o.state==="ready"){E(null);for(let S of y.splice(0,y.length))S.resolve();return}if(o.state!=="fenced"&&o.state!=="closed")return;let m=g??new h(o.state==="closed"?"owner-lost":"aborted",`the store handle is ${o.state}`);E(m);for(let S of y.splice(0,y.length))S.reject(m)}function E(g){let m=f;if(m!==null){f=null,m.q!==null&&a.delete(m.q);for(let S of[...m.calls])m.calls.delete(S),g===null?S.resolve():S.reject(g)}}function j(g){return E(new h("aborted","a newer transition superseded this one before it installed")),f={q:g,calls:new Set},g===null?null:a.size>=An?new h("capacity","too many requests are already outstanding"):(a.set(g,{resolve:()=>E(null),reject:m=>E(m),at:r(),transition:!0}),null)}function Y(){return new Promise((g,m)=>{let S={resolve:g,reject:m,deadlineAt:r()+Zs},x=f??{q:null,calls:new Set};f=x,x.calls.add(S)})}let ee=n.transport.onEvent(g=>{if(l||g.type!=="stream_data"||typeof g.peerNode!="string"||!xn(g.peerNode,n.host))return;let m=g.payload;if(m===void 0)return;let S=to.decode(m),x=Me(S,{maxBytes:n.maxEventBytes,as:"replica"});if(x.ok&&"q"in x.message&&typeof x.message.q=="string"){let K=a.get(x.message.q);if(K!==void 0&&(x.message.k==="res"||x.message.k==="ok")){a.delete(x.message.q),K.resolve(x.message.k==="res"?x.message.out:void 0);return}K!==void 0&&x.message.k==="no"&&(a.delete(x.message.q),K.reject(new h(x.message.code,`the store refused: ${x.message.code}`)))}let I=null;x.ok&&x.message.k==="no"&&(I=new h(x.message.code,`the store refused: ${x.message.code}`));let W=o.receive(S);M(H(W.out)),k(I)}),ie=i(()=>{if(l)return;let g=o.handle;g!==null&&M([_({k:"alive",q:Qe(8),h:g})])},Kr),v=i(()=>{if(l)return;let g=r(),m=f;if(m!==null){for(let S of[...m.calls])g<S.deadlineAt||(m.calls.delete(S),o.cancelWaiter(),S.reject(new h("indeterminate","the transition did not install before its deadline")));m.q!==null&&m.calls.size===0&&E(null)}for(let[S,x]of[...a])x.transition||g-x.at<En||(a.delete(S),x.reject(new h("indeterminate","the store did not answer before the deadline")))},En),A=i(()=>{l||(M(H(o.tick())),k(s.getStatus().error??null))},eo),C;try{C=o.join()}catch(g){throw new h("invalid-data","the join request cannot be encoded",{cause:g})}j(null),M(H([C]));function q(g){return a.size>=An?Promise.reject(new h("capacity","too many requests are already outstanding")):new Promise((m,S)=>{a.set(g,{resolve:x=>{m(x)},reject:S,at:r(),transition:!1})})}let F={getState:()=>s.getState(),subscribe:g=>s.subscribe(g),getStatus:()=>s.getStatus(),subscribeStatus:g=>s.subscribeStatus(g),ready:()=>new Promise((g,m)=>{if(l){m(new h("closed","this store handle is closed"));return}if(o.state==="ready"){g();return}if(o.state==="closed"){m(new h("owner-lost","the store owner closed this handle"));return}y.push({resolve:g,reject:m})}),act:async(g,m)=>{if(l)throw new h("closed","this store handle is closed");if(o.state==="closed")throw new h("owner-lost","the store owner closed this handle");let S=o.handle;if(S===null)throw new h("not-ready","no handle yet: the join has not been answered");c+=1n;let x=(n.newQ??(()=>Qe(8)))(),I;try{I=_({k:"act",q:x,h:S,s:c.toString(),name:g,in:m})}catch(K){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:K})}let W=q(x);return W.catch(()=>{}),await R([I]),await W},input:(g,m)=>{if(l)return{type:"dropped",reason:"not-ready"};let S=o.handle;if(S===null||o.state!=="ready")return{type:"dropped",reason:"not-ready"};let x=(d.get(g)??0n)+1n;d.set(g,x);let I;try{I=_({k:"in",h:S,s:x.toString(),name:g,in:m})}catch(W){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:W})}return M([I]),{type:x===1n?"queued":"replaced"}},setAudience:async g=>{if(l)throw new h("closed","this store handle is closed");let m;try{m=o.setAudience(g)}catch(I){throw new h("invalid-data","the audience cannot be encoded",{cause:I})}let S=m[0];if(S!==void 0){let I=j(S.q);if(I!==null)throw I}let x=Y();x.catch(()=>{}),S!==void 0&&await R(H(m)),await x},setInterest:async g=>{if(l)throw new h("closed","this store handle is closed");let m=[...g],S="0".repeat(32),x;try{x=_({k:"int",q:"0".repeat(16),h:S,int:m})}catch(Je){throw new h("invalid-data","the interest set cannot be encoded",{cause:Je})}if(U(x)>n.maxEventBytes)throw new h("capacity","the interest set does not fit one message");o.interest=m;let I=o.handle;if(I===null||o.state!=="ready")return await F.ready(),o.interest===null||o.interest.join("\0")!==m.join("\0")?void 0:F.setInterest(m);let W=(n.newQ??(()=>Qe(8)))(),K=q(W);K.catch(()=>{}),await R([_({k:"int",q:W,h:I,int:m})]),await K},reconnect:async()=>{if(l)throw new h("closed","this store handle is closed");u=null,p=null;let g;try{g=o.reconnect()}catch(m){throw new h("invalid-data","the reconnect request cannot be encoded",{cause:m})}g[0]!==void 0&&j(null),await R(H(g))},close:async()=>{if(l)return;l=!0,ie(),v(),A();let g=o.handle;if(g!==null)try{await(await w()).send(Vr.encode(_({k:"leave",q:Qe(8),h:g})))}catch{}ee(),E(new h("aborted","the store handle closed before this request was answered"));for(let m of a.values())m.reject(new h("aborted","the store handle closed before this request was answered"));a.clear();for(let m of y.splice(0,y.length))m.reject(new h("closed","the store handle closed before a view was installed"));u?.close(),u=null,s.close()}};return F}var Xr="0".repeat(16),_n="0".repeat(32);function zr(n,e,t){let r;try{r=t==="act"?_({k:"act",q:Xr,h:_n,s:"1",name:n,in:e}):_({k:"in",h:_n,s:"1",name:n,in:e})}catch(s){throw new h("invalid-data",`the input for '${n}' cannot be encoded`,{cause:s})}let i=De(r);if(!i.ok||typeof i.value!="object"||i.value===null||Array.isArray(i.value))throw new h("invalid-data",`the input for '${n}' cannot be encoded`);return i.value.in}function no(n){let e=De(JSON.stringify(n));return e.ok?e.value:n}function Pn(n,e){let t=Lt(n);if(t===void 0)throw new h("invalid-data","hostPlayer needs a handle returned by hostStore");let{owner:r,peer:i}=t,s=n.definition,o=new he({definition:s,initialState:s.empty(),phase:"syncing"}),a=[...e.audience],d=e.interest===void 0?null:[...e.interest],c=!1,l=!1,u=new Map;function p(k,E){l=!0,E?.code==="forbidden"&&queueMicrotask(()=>R("refused")),o.applySnapshot(s.empty()),o.setStatus({phase:k,stale:!1,error:E})}function y(){if(c||l)return;if(t.isClosed()){p("closed",null);return}if(!r.localRead(i,a)){p("failed",new h("forbidden","the store refused: forbidden"));return}let k=r.localView(i,a,d);if(k===null){p("failed",new h("capacity","the store refused: capacity"));return}o.applySnapshot(k),o.setStatus({phase:"ready",stale:!1,error:null})}let f=r.subscribe(()=>{y()});t.onClose(()=>{f(),!c&&!l&&p("closed",null)}),y();let w=!1;o.getStatus().phase==="ready"&&(w=!0,r.localPresence(i,!0,a),t.dispatched({out:[],refused:null,deferred:null}));function R(k){!w||t.isClosed()||(w=!1,r.localPresence(i,!1,a,k),t.dispatched({out:[],refused:null,deferred:null}))}function P(){return c?new h("closed","this store handle is closed"):t.isClosed()?new h("owner-lost","the store owner closed this handle"):l?o.getStatus().error??new h("owner-lost","the store owner closed this handle"):null}function M(){let k=[...u];if(u.clear(),P()===null)for(let[E,j]of k)t.dispatched(r.localInput(E,j,i))}function H(k,E,j){return E===void 0?o.subscribe(k):o.subscribe(k,E,j)}return{getState:()=>o.getState(),subscribe:H,getStatus:()=>o.getStatus(),subscribeStatus:k=>o.subscribeStatus(k),ready:()=>{let k=o.getStatus();return k.phase==="ready"?Promise.resolve():Promise.reject(k.error??new h(c?"closed":"owner-lost","this store handle is not ready"))},act:async(k,E)=>{let j=P();if(j!==null)throw j;let Y=zr(k,E,"act");await Promise.resolve();let ee=P();if(ee!==null)throw ee;let{outcome:ie,dispatched:v}=r.localAct(k,Y,i);if(t.dispatched(v),ie.kind==="refusal")throw new h(ie.code,`the store refused: ${ie.code}`);return no(ie.out)},input:(k,E)=>{if(P()!==null||o.getStatus().phase!=="ready")return{type:"dropped",reason:"not-ready"};let j=zr(k,E,"in"),Y=u.size===0,ee=u.has(k);return u.set(k,j),Y&&queueMicrotask(M),{type:ee?"replaced":"queued"}},setAudience:async k=>{let E=P();if(E!==null)throw E;try{_({k:"aud",q:Xr,h:_n,aud:[...k]})}catch(Y){throw new h("invalid-data","the audience cannot be encoded",{cause:Y})}await Promise.resolve();let j=P();if(j!==null)throw j;if(!r.localRead(i,k))throw new h("forbidden","the store refused: forbidden");a=[...k],y()},setInterest:async k=>{let E=P();if(E!==null)throw E;let j=[...k];await Promise.resolve(),d=j,y()},reconnect:()=>Promise.resolve(),close:()=>(c||(c=!0,R("left"),u.clear(),f(),o.close()),Promise.resolve())}}var ue=class extends Error{constructor(t,r){super(r);this.code=t;this.name="InventoryError"}code},jn=64,Cn=Object.freeze({});function ro(){return Cn}function Gr(n){if(typeof n!="string"||n.length===0||n.length>jn||n==="__proto__")throw new ue("invalid",`an item id is 1-${jn} characters, got ${JSON.stringify(n)}`)}function Yr(n){if(!Number.isSafeInteger(n)||n<1)throw new ue("invalid",`a count is a whole number of at least 1, got ${String(n)}`)}function io(n,e){let t=e?.maxCount;return t===void 0?Number.MAX_SAFE_INTEGER:typeof t=="number"?t:Object.prototype.hasOwnProperty.call(t,n)?t[n]:Number.MAX_SAFE_INTEGER}function Dt(n,e){return n===void 0||!Object.prototype.hasOwnProperty.call(n,e)?0:n[e]??0}function so(n,e,t=1){return Dt(n,e)>=t}function Qr(n,e,t,r){Gr(e),Yr(t);let i=Dt(n,e),s=i+t;if(!Number.isSafeInteger(s)||s>io(e,r))throw new ue("full",`no room for ${String(t)} more ${e}`);if(i===0&&r?.maxKinds!==void 0&&Object.keys(n).length>=r.maxKinds)throw new ue("full",`no room for another kind of item (${String(r.maxKinds)} at most)`);return Object.freeze({...n,[e]:s})}function oo(n,e,t){Gr(e),Yr(t);let r=Dt(n,e);if(r<t)throw new ue("insufficient",`has ${String(r)} ${e}, needs ${String(t)}`);let i={...n};return r===t?delete i[e]:i[e]=r-t,Object.freeze(i)}function ao(n,e){if(typeof n!="object"||n===null||Array.isArray(n))throw new ue("invalid","an inventory is an object of item id \u2192 count");let t=Cn;for(let[r,i]of Object.entries(n)){if(typeof i!="number")throw new ue("invalid",`the count of ${r} is not a number`);t=Qr(t,r,i,e)}return t}function lo(n,e){return Object.prototype.hasOwnProperty.call(n,e)?n[e]:Cn}function co(n,e){return Object.prototype.hasOwnProperty.call(n,e)?{[e]:n[e]}:{}}function Zr(n){if(!(n>0)||!Number.isFinite(n))throw new RangeError(`a cell size is a positive number, got ${String(n)}`)}function uo(n,e,t){return Zr(t),`${String(Math.floor(n/t))}:${String(Math.floor(e/t))}`}function po(n){let e=/^(-?\d+):(-?\d+)$/.exec(n);return e===null?null:[Number(e[1]),Number(e[2])]}function ei(n,e,t){Zr(t.size);let r=t.radius??1,i=Math.floor(n/t.size),s=Math.floor(e/t.size),o=[`${String(i)}:${String(s)}`];for(let a=-r;a<=r;a+=1)for(let d=-r;d<=r;d+=1)(a!==0||d!==0)&&o.push(`${String(i+a)}:${String(s+d)}`);return o}function fo(n,e,t,r){let i=ei(e,t,r),o=(r.radius??1)+(r.margin??1),a=Math.floor(e/r.size),d=Math.floor(t/r.size),c=new Set(i);for(let l of n){if(c.has(l))continue;let u=po(l);u!==null&&Math.abs(u[0]-a)<=o&&Math.abs(u[1]-d)<=o&&(i.push(l),c.add(l))}return i}function ho(n,e){if(n.length!==e.length)return!1;let t=new Set(n);return e.every(r=>t.has(r))}var J=class extends Error{constructor(t,r){super(r);this.code=t;this.name="LobbyError"}code},ti=64,ni=256,In=512,ri=256,Mt="ABCDEFGHJKMNPQRSTUVWXYZ23456789",Hn=6,si=2e3,oi=8104,yo=/^[a-z0-9][a-z0-9._-]{0,63}$/,ai=1,Ze=new TextEncoder,go=new TextDecoder;function Ln(n){if(!yo.test(n))throw new J("invalid",`a game name is 1-64 of a-z 0-9 . _ - (starting with a letter or digit), got ${JSON.stringify(n)}`)}function Tn(n){let e=n.toUpperCase().replace(/[\s-]/g,"");if(e.length!==Hn||[...e].some(t=>!Mt.includes(t)))throw new J("invalid",`not a lobby code: ${JSON.stringify(n)}`);return e}function mo(){let n=256-256%Mt.length,e="";for(;e.length<Hn;){let t=new Uint8Array(16);crypto.getRandomValues(t);for(let r of t)r<n&&e.length<Hn&&(e+=Mt[r%Mt.length])}return e}function bo(n,e){return`net-lobby:${n}:seek:${e}`}function li(n){return`net-lobby:${n}`}function Dn(n){return`net-lobby:${n}:rec:`}async function ci(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",Ze.encode(`net-lobby${n}${e}`))),r="";for(let i of t.subarray(0,16))r+=i.toString(16).padStart(2,"0");return`net-lobby:${n}:code:${r}`}function So(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function wo(n){if(!/^[A-Za-z0-9_-]*$/.test(n))return null;try{let e=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(e,t=>t.charCodeAt(0))}catch{return null}}function di(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new J("invalid","lobby info is a flat object of strings, numbers and booleans");let e={};for(let[t,r]of Object.entries(n)){if(typeof r=="number"?!Number.isFinite(r):typeof r!="string"&&typeof r!="boolean")throw new J("invalid",`lobby info.${t} must be a string, a finite number or a boolean`);e[t]=r}if(Ze.encode(JSON.stringify(e)).length>ni)throw new J("invalid",`lobby info is over ${ni} bytes of JSON`);return Object.freeze(e)}function ui(n){if(typeof n!="string"||n.trim().length===0||[...n].length>ti)throw new J("invalid",`a lobby name is 1-${ti} characters`);return n}function pi(n){if(typeof n!="number"||!Number.isInteger(n)||n<1||n>ri)throw new J("invalid",`capacity is a whole number from 1 to ${ri}`);return n}function ii(n,e){let t=JSON.stringify({v:ai,c:e.code,n:e.name,p:e.players,m:e.capacity,s:e.store,i:e.info}),r=Dn(n)+So(Ze.encode(t));if(Ze.encode(r).length>In)throw new J("invalid",`the lobby record is over ${In} bytes: shorten the name or info`);return r}function vo(n,e){if(Ze.encode(e).length>In)return null;let t=wo(e.slice(Dn(n).length));if(t===null)return null;let r;try{r=JSON.parse(go.decode(t))}catch{return null}if(typeof r!="object"||r===null)return null;let i=r;try{if(i.v!==ai||typeof i.c!="string"||typeof i.s!="string"||i.s.length>200)return null;let s=pi(i.m),o=i.p;return typeof o!="number"||!Number.isInteger(o)||o<0||o>s?null:{code:Tn(i.c),name:ui(i.n),players:o,capacity:s,store:i.s,info:di(i.i??{})}}catch{return null}}function qt(n){let e=n.startsWith("0x")?n.slice(2):n;if(/^[0-9a-fA-F]{1,16}$/.test(e))return e.toLowerCase().padStart(16,"0");throw new J("invalid",`not a peer id: ${JSON.stringify(n)}`)}async function Dl(n){let{node:e,game:t}=n;Ln(t);let r=ui(n.name),i=pi(n.capacity),s=di(n.info??{}),o=n.visibility??"public",a=mo(),d=`${n.definition.id}@${n.definition.version}`,c=await ci(t,a);ii(t,{code:a,name:r,players:i,capacity:i,store:d,info:s});let l=e.nodeIdHex();if(l===null)throw new J("invalid","the node has no id yet: connect it before opening a lobby");let u=qt(l),p=new Set,y=n.authorize??(()=>!0),f=()=>[],w=N=>{let te=N.peer;return p.has(te)||N.type==="read"&&te!==u&&!f().includes(te)&&1+f().filter(wi=>wi!==u).length>=i?!1:y(N)},{audience:R,tags:P,announceEveryMs:M,maxEventBytes:H}=n,{node:k,game:E,name:j,capacity:Y,visibility:ee,info:ie,audience:v,tags:A,announceEveryMs:C,maxEventBytes:q,authorize:F,...g}=n,m=kn({...g,transport:e,maxEventBytes:H??oi,authorize:w}),S=Lt(m);f=()=>S.owner.peers();let x=Pn(m,{audience:R??[]});function I(){return[u,...S.owner.peers().filter(N=>N!==u)]}let W=new Set,K=!1,Je=null,Nt=!1;function mi(){let N=[...P??[],c];return o==="public"&&N.push(li(t),ii(t,{code:a,name:r,players:I().length,capacity:i,store:d,info:s})),N}function et(){if(!K){if(Je!==null){Nt=!0;return}Je=e.announce(mi()).catch(()=>{}).finally(()=>{Je=null,Nt&&(Nt=!1,et())})}}let Mn=I().join(),bi=S.owner.onMembership(()=>{queueMicrotask(()=>{if(K)return;let N=I();if(N.join()!==Mn){Mn=N.join(),et();for(let te of[...W])try{te(N)}catch{}}})});et();let Si=setInterval(et,M??si);return{code:a,game:t,visibility:o,host:m,self:x,players:I,subscribePlayers:N=>(W.add(N),()=>{W.delete(N)}),link:N=>{let te=new URL(N??globalThis.location?.href??"about:blank");return te.searchParams.set("lobby",a),te.toString()},kick:N=>{let te=qt(N);if(te===u)throw new J("invalid","the host cannot kick itself; close the lobby instead");p.add(te),S.dispatched(S.owner.reauthorize())},close:async()=>{K||(K=!0,clearInterval(Si),bi(),W.clear(),await x.close(),await m.close(),await e.announce([...P??[]]).catch(()=>{}))}}}async function Ml(n){Ln(n.game);let e=Dn(n.game),t=[],r=new Set;for(let i of await n.node.query(li(n.game))){if(r.has(i.peerIdHex))continue;let s=i.capabilities.find(a=>a.startsWith(e));if(s===void 0)continue;let o=vo(n.game,s);o!==null&&(r.add(i.peerIdHex),t.push({...o,host:i.peerIdHex}))}return t}async function ql(n){Ln(n.game);let e;if(n.lobby!==void 0)e=qt(n.lobby.host);else if(n.code!==void 0){let p=await ci(n.game,Tn(n.code)),y=Date.now()+(n.timeoutMs??2e4),f=[];for(;f=[...new Set((await n.node.query(p)).map(w=>w.peerIdHex))],!(f.length>0||Date.now()>=y);)await new Promise(w=>setTimeout(w,250));if(f.length===0)throw new J("not-found",`no lobby answered to code ${n.code}`);if(f.length>1)throw new J("ambiguous",`${f.length} nodes claim code ${n.code}; join from the list instead`);e=f[0]}else throw new J("invalid","joinLobby needs a code or a lobby");let t=n.node.nodeIdHex();if(t!==null&&qt(t)===e)throw new h("invalid-data","this node hosts that lobby: use lobby.self to play in it");let r=n.node,i=[...n.tags??[]],s=[...i,bo(n.game,e)],o=!1,a=()=>{o||r.announce(s).catch(()=>{})};a();let d=setInterval(a,si),c=()=>{o||(o=!0,clearInterval(d),r.announce(i).catch(()=>{}))};if(r.connectPeer!==void 0){let p=Date.now()+(n.timeoutMs??2e4);for(;;)try{await r.connectPeer(e);break}catch(y){if(Date.now()>=p)throw c(),new J("not-found",`could not reach the lobby's host ${e}: ${String(y?.message??y)}`);await new Promise(f=>setTimeout(f,500))}}let l;try{l=Rn({definition:n.definition,transport:r,host:e,audience:n.audience??[],key:n.key??"player",maxEventBytes:n.maxEventBytes??oi,...n.interest===void 0?{}:{interest:n.interest}})}catch(p){throw c(),p}let u=l.close.bind(l);return l.close=async()=>{c(),await u()},l}function Nl(n){try{let e=new URL(n??globalThis.location?.href??"").searchParams.get("lobby");return e===null?null:Tn(e)}catch{return null}}var yi="net-mesh:identity";function fi(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var hi=/^[0-9a-f]{64}$/;function Oo(n){if(n===null)return null;try{let e=JSON.parse(n);if(typeof e.entitySecretHex=="string"&&typeof e.noiseSecretHex=="string"&&hi.test(e.entitySecretHex)&&hi.test(e.noiseSecretHex))return{entitySecretHex:e.entitySecretHex,noiseSecretHex:e.noiseSecretHex}}catch{}return null}function xo(n=yi,e){let t=e;try{t??=globalThis.localStorage}catch{t=void 0}let r=null;try{r=Oo(t?.getItem(n)??null)}catch{t=void 0}if(r!==null)return r;let i={entitySecretHex:fi(32),noiseSecretHex:fi(32)};try{t?.setItem(n,JSON.stringify(i))}catch{}return i}var qe=class extends Error{constructor(t,r,i=null){super(r);this.kind=t;this.status=i}kind;status;name="CredentialRequestError"},gi={unknown_game:"unknown-game",rate_limited:"rate-limited",malformed_request:"malformed-request"};async function ko(n){let e=n.fetch??globalThis.fetch;if(typeof e!="function")throw new qe("unreachable","requestCredential needs fetch");let t=`${n.anchorUrl.replace(/\/+$/,"")}/credential`,r;try{r=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({game:n.game}),...n.signal===void 0?{}:{signal:n.signal}})}catch(o){throw n.signal?.aborted?o:new qe("unreachable",`could not reach ${t}: ${String(o)}`)}let i=null;try{i=await r.json()}catch{}if(!r.ok){let o=i?.refusal,a=i?.message,d=typeof o=="string"&&o in gi?gi[o]:r.status===404?"unreachable":"unexpected",c=d==="unreachable"?`${t} issues no credentials (is the anchor started with --game?)`:typeof a=="string"?a:`the anchor answered ${r.status}`;throw new qe(d,c,r.status)}let s=i;if(typeof s?.credentialB64!="string"||typeof s.bootstrapUrl!="string"||typeof s.game!="string")throw new qe("unexpected","the anchor answered without a credential",r.status);return{credentialB64:s.credentialB64,bootstrapUrl:s.bootstrapUrl,game:s.game}}export{Kr as ALIVE_INTERVAL_MS,we as AsyncQueue,St as BrowserNode,nt as ControlPlaneError,qe as CredentialRequestError,yi as DEFAULT_IDENTITY_KEY,Ae as EventHub,Et as HIDDEN,Jr as HOST_SWEEP_MS,rt as IceServerConflictError,ge as IdentityError,ue as InventoryError,si as LOBBY_ANNOUNCE_MS,Mt as LOBBY_CODE_ALPHABET,Hn as LOBBY_CODE_LENGTH,z as LeafError,je as LeafStream,J as LobbyError,Wr as MAX_EVENT_ROUNDS,yr as MAX_INTEREST_KEYS,gr as MAX_INTEREST_KEY_BYTES,jn as MAX_ITEM_ID_CHARS,ri as MAX_LOBBY_CAPACITY,ni as MAX_LOBBY_INFO_BYTES,ti as MAX_LOBBY_NAME_CHARS,In as MAX_LOBBY_RECORD_TAG_BYTES,An as MAX_OUTSTANDING,xt as MeshSession,it as NotLeaderError,lt as ORG_SINK_CLOSED_REFUSAL,pe as OrgAdmissionDeniedError,D as OrgCancelledError,Pe as OrgDuplex,Re as OrgHandleRegistry,Fe as OrgIndeterminateError,ve as OrgInternalError,Z as OrgLeaderLostError,We as OrgMalformedError,Ve as OrgRefusedError,ze as OrgRequests,xe as OrgRevokedError,X as OrgServe,Ee as OrgSessionLostError,Ke as OrgSink,be as OrgStream,Q as OrgStreamError,ke as OrgTimeoutError,_e as OrgUpload,En as REQUEST_DEADLINE_MS,st as RpcError,oe as RtcError,Oe as SessionError,he as StoreCore,h as StoreError,Fn as U64_EVENT_KEYS,Ne as UnknownLeafError,tt as WireError,Qr as addItems,nn as asSessionModule,ss as assertHidden,wt as buildConnectRequest,zt as candidateLineIsReflexive,uo as cellKey,ei as cellsAround,Ui as classifyRtcError,er as classifyRtcFailure,mt as classifyRtcFailureAll,ot as coarseAdmissionReason,zi as connect,Dt as countItems,Dl as createLobby,os as defineStore,nr as diagnosticStunUrl,ro as emptyInventory,Vn as fromBase64,b as fromWasmError,so as hasItems,ts as hiddenOr,Pn as hostPlayer,kn as hostStore,lo as inventoryOf,At as isHidden,tn as isLifecycleEvent,_i as isUdpBlocked,ql as joinLobby,Rn as joinStore,Ml as listLobbies,Ge as loadLeafWasm,Nl as lobbyCodeFromUrl,Pt as mergeShallow,Tn as normalizeLobbyCode,co as onlyOwn,es as openSession,Oi as orgRetireError,ct as orgRetireReason,Wt as orgTerminalError,Ie as parseAttemptStatus,vt as parseCounters,Ot as parseDescriptors,me as parseEvent,ao as parseInventory,dt as parseJsonPreservingU64,Un as parseLeafError,Xe as parseOrgCaller,Nn as parseOrgError,ar as parseRetryReport,Bn as parseRpcFailure,$n as parseRtcFailure,or as parseRtcStats,en as parseSessionEvent,sr as peerIdHex,Yt as probeBootstrapReachable,Xt as probeEventAnswers,tr as probeStunBinding,Gt as probeStunBindings,pr as projectVisible,ce as reconcile,Zt as refineIceFailure,rr as reflexiveAddress,xo as rememberedIdentity,oo as removeItems,ko as requestCredential,ho as sameCells,fo as stickyCells,Wi as stunProbeAnswered,Zn as stunProbeVerdict,Jt as toBase64,ne as toWasmOrgCallOptions,re as toWasmOrgServeOptions,at as udpBlockedEvidence};
1
+ var Ae=class{constructor(e=()=>{}){this.detach=e}detach;buffered=[];waiting=null;ended=!1;push(e){if(this.ended)return;let t=this.waiting;if(t){this.waiting=null,t({value:e,done:!1});return}this.buffered.push(e)}end(){if(this.ended)return;this.ended=!0;let e=this.waiting;e&&(this.waiting=null,e({value:void 0,done:!0}))}next(){let e=this.buffered.shift();if(e!==void 0)return Promise.resolve({value:e,done:!1});if(this.ended)return Promise.resolve({value:void 0,done:!0});let{promise:t,resolve:r}=Promise.withResolvers();return this.waiting=r,t}return(){return this.detach(),this.end(),Promise.resolve({value:void 0,done:!0})}[Symbol.asyncIterator](){return this}};function vt(n,e,t,r=[t]){return!n||!e||t.length===0||r.length===0||r[0]!==t||r.some(s=>s.length===0)?null:{bootstrapOk:!0,stunProbeFailed:!0,probed:t,probedAll:[...r]}}var z=class extends Error{constructor(e){super(e),this.name="LeafError"}},yt=class extends z{constructor(t){super(`wire: ${t}`);this.detail=t;this.name="WireError"}detail;kind="wire"},_e=class extends z{constructor(t){super(`session: ${t}`);this.detail=t;this.name="SessionError"}detail;kind="session"},gt=class extends z{constructor(t){super(`control plane: ${t}`);this.detail=t;this.name="ControlPlaneError"}detail;kind="control-plane"},be=class extends z{constructor(t){super(`identity: ${t}`);this.detail=t;this.name="IdentityError"}detail;kind="identity"},mt=class extends z{constructor(t,r){super(`ice configuration: the iceServers entry ${t} names this connection's peer RTC endpoint ${r}; a peer cannot be its own STUN server. Omit iceServers to use the STUN endpoint the anchor announces (the stun_addr field of GET /rtc/anchor), or name a STUN server that is not this peer`);this.entry=t;this.peerRtcAddr=r;this.name="IceServerConflictError"}entry;peerRtcAddr;kind="ice-server-conflict"},bt=class extends z{constructor(t,r=null){super(r===null?`not the leader: this tab holds generation ${t}`:`not the leader: this tab holds generation ${t}, the leader holds ${r}`);this.presented=t;this.current=r;this.name="NotLeaderError"}presented;current;kind="not-leader"},ce=class extends z{constructor(t){super(`rtc: ${ri(t)}`);this.failure=t;this.name="RtcError",this.kind=ti[t.type]}failure;kind},St=class extends z{constructor(t){super(`rpc: ${si(t)}`);this.failure=t;this.name="RpcError",this.kind=ni[t.type]}failure;kind},Ue=class extends z{constructor(t,r){super(t);this.cause=r;this.name="UnknownLeafError"}cause;kind="unknown"},Z=class extends z{},he=class extends Z{constructor(t,r){super(r??`org:admission_denied:${Zs[t]}`);this.coarse=t;this.name="OrgAdmissionDeniedError"}coarse;kind="org-admission-denied"},Pe=class extends he{kind="org-revoked";constructor(e="org:admission_denied:denied"){super("denied",e),this.name="OrgRevokedError"}},Ie=class extends Z{kind="org-timeout";constructor(e="org:rpc:timeout"){super(e),this.name="OrgTimeoutError"}},D=class extends Z{kind="org-cancelled";constructor(e="org:rpc:cancelled"){super(e),this.name="OrgCancelledError"}},ee=class extends Z{constructor(t,r="org:rpc:leader_lost"){super(r);this.generation=t;this.name="OrgLeaderLostError"}generation;kind="org-leader-lost"},Ce=class extends Z{kind="org-session-lost";constructor(e="org:rpc:session_lost"){super(e),this.name="OrgSessionLostError"}},Ve=class extends Z{constructor(t,r="org:rpc:indeterminate"){super(r);this.deadlineMs=t;this.name="OrgIndeterminateError"}deadlineMs;kind="org-indeterminate"},Ke=class extends Z{constructor(t,r="org:rpc:refused"){super(r);this.status=t;this.name="OrgRefusedError"}status;kind="org-refused"},Re=class extends Z{kind="org-internal";constructor(e="org:rpc:internal"){super(e),this.name="OrgInternalError"}},Be=class extends Z{kind="org-malformed";constructor(e="org:rpc:malformed"){super(e),this.name="OrgMalformedError"}},Ot="org: the response sink is closed: the call was retired",Gs="org: the upload sink is closed: the call was retired",Ys="org: the response sink is closed: the call's byte budget refused the item and retired the call",Qs="org: the upload sink is closed: the call's byte budget refused the item and retired the call",er="org:",Zs={denied:"denied","not-supported":"not_supported",unavailable:"unavailable"};function wt(n){let e=(n??"").trim();return e==="unavailable"?"unavailable":e==="not_supported"||e==="not-supported"?"not-supported":e==="\0"||e==="0"?"denied":e===""||e==="1"?"not-supported":e===""||e==="2"?"unavailable":"denied"}function ei(n){switch(n){case"timeout":return new Ie;case"revoked":return new Pe;case"session-lost":return new Ce;case"leader-lost":return new ee("");case"cancelled":case"node-closed":case"replaced":return new D;case"resource-exhausted":return new he("unavailable")}}function en(n){let e=n.message;switch(n.kind){case"admission-denied":return new he(wt(n.coarse),e);case"revoked":return e===void 0?new Pe:new Pe(e);case"timeout":return e===void 0?new Ie:new Ie(e);case"cancelled":return e===void 0?new D:new D(e);case"leader-lost":return new ee(n.generation??"",e);case"session-lost":return e===void 0?new Ce:new Ce(e);case"indeterminate":return new Ve(n.deadlineMs??0,e);case"refused":return new Ke(n.status??0,e);case"malformed":return e===void 0?new Be:new Be(e);case"internal":return e===void 0?new Re:new Re(e);default:return new Re(`org:rpc:internal: unrecognized terminal kind ${JSON.stringify(n.kind)}`+(e===void 0?"":`: ${e}`))}}function xt(n){switch(n){case"timeout":case"cancelled":case"revoked":case"session-lost":case"leader-lost":case"node-closed":case"replaced":case"resource-exhausted":return n;default:return"replaced"}}function tr(n){if(/^org: .+ is closed: the call was retired$/.test(n))return new D(n);if(/^org: .+ is closed: the call's byte budget refused the item and retired the call$/.test(n))return new he("unavailable",n);if(n.startsWith(er)){let t=n.slice(er.length),r=t.indexOf(":");if(r<=0)return null;let s=t.slice(0,r),i=t.slice(r+1),o=i.indexOf(":"),a=o===-1?i:i.slice(0,o);if(a.length===0)return null;if(s==="admission_denied")return new he(wt(a),n);if(s!=="rpc")return null;switch(a){case"revoked":return new Pe(n);case"timeout":return new Ie(n);case"cancelled":return new D(n);case"leader_lost":case"leader-lost":return new ee("",n);case"session_lost":case"session-lost":return new Ce(n);case"indeterminate":return new Ve(0,n);case"refused":case"server_error":case"capability_denied":return new Ke(0,n);case"malformed":case"codec_encode":case"codec_decode":return new Be(n);case"internal":case"no_route":case"transport":return new Re(n);default:return null}}let e=/^rpc: refused \(9\): ([\s\S]*)$/.exec(n);return e?new he(wt(e[1]),n):null}var ti={iceTimeout:"ice-timeout",udpBlocked:"udp-blocked",channelClosed:"channel-closed",unsupported:"rtc-unsupported"},ni={refused:"rpc-refused",timeout:"rpc-timeout",sessionLost:"session-lost",leaderLost:"leader-lost",indeterminate:"rpc-indeterminate",malformed:"rpc-malformed"},nr="ICE did not connect inside the deadline (this does not establish that UDP is blocked)";function ri(n){switch(n.type){case"iceTimeout":return nr;case"udpBlocked":return`no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to ${n.evidence.probedAll.join(", ")} went unanswered`;case"channelClosed":return`the DataChannel closed: ${n.detail}`;case"unsupported":return`this browser refused the attempt: ${n.detail}`}}function si(n){switch(n.type){case"refused":return`refused (${n.status}): ${n.message}`;case"timeout":return"the call's deadline elapsed";case"sessionLost":return"the session carrying the call went away";case"leaderLost":return`the leader holding generation ${n.generation} was replaced`;case"indeterminate":return`the local deadline of ${n.deadlineMs}ms elapsed before the tab running the node answered; the remote operation may still have executed (it was not retried)`;case"malformed":return`the reply did not decode: ${n.detail}`}}function S(n){if(n instanceof z)return n;let e=ii(n);return rr(e)??new Ue(e,n)}function ii(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n!==null&&typeof n=="object"&&"message"in n){let e=n.message;if(typeof e=="string")return e}return String(n)}function rr(n){let e=tr(n);if(e!==null)return e;let t=le(n,"rtc: ");if(t!==null){let d=sr(t);return d===null?null:new ce(d)}let r=le(n,"rpc: ");if(r!==null){let d=ir(r);return d===null?null:new St(d)}let s=le(n,"wire: ");if(s!==null)return new yt(s);let i=le(n,"session: ");if(i!==null)return new _e(i);let o=le(n,"control plane: ");if(o!==null)return new gt(o);let a=le(n,"identity: ");if(a!==null)return new be(a);let l=le(n,"ice configuration: ");if(l!==null){let d=/^the iceServers entry (.+?) names this connection's peer RTC endpoint (.+?); a peer cannot be its own STUN server\./.exec(l);if(d)return new mt(d[1]??"",d[2]??"")}let c=/^not the leader: this tab holds generation (\d+)(?:, the leader holds (\d+))?$/.exec(n);if(c){let d=Number(c[1]),u=c[2]===void 0?null:Number(c[2]);return new bt(d,u)}return null}function sr(n){if(n===nr)return{type:"iceTimeout"};let e=/^no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to (.+) went unanswered$/.exec(n);if(e){let s=(e[1]??"").split(", "),i=s[0]??"",o=vt(!0,!0,i,s);return o===null?null:{type:"udpBlocked",evidence:o}}let t=le(n,"the DataChannel closed: ");if(t!==null)return{type:"channelClosed",detail:t};let r=le(n,"this browser refused the attempt: ");return r!==null?{type:"unsupported",detail:r}:null}function ir(n){let e=/^refused \((\d+)\): ([\s\S]*)$/.exec(n);if(e)return{type:"refused",status:Number(e[1]),message:e[2]??""};if(n==="the call's deadline elapsed")return{type:"timeout"};if(n==="the session carrying the call went away")return{type:"sessionLost"};let t=/^the leader holding generation (\d+) was replaced$/.exec(n);if(t)return{type:"leaderLost",generation:Number(t[1])};let r=/^the local deadline of (\d+)ms elapsed before the tab running the node answered; the remote operation may still have executed \(it was not retried\)$/.exec(n);if(r)return{type:"indeterminate",deadlineMs:Number(r[1])};let s=le(n,"the reply did not decode: ");return s!==null?{type:"malformed",detail:s}:null}function oi(n){return n instanceof ce&&n.failure.type==="udpBlocked"}function le(n,e){return n.startsWith(e)?n.slice(e.length):null}var ar=["node_id","peer_node","channel_hash","origin_hash","stream_id","dialog","not_after","call_id","seq","generation","incarnation","version","from","to"];function Se(n){let e;try{e=Et(n)}catch{return{type:"unknown",tag:null,raw:n}}if(e===null||typeof e!="object")return{type:"unknown",tag:null,raw:e};let t=e,r=typeof t.type=="string"?t.type:null;switch(r){case"connected":return{type:"connected",nodeIdHex:U(t,"node_id_hex"),peerNode:U(t,"peer_node"),rtcAddr:rn(t,"rtc_addr"),rtcAddrs:ai(t)};case"disconnected":return{type:"disconnected",reason:U(t,"reason")};case"channel_message":return{type:"channel_message",channelHash:U(t,"channel_hash"),originHash:U(t,"origin_hash"),payload:nn(t,"payload")};case"stream_data":return{type:"stream_data",peerNode:U(t,"peer_node"),incarnation:U(t,"incarnation"),streamId:U(t,"stream_id"),seq:tn(t,"seq"),payload:nn(t,"payload")};case"announcement":return{type:"announcement",nodeId:U(t,"node_id"),capabilities:li(t,"capabilities"),rtcAddr:rn(t,"rtc_addr"),verified:t.verified===!0};case"signal":return{type:"signal",from:U(t,"from"),to:U(t,"to"),dialog:U(t,"dialog"),kind:U(t,"kind"),payload:nn(t,"payload"),notAfter:U(t,"not_after")};case"rpc_response":return{type:"rpc_response",callId:U(t,"call_id"),status:tn(t,"status")};case"dropped":return{type:"dropped",reason:U(t,"reason"),subprotocol:tn(t,"subprotocol")};case"rtc_failure":return{type:"rtc_failure",error:S(U(t,"error"))};default:return{type:"unknown",tag:r,raw:t}}}var je=class{typed=new Map;any=new Set;queues=new Set;on(e,t){let r=this.typed.get(e)??new Set;this.typed.set(e,r);let s=t;return r.add(s),()=>{r.delete(s)}}onAny(e){return this.any.add(e),()=>{this.any.delete(e)}}events(){let e=new Ae(()=>this.queues.delete(e));return this.queues.add(e),e}deliver(e,t){this.dispatch(t?t(e):Se(e))}dispatch(e){for(let t of this.typed.get(e.type)??[])or(t,e);for(let t of this.any)or(t,e);for(let t of this.queues)t.push(e)}close(){this.typed.clear(),this.any.clear();for(let e of[...this.queues])e.end();this.queues.clear()}};function or(n,e){try{n(e)}catch(t){console.error("[@net-mesh/browser] event listener threw",t)}}function Et(n){let e=ar.join("|"),t=n.replace(new RegExp(`("(?:${e})"\\s*:\\s*)(\\d+)`,"g"),'$1"$2"');return JSON.parse(t)}function U(n,e){let t=n[e];return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):""}function ai(n){let e=n.rtc_addrs;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.length>0);let t=rn(n,"rtc_addr");return t===null?[]:[t]}function rn(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:null}function tn(n,e){let t=n[e];if(typeof t=="number")return t;if(typeof t=="string"){let r=Number(t);return Number.isFinite(r)?r:0}return 0}function li(n,e){let t=n[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function nn(n,e){let t=n[e];return t instanceof Uint8Array?t:typeof t!="string"?new Uint8Array(0):lr(t)}function lr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function sn(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var He=class{live=new Set;add(e){this.live.add(e)}delete(e){this.live.delete(e)}retireAll(e){let t=[...this.live];this.live.clear();let r=[];for(let s of t)try{s.retire(e)}catch(i){r.push(i)}return r}},we=class{constructor(e,t,r){this.inner=e;this.onCancel=t;this.onDone=r}inner;onCancel;onDone;terminal=null;failure=null;handleDropped=!1;waiters=[];next(){if(this.failure!==null)return Promise.reject(this.failure);if(this.terminal!==null)return Promise.resolve(this.terminal);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={resolve:t,reject:r};return this.waiters.push(s),this.inner.next().then(i=>{$e(this.waiters,s);let o=ci(i);o.done&&this.complete(o),t(o)},i=>{$e(this.waiters,s);let o=S(i);this.fail(o),r(o)}),e}cancel(){this.retire(new D)}retire(e){this.terminal!==null||this.failure!==null||(this.dropHandle(),this.complete({done:!0,error:e}))}[Symbol.asyncIterator](){let e=!1;return{next:async()=>{if(e)return{done:!0,value:void 0};let t=await this.next();if(t.error!==void 0)throw t.error;return t.value===void 0?(e=!0,{done:!0,value:void 0}):(t.done&&(e=!0),{done:!1,value:t.value})},return:async()=>(e=!0,this.cancel(),{done:!0,value:void 0})}}complete(e){if(this.terminal!==null)return;this.terminal=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.resolve(e)}fail(e){if(this.terminal!==null||this.failure!==null)return;this.failure=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.onCancel()}catch{}}}},Le=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;failure=null;handleDropped=!1;waiters=[];async send(e){if(this.failure!==null)throw this.failure;try{await this.inner.send(e)}catch(t){throw S(t)}}finish(){if(this.failure!==null)return Promise.reject(this.failure);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={reject:r};return this.waiters.push(s),this.inner.finish().then(i=>{$e(this.waiters,s),this.onDone?.(),t(i)},i=>{$e(this.waiters,s),this.onDone?.(),r(S(i))}),e}cancel(){this.retire(new D)}retire(e){if(this.failure!==null)return;if(this.failure=e,!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}},Te=class{constructor(e,t){this.inner=e;this.onDone=t;this.stream=new we(e.stream(),()=>this.dropHandle(),()=>this.onDone?.()),this.sink={send:async r=>{if(this.failure!==null)throw this.failure;try{await this.inner.send(r)}catch(s){throw S(s)}},finishSending:async()=>{if(this.failure!==null)throw this.failure;try{await this.inner.finish_sending()}catch(r){throw S(r)}},cancel:()=>{this.retire(new D)}}}inner;onDone;handleDropped=!1;failure=null;sink;stream;retire(e){this.failure??=e,this.dropHandle(),this.stream.retire(e),this.onDone?.()}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}}},Xe=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.verdict??=xt(t),this.verdict),()=>(this.verdict??="replaced",this.verdict))}inner;retired;verdict=null;async send(e){if(this.verdict!==null)throw new D(Ot);try{await this.inner.send(e)}catch(t){throw S(t)}}async close(){if(this.verdict!==null)throw new D(Ot);try{await this.inner.close()}catch(e){throw S(e)}}},ze=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.settle(xt(t)),this.verdict),()=>(this.settle("replaced"),this.verdict))}inner;retired;verdict=null;waiters=[];next(){if(this.verdict!==null)return Promise.resolve({done:!0});let{promise:e,resolve:t}=Promise.withResolvers();return this.waiters.push(t),this.inner.next().then(r=>{$e(this.waiters,t),t(di(r))},()=>{$e(this.waiters,t),t({done:!0})}),e}[Symbol.asyncIterator](){return{next:async()=>{let e=await this.next();return e.done||e.value===void 0?{done:!0,value:void 0}:{done:!1,value:e.value}},return:async()=>({done:!0,value:void 0})}}settle(e){if(this.verdict!==null)return;this.verdict=e;let t=[...this.waiters];this.waiters.length=0;for(let r of t)r({done:!0})}},Q=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;closed=!1;get service(){return this.inner.service()}close(){this.closed||(this.closed=!0,this.onDone?.(),this.inner.close())}retire(e){this.close()}};function re(n){return{credentials:{membership:n.credentials.membership,dispatcher:n.credentials.dispatcher,...n.credentials.capabilityGrant===void 0?{}:{capabilityGrant:n.credentials.capabilityGrant},actingOrg:n.credentials.actingOrg,providerOwnerOrg:n.credentials.providerOwnerOrg,provider:n.credentials.provider,...n.credentials.proofTtlSecs===void 0?{}:{proofTtlSecs:n.credentials.proofTtlSecs}},...n.deadlineMs===void 0?{}:{deadlineMs:n.deadlineMs},...n.streamWindowInitial===void 0?{}:{streamWindowInitial:n.streamWindowInitial},...n.requestWindowInitial===void 0?{}:{requestWindowInitial:n.requestWindowInitial}}}function se(n){return{ownerOrg:n.ownerOrg}}function Ge(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new Ue("the caller attribution is not an OrgCaller object");let t=e;return{entity:String(t.entity??""),actingOrg:String(t.actingOrg??""),providerOrg:String(t.providerOrg??""),provider:String(t.provider??""),capability:String(t.capability??""),isSameOrg:t.isSameOrg===!0}}function Ye(n){return async(e,t)=>await n(Ge(e),t)}function Qe(n){return async(e,t,r)=>{await n(Ge(e),t,new Xe(r))}}function Ze(n){return async(e,t)=>await n(Ge(e),new ze(t))}function et(n){return async(e,t,r)=>{await n(Ge(e),new ze(t),new Xe(r))}}function $e(n,e){let t=n.indexOf(e);t>=0&&n.splice(t,1)}function ci(n){return n.done?n.error!==void 0?{done:!0,error:en(n.error)}:n.value===void 0?{done:!0}:{done:!0,value:n.value}:{done:!1,value:n.value}}function di(n){return n.done?{done:!0}:{done:!1,value:n.value}}var kt=class extends _e{constructor(e){super(e),this.name="StreamIdentityError"}},De=class{constructor(e,t,r="required"){this.inner=e;this.onClosed=t;if(this.wireId=cr(()=>e.stream_id_hex()),this.peerId=cr(()=>e.peer_node_hex()),r==="required"&&this.peerId===null)throw new kt("the stream did not report a readable peer, so its frames cannot be attributed");e.on_message(s=>this.receive(s))}inner;onClosed;queues=new Set;listeners=new Set;pending=[];closed=!1;wireId;peerId;get peerNode(){return this.inner.peer_node_hex()}get reliability(){return this.inner.is_reliable()?"reliable":"fireAndForget"}get streamId(){return this.inner.stream_id_hex()}async send(e){if(this.closed)throw new _e("the stream is closed");try{await this.inner.send(e)}catch(t){throw S(t)}}onMessage(e){this.listeners.add(e);let t=this.pending.splice(0,this.pending.length);for(let r of t)e(r);return()=>{this.listeners.delete(e)}}[Symbol.asyncIterator](){let e=new Ae(()=>this.queues.delete(e));this.queues.add(e);let t=this.pending.splice(0,this.pending.length);for(let r of t)e.push(r);return this.closed&&e.end(),e}close(){if(!this.closed){this.closed=!0;for(let e of[...this.queues])e.end();this.queues.clear(),this.listeners.clear(),this.onClosed?.(),this.inner.close()}}receive(e){let t=this.decode(e);if(!(t===null||this.closed)){if(this.queues.size===0&&this.listeners.size===0){this.pending.push(t);return}for(let r of this.listeners)try{r(t)}catch(s){console.error("[@net-mesh/browser] stream listener threw",s)}for(let r of this.queues)r.push(t)}}decode(e){if(e instanceof Uint8Array)return e;if(typeof e!="string")return console.error("[@net-mesh/browser] stream callback received",typeof e,"not the leaf event JSON"),null;let t=Se(e);return t.type!=="stream_data"||!/^\d+$/.test(t.streamId)||this.wireId!==null&&BigInt(t.streamId)!==this.wireId||this.peerId!==null&&(!/^\d+$/.test(t.peerNode)||BigInt(t.peerNode)!==this.peerId)?null:t.payload}};function cr(n){let e;try{e=n()}catch{return null}return e===void 0||!/^[0-9a-fA-F]{1,16}$/.test(e)?null:BigInt(`0x${e}`)}var on="no verified announcement for",dr="no live attempt with",ur="no verified offer from",pr="is not the live attempt",fr=50,hr=5e3;function ui(n){switch(n.type){case"direct":case"iceTimeout":case"udpBlocked":return!0;case"superseded":return n.liveDialog!==null;default:return!1}}var Me=class n{#e=new Map;#t=new Map;connect(e,t,r){let s=e.toLowerCase(),i=this.#e.get(s);if(i!==void 0)return i;let o=this.#t.get(s),a=(async()=>{if(o!==void 0){let c=await o.catch(()=>null);if(c!==null&&ui(c))return c}let l=await t();return l!=null?{type:"direct",peer:e,dialog:l}:r()})();return n.#r(this.#e,s,a)}accept(e,t){let r=e.toLowerCase(),s=this.#t.get(r);return s!==void 0?s:n.#r(this.#t,r,t())}static#r(e,t,r){e.set(t,r);let s=()=>{e.get(t)===r&&e.delete(t)};return r.then(s,s),r}};async function tt(n,e,t){let r;try{r=await e.offer(n)}catch(i){let o=S(i);if(o.message.includes(on))return{type:"noAnnouncement",peer:n,detail:o.message};throw o}let s=await an(n,r,i=>i.state==="open",e,t);return s.type!=="direct"?s:At(n,r,e)}async function nt(n,e,t){let r=null,s=Date.now()+hr;for(;;)try{r=await e.acceptOffer(n);break}catch(i){let o=S(i);if(o.message.includes(on))return{type:"noAnnouncement",peer:n,detail:o.message};if(!o.message.includes(ur)||Date.now()>=s)throw o;await gr()}return an(n,r,i=>i.direct,e,t)}async function At(n,e,t){let r;try{r=await t.handshake(n,e)}catch(s){let i=yr(s,n,e);return i!==null?i:{type:"handshakeFailed",peer:n,dialog:e,detail:S(s).message}}return r!==e?{type:"superseded",peer:n,dialog:e,liveDialog:r}:{type:"direct",peer:n,dialog:e}}async function an(n,e,t,r,s){for(;;){let i;try{i=s(await r.candidate(n,e))}catch(o){let a=yr(o,n,e);if(a!==null)return a;throw S(o)}if(i.dialog!==e)return{type:"superseded",peer:n,dialog:e,liveDialog:i.dialog};if(t(i))return{type:"direct",peer:n,dialog:e};if(i.state==="iceTimeout")return{type:"iceTimeout",peer:n,dialog:e};if(i.state==="udpBlocked")return{type:"udpBlocked",peer:n,dialog:e};if(i.state==="failed")return{type:"handshakeFailed",peer:n,dialog:e,detail:i.candidateError??"the attempt reached its terminal transition without installing a session"};await gr()}}function yr(n,e,t){let{message:r}=S(n);return r.includes(pr)?{type:"superseded",peer:e,dialog:t,liveDialog:pi(r)}:r.includes(dr)?{type:"superseded",peer:e,dialog:t,liveDialog:null}:null}function pi(n){return/\(dialog ([0-9a-f]{16}) is\)/.exec(n)?.[1]??null}async function gr(){let n=Promise.withResolvers();setTimeout(n.resolve,fr),await n.promise}function cn(n){let e=n.trim().split(/\s+/);return e.some((t,r)=>t==="typ"&&e[r+1]==="srflx")}function dn(n){return"candidate"in n?cn(n.candidate):"error"in n?n.error<wr:!1}function br(n){if(n.some(dn))return"answered";let e=n.some(r=>"candidate"in r);return n.some(r=>"ice"in r&&r.ice==="failed")&&!e?"notRun":"unanswered"}function fi(n){return br(n)==="answered"}function Sr(n){let{bootstrapOk:e,stunProbe:t,probed:r}=n;return r===null?{type:"iceTimeout"}:Rt({bootstrapOk:e,probes:[{probed:r,stunProbe:t}]})}function Rt(n){let{bootstrapOk:e,probes:t}=n;if(t.length===0||t.some(i=>i.stunProbe.type!=="unanswered"))return{type:"iceTimeout"};let r=t.map(i=>i.probed),s=vt(e,!0,r[0]??"",r);return s===null?{type:"iceTimeout"}:{type:"udpBlocked",evidence:s}}function hi(n){return new ce(Sr(n))}var yi=2500,wr=700,ln=3478;async function vr(n,e={}){let t=Or(n);if(t===null)return{type:"notRun",reason:`not an address: ${n}`};let r=e.peerConnectionFactory??mi();if(r===null)return{type:"unsupported",detail:"RTCPeerConnection is not available in this context"};let s=e.timeoutMs??yi,{promise:i,resolve:o}=Promise.withResolvers(),a;try{a=r({iceServers:[{urls:t}],iceCandidatePoolSize:0})}catch(f){return{type:"unsupported",detail:String(f)}}let l=!1,c=f=>{l||(l=!0,o(f))},d=null,u=setTimeout(()=>c({type:"unanswered",detail:d??"no answer inside the probe deadline"}),s),p=()=>{c({type:"unanswered",detail:d??"gathering completed with no reflexive candidate"})},y=!1;a.oniceconnectionstatechange=()=>{a.iceConnectionState==="failed"&&!y&&c({type:"notRun",reason:"the engine failed the probe connection before gathering any candidate"})},a.onicecandidate=f=>{let b=f.candidate;if(b===null){p();return}y=!0;let A=xr(b);A!==null&&c({type:"reflexive",address:A})},a.onicecandidateerror=f=>{let b=f.errorCode,A=`${b}: ${f.errorText} (${f.url})`;if(dn({error:b})){c({type:"stunError",code:b,detail:A});return}d=A},a.onicegatheringstatechange=()=>{a.iceGatheringState==="complete"&&p()};try{a.createDataChannel("net-udp-probe"),await a.setLocalDescription(await a.createOffer())}catch(f){c({type:"unsupported",detail:String(f)})}try{return await i}finally{clearTimeout(u),a.onicecandidate=null,a.onicecandidateerror=null,a.oniceconnectionstatechange=null,a.onicegatheringstatechange=null,a.close()}}async function un(n,e={}){return Promise.all(n.map(async t=>({probed:t,stunProbe:await vr(t,e)})))}var gi=3e3;async function pn(n,e={}){let t=e.fetchImpl??globalThis.fetch;if(typeof t!="function")return!1;try{return await t(n,{method:"GET",mode:"no-cors",cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(e.timeoutMs??gi)}),!0}catch{return!1}}function Or(n){let e=n.trim();if(e.length===0)return null;if(e.startsWith("stun:")||e.startsWith("stuns:"))return e;let t=/^\[([0-9a-fA-F:.]+)\](?::(\d+))?$/.exec(e);if(t)return`stun:[${t[1]??""}]:${t[2]??ln}`;if((e.match(/:/g)?.length??0)>1)return`stun:[${e}]:${ln}`;let r=/^([A-Za-z0-9._-]+)(?::(\d+))?$/.exec(e);return r===null?null:`stun:${r[1]??""}:${r[2]??ln}`}function xr(n){return n.type==="srflx"?n.address??mr(n.candidate):n.type!==null?null:cn(n.candidate)?mr(n.candidate):null}function mr(n){let e=n.split(" "),t=e[4]??"",r=e[5]??"";return r.length>0?`${t}:${r}`:t}function mi(){return typeof RTCPeerConnection>"u"?null:n=>new RTCPeerConnection(n)}var fn=new Map;async function rt(n={}){if(n.wasm)return n.wasm;let e=n.wasmModule??new URL("./net_leaf.js",import.meta.url).href,t=`${e}|${String(n.wasmUrl??"")}`,r=fn.get(t);if(r)return r;let s=bi(e,n.wasmUrl);fn.set(t,s);try{return await s}catch(i){throw fn.delete(t),i}}async function bi(n,e){let t=await import(n),r=Si(t,n);return r.default&&await r.default(e===void 0?void 0:{module_or_path:e}),r}function Si(n,e){if(n===null||typeof n!="object"||!("LeafNode"in n))throw new Error(`${e} is not a net-mesh-leaf module: no LeafNode export`);let t=n.LeafNode;if(typeof t!="function"||!("connect"in t))throw new Error(`${e} exports a LeafNode without a static connect()`);if(typeof t.connect!="function")throw new Error(`${e} exports a LeafNode whose connect is not callable`);return n}function ve(n,e){if(typeof n=="string")return n;let t=typeof n=="object"&&n!==null?Object.prototype.toString.call(n):String(n);throw new TypeError(`${t} is not a ${e} id: a ${e} id crosses this boundary as 16 hex digits as a STRING \u2014 the spelling this boundary hands out; a ${typeof n} is refused rather than coerced, because a number cannot carry a u64 id`)}function kr(n){if(!/^\d+$/.test(n))throw new TypeError(`a decimal node id is digits only, got ${JSON.stringify(n)}`);let e=BigInt(n);if(e>0xffffffffffffffffn)throw new TypeError(`${n} does not fit in a u64 node id`);return e.toString(16).padStart(16,"0")}var Pt=class{constructor(e,t,r,s){this.inner=e;this.bootstrapUrl=t;this.failureTyping=r;this.nodeId=e.node_id_hex(),this.anchorRtcAddr=s,e.on_event(i=>this.ingest(i))}inner;bootstrapUrl;failureTyping;hub=new je;nodeId;closed=!1;streams=new Set;attempts=new Me;orgHandles=new He;anchorRtcAddr;anchorRtcAddrs=[];bootstrapObserved=!1;nodeIdHex(){return this.nodeId}anchorIdHex(){return this.inner.anchor_id_hex()}originHashHex(){return this.inner.origin_hash_hex()}async enroll(){try{await this.inner.enroll()}catch(e){throw S(e)}}isEnrolled(){return this.inner.is_enrolled()}async call(e,t,r){try{return await this.inner.call(e,t,r)}catch(s){throw S(s)}}async subscribe(e){try{await this.inner.subscribe(e)}catch(t){throw S(t)}}async publish(e,t){try{await this.inner.publish(e,t)}catch(r){throw S(r)}}openStream(e){let t;try{t=this.inner.open_stream(e)}catch(s){throw S(s)}let r=new De(t,()=>this.streams.delete(r));return this.streams.add(r),r}async callOrg(e,t,r){try{return await this.inner.call_org(e,t,re(r))}catch(s){throw S(s)}}async callOrgStreaming(e,t,r){try{let s=await this.inner.call_org_streaming(e,t,re(r)),i=new we(s,()=>s.cancel(),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(s){throw S(s)}}async callOrgClientStream(e,t){try{let r=await this.inner.call_org_client_stream(e,re(t)),s=new Le(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}async callOrgDuplex(e,t){try{let r=await this.inner.call_org_duplex(e,re(t)),s=new Te(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}serveOrg(e,t,r,s){try{let i=new Q(this.inner.serve_org(e,t,Ye(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new Q(this.inner.serve_org_streaming(e,t,Qe(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new Q(this.inner.serve_org_client_stream(e,t,Ze(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new Q(this.inner.serve_org_duplex(e,t,et(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}async signal(e,t,r,s){try{await this.inner.signal(ve(e,"peer"),ve(t,"dialog"),r,s)}catch(i){throw S(i)}}async connectPeer(e){let t;try{t=ve(e,"peer")}catch(r){throw S(r)}return this.attempts.connect(e,()=>{try{return this.inner.peer_direct_dialog(t)}catch(r){throw S(r)}},()=>tt(e,this.peerPrimitives(),Ne))}peerPrimitives(){return{offer:e=>this.inner.peer_offer(e),acceptOffer:e=>this.inner.peer_accept_offer(e),candidate:(e,t)=>this.inner.peer_candidate_in(e,t),handshake:(e,t)=>this.inner.peer_handshake_in(e,t)}}async handshakePeer(e,t){return At(e,t,this.peerPrimitives())}async acceptPeer(e){return this.attempts.accept(e,()=>nt(e,this.peerPrimitives(),Ne))}async peerAttempt(e){try{return Ne(await this.inner.peer_candidate(e))}catch(t){throw S(t)}}counters(){return Ct(this.inner.counters_json())}rtcStats(){return Ar(this.inner.rtc_stats_json())}enableNetworkRetry(){try{this.inner.arm_network_retry()}catch(e){throw S(e)}}retryReport(){return Rr(this.inner.retry_report())}async announce(e){try{await this.inner.announce([...e])}catch(t){throw S(t)}}async query(e){let t;try{t=await this.inner.query(e)}catch(r){throw S(r)}return jt(t)}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}events(){return this.hub.events()}async refineIceFailure(e){return hn(e,{bootstrapUrl:this.bootstrapUrl,bootstrapObserved:this.bootstrapObserved,anchorRtcAddr:this.anchorRtcAddr,anchorRtcAddrs:this.anchorRtcAddrs,failureTyping:this.failureTyping})}close(){if(this.closed)return;this.closed=!0;let e=[];for(let r of this.orgHandles.retireAll(new D("org:rpc:cancelled: the node is closed")))e.push(S(r));let t=[...this.streams];this.streams.clear();for(let r of t)try{r.close()}catch(s){e.push(S(s))}try{this.hub.close()}catch(r){e.push(S(r))}try{this.inner.close()}catch(r){e.push(S(r))}if(e.length>0)throw new AggregateError(e,`close: ${e.length} of this node's teardown steps failed`)}ingest(e){let t=Se(e);t.type==="connected"&&(this.bootstrapObserved=!0,t.rtcAddr!==null&&(this.anchorRtcAddr=t.rtcAddr),t.rtcAddrs.length>0&&(this.anchorRtcAddrs=t.rtcAddrs)),this.hub.dispatch(t)}};async function wi(n){let e=It(n),t=n.failureTyping??{},r=await rt(n);try{let s=await r.LeafNode.connect(e);return new Pt(s,n.bootstrapUrl??null,t,n.anchorRtcAddr??null)}catch(s){throw await hn(S(s),{bootstrapUrl:n.bootstrapUrl??null,bootstrapObserved:!1,anchorRtcAddr:n.anchorRtcAddr??null,failureTyping:t})}}function It(n){return{credentialB64:xi(n),origin:n.origin??Ei(),...n.bootstrapUrl===void 0?{}:{bootstrapUrl:n.bootstrapUrl},...n.iceServers?{iceServers:n.iceServers}:{},...vi(n)}}function Ct(n){let e=JSON.parse(n);if(e===null||typeof e!="object")return{};let t={};for(let[r,s]of Object.entries(e))t[r]=typeof s=="string"?s:String(s);return t}function Ne(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`peer_candidate did not answer an object: ${n}`);let t=e,r=t.state;if(r!=="gathering"&&r!=="open"&&r!=="iceTimeout"&&r!=="udpBlocked"&&r!=="failed")throw new TypeError(`peer_candidate answered an unknown state: ${String(r)}`);let s=t.candidateError;return{dialog:String(t.dialog??""),state:r,sent:Number(t.sent??0),applied:Number(t.applied??0),answered:t.answered===!0,direct:t.direct===!0,remainingMs:String(t.remainingMs??"0"),candidateError:typeof s=="string"?s:null}}function Ar(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`rtc_stats_json did not answer an object: ${n}`);let t={},r={};for(let[s,i]of Object.entries(e)){if(s==="not_applicable"){if(i===null||typeof i!="object")continue;for(let[o,a]of Object.entries(i))r[o]=String(a);continue}t[s]=typeof i=="string"?i:String(i)}return{counters:t,notApplicable:r}}function Rr(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`retry_report did not answer an object: ${n}`);let t=e;return{armed:t.armed===!0,online:String(t.online??"0"),iceFailed:String(t.iceFailed??"0"),triggers:String(t.triggers??"0"),started:String(t.started??"0"),coalesced:String(t.coalesced??"0"),notEligible:String(t.notEligible??"0"),openEpisodes:Number(t.openEpisodes??0),owned:Number(t.owned??0),last:typeof t.last=="string"?t.last:null}}async function hn(n,e){if(!(n instanceof ce)||n.failure.type!=="iceTimeout"||e.failureTyping.probeOnIceTimeout===!1)return n;let t=e.anchorRtcAddrs!==void 0&&e.anchorRtcAddrs.length>0?e.anchorRtcAddrs:e.anchorRtcAddr!==null?[e.anchorRtcAddr]:[];if(t.length===0)return n;let r=await un(t,e.failureTyping.stun);if(r.some(i=>i.stunProbe.type!=="unanswered"))return n;let s=e.bootstrapObserved||e.bootstrapUrl!==null&&await pn(e.bootstrapUrl,e.failureTyping.bootstrap);return new ce(Rt({bootstrapOk:s,probes:r}))}function jt(n){let e=Et(n);if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s={...r},i=s.capabilities,o=Oi(s.node_id);t.push({nodeId:o,peerIdHex:kr(o),entityId:_t(s.entity_id),capabilities:Array.isArray(i)?i.filter(a=>typeof a=="string"):[],rtcAddr:_t(s.rtc_addr),noisePubkey:_t(s.noise_pubkey),version:_t(s.version)})}return t}var Er=/^[0-9a-fA-F]{64}$/;function vi(n){let{entitySecretHex:e,noiseSecretHex:t}=n;if(e===void 0){if(t!==void 0)throw new be("noiseSecretHex was supplied without entitySecretHex: the leaf would generate the entity half, so the identity would not be the one you meant to inject");return{}}if(!Er.test(e))throw new be(`entitySecretHex must be 32 bytes of hex (64 hex digits), got ${e.length} characters`);if(t===void 0)return{entitySecretHex:e};if(!Er.test(t))throw new be(`noiseSecretHex must be 32 bytes of hex (64 hex digits), got ${t.length} characters`);return{entitySecretHex:e,noiseSecretHex:t}}function Oi(n){return typeof n=="string"?n:typeof n=="number"?String(n):""}function _t(n){return typeof n=="string"?n.length>0?n:null:typeof n=="number"?String(n):null}function xi(n){if(n.credentialB64!==void 0)return n.credentialB64;let e=n.credential;if(typeof e=="string")return e;if(e instanceof Uint8Array)return sn(e);throw new Error("connect() needs a credential: pass credentialB64 or credential")}function Ei(){let n=globalThis.location?.origin;if(typeof n=="string"&&n.length>0)return n;throw new Error("connect() needs an origin: there is no location.origin in this context")}function yn(n){let e=Se(n);return e.type!=="unknown"?e:ki(e)??e}function gn(n){switch(n.type){case"leader_changed":case"subscription_restored":case"leader_lost":case"generation_fenced":case"not_leader":case"promotion_failed":return!0;default:return!1}}function ki(n){let e=n.raw;if(e===null||typeof e!="object")return null;let t={...e};switch(n.tag){case"leader_changed":return{type:"leader_changed",generation:We(t.generation)};case"subscription_restored":return{type:"subscription_restored",channel:typeof t.channel=="string"?t.channel:""};case"leader_lost":{let r=Number(t.failed);return{type:"leader_lost",generation:We(t.generation),failed:Number.isFinite(r)?r:0}}case"generation_fenced":return{type:"generation_fenced",presented:We(t.presented),current:We(t.current)};case"not_leader":return{type:"not_leader",presented:We(t.presented),current:We(t.current)};case"promotion_failed":return{type:"promotion_failed",generation:We(t.generation),detail:typeof t.detail=="string"?t.detail:""};default:return null}}function We(n){return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):"0"}function mn(n){let e=n.MeshSession;if(!(e!==null&&(typeof e=="object"||typeof e=="function")&&"open"in e&&typeof e.open=="function"))throw new Error("this net-mesh-leaf bundle has no MeshSession: leader election and the follower proxy need a wasm build from Stage 5 slice 3 or later");return n}var Ht=class{constructor(e){this.inner=e;this.streamGeneration=e.generation(),e.on_event(t=>this.hub.deliver(t,yn)),this.hub.onAny(t=>{if(t.type==="leader_lost"||t.type==="not_leader"){this.orgHandles.retireAll(new ee(this.streamGeneration)),this.endStreams();return}let r=this.inner.generation();if(r===this.streamGeneration)return;let s=this.streamGeneration;this.streamGeneration=r,this.orgHandles.retireAll(new ee(s)),this.endStreams()})}inner;hub=new je;streams=new Set;attempts=new Me;streamGeneration;orgHandles=new He;closed=!1;role(){return this.inner.role()==="leader"?"leader":"follower"}generation(){return this.inner.generation()}nodeIdHex(){return this.inner.node_id_hex()??null}fingerprint(){return this.inner.fingerprint()}scope(){return this.inner.scope()}interruptionMs(){return this.inner.interruption_ms()??null}async call(e,t,r){return await this.guard(()=>this.inner.call(e,t,r))}async subscribe(e){await this.guard(()=>this.inner.subscribe(e))}async unsubscribe(e){await this.guard(()=>this.inner.unsubscribe(e))}async publish(e,t){await this.guard(()=>this.inner.publish(e,t))}async announce(e){await this.guard(()=>this.inner.announce([...e]))}async query(e){return jt(await this.guard(()=>this.inner.query(e)))}async counters(){return Ct(await this.guard(()=>this.inner.counters_json()))}async enroll(){await this.guard(()=>this.inner.enroll())}async isEnrolled(){return await this.guard(()=>this.inner.is_enrolled())}async signal(e,t,r,s){await this.guard(()=>this.inner.signal(ve(e,"peer"),ve(t,"dialog"),r,s))}async connectPeer(e){return this.attempts.connect(e,async()=>{try{return await this.inner.peer_direct_dialog(e)??void 0}catch{return}},()=>tt(e,this.peerPrimitives(),Ne))}async acceptPeer(e){return this.attempts.accept(e,()=>nt(e,this.peerPrimitives(),Ne))}peerPrimitives(){return{offer:e=>this.guard(()=>this.inner.peer_offer(e)),acceptOffer:e=>this.guard(()=>this.inner.peer_accept_offer(e)),candidate:(e,t)=>this.guard(()=>this.inner.peer_candidate(e,t)),handshake:(e,t)=>this.guard(()=>this.inner.peer_handshake(e,t))}}async openStream(e){let t=this.inner.generation(),r=new De(await this.guard(()=>this.inner.open_stream(e)));return this.closed||this.inner.generation()!==t?(r.close(),r):(this.streams.add(r),r)}async callOrg(e,t,r){return await this.guard(()=>this.inner.call_org(e,t,re(r)))}async callOrgStreaming(e,t,r){let s=this.inner.generation(),i;try{let o=await this.inner.call_org_streaming(e,t,re(r));i=new we(o,()=>o.cancel(),()=>this.orgHandles.delete(i))}catch(o){throw S(o)}return this.closed||this.inner.generation()!==s?(i.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ee(s)),i):(this.orgHandles.add(i),i)}async callOrgClientStream(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_client_stream(e,re(t));s=new Le(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ee(r)),s):(this.orgHandles.add(s),s)}async callOrgDuplex(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_duplex(e,re(t));s=new Te(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ee(r)),s):(this.orgHandles.add(s),s)}serveOrg(e,t,r,s){try{let i=new Q(this.inner.serve_org(e,t,Ye(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new Q(this.inner.serve_org_streaming(e,t,Qe(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new Q(this.inner.serve_org_client_stream(e,t,Ze(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new Q(this.inner.serve_org_duplex(e,t,et(r),se(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}onLifecycle(e){return this.hub.onAny(t=>{gn(t)&&e(t)})}events(){return this.hub.events()}close(){this.closed||(this.closed=!0,this.orgHandles.retireAll(new D("org:rpc:cancelled: the session is closed")),this.endStreams(),this.hub.close(),this.inner.close())}endStreams(){let e=[...this.streams];this.streams.clear();for(let t of e)t.close()}async guard(e){try{return await e()}catch(t){throw S(t)}}};async function Ai(n){let e=mn(await rt(n)),t={...It(n),...n.capabilities?{capabilities:[...n.capabilities]}:{},...n.subscriptions?{subscriptions:[...n.subscriptions]}:{},...n.dbName===void 0?{}:{dbName:n.dbName},...n.lockScope===void 0?{}:{lockScope:n.lockScope}};try{return new Ht(await e.MeshSession.open(t))}catch(r){throw S(r)}}var bn=["invalid-data","version-mismatch","forbidden","not-ready","capacity","timeout","aborted","indeterminate","owner-lost","closed","action-rejected","result-expired"],h=class extends Error{code;constructor(e,t,r){super(t,r),this.name="StoreError",this.code=e}};function st(n){return(n instanceof Error?n.message:String(n)).includes("stale stream handle")}var Lt=Object.freeze({$hidden:!0});function Tt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.keys(n).length===1&&n.$hidden===!0}function Ri(n){return e=>Tt(e)?Lt:n(e)}var _r=Object.freeze({"card-game":Object.freeze({"players.*.hand":"owner",deck:"nobody","deck.length":"everyone"})}),_i=/^(\*|[^.*]+)$/;function Oe(n){let e;if(n==="open")e={};else if(typeof n=="string"){let s=_r[n];if(s===void 0)throw new h("invalid-data",`unknown visibility preset '${n}'`);e={...s}}else if(typeof n=="object"&&n!==null){let{preset:s,...i}=n;if(e={},s!==void 0){let o=_r[s];if(o===void 0)throw new h("invalid-data",`unknown visibility preset '${String(s)}'`);Object.assign(e,o)}Object.assign(e,i)}else throw new h("invalid-data","visibility is a preset name or an object of path \u2192 rule");let t=[],r=!1;for(let[s,i]of Object.entries(e)){let o=s.split(".");if(s.length===0||!o.every(c=>_i.test(c)))throw new h("invalid-data",`visibility path '${s}' is not dot-separated keys and '*'`);let a=o.length>1&&o[o.length-1]==="length";if(!(i==="everyone"||i==="nobody"||i==="owner"||Array.isArray(i)&&i.length>0&&i.every(c=>typeof c=="string"&&c.length>0)))throw new h("invalid-data",`visibility rule for '${s}' must be 'everyone', 'nobody', 'owner' or a non-empty list of audiences`);if(i==="owner"){if(!o.includes("*"))throw new h("invalid-data",`'owner' needs a '*' in the path to name the owner: '${s}'`);r=!0}t.push(Object.freeze({path:s,segments:Object.freeze(o),rule:i,counts:a}))}return t.sort((s,i)=>s.segments.length-i.segments.length),Object.freeze({rules:Object.freeze(t),perPlayer:r})}function Pr(n,e,t){return n==="everyone"?!0:n==="nobody"||t===null?!1:n==="owner"?e[0]===t.peer:n.some(r=>t.audience.includes(r))}function Pi(n,e){let t=[],r=(s,i,o,a)=>{if(i===e.length){t.push({keys:[...o],captures:[...a],value:s});return}if(typeof s!="object"||s===null)return;let l=e[i];if(l==="*"){let c=Array.isArray(s)?s.map((d,u)=>[u,d]):Object.entries(s);for(let[d,u]of c)r(u,i+1,[...o,d],[...a,String(d)]);return}Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,l)||r(s[l],i+1,[...o,l],a)};return r(n,0,[],[]),t}var Sn=Symbol("drop");function Ii(n,e,t){let r=n;for(let s of e){let i=r.children.get(s);i===void 0&&(i={children:new Map},r.children.set(s,i)),r=i}r.value=t}function wn(n,e){if("value"in e)return e.value;if(e.children.size===0||typeof n!="object"||n===null)return n;if(Array.isArray(n)){let r=[];return n.forEach((s,i)=>{let o=e.children.get(i),a=o===void 0?s:wn(s,o);a!==Sn&&r.push(a)}),r}let t={};for(let[r,s]of Object.entries(n)){let i=e.children.get(r),o=i===void 0?s:wn(s,i);o!==Sn&&(t[r]=o)}return t}var Ir="\0";function xe(n,e,t){if(n.rules.length===0)return e;let r={children:new Map},s=new Set,i=!1;for(let o of n.rules){if(o.counts)continue;let a=n.rules.find(c=>c.counts&&c.segments.length===o.segments.length+1&&c.segments.slice(0,-1).every((d,u)=>d===o.segments[u])),l=o.segments[o.segments.length-1]==="*";for(let c of Pi(e,o.segments)){let d="",u=!1;for(let y=0;y<c.keys.length-1&&!u;y+=1)d=y===0?String(c.keys[0]):`${d}${Ir}${String(c.keys[y])}`,u=s.has(d);if(u||Pr(o.rule,c.captures,t))continue;let p=l?Sn:Lt;a!==void 0&&Array.isArray(c.value)&&Pr(a.rule,c.captures,t)&&(p=c.value.map(()=>Lt)),Ii(r,c.keys,p),s.add(c.keys.map(String).join(Ir)),i=!0}}return i?wn(e,r):e}function Cr(n,e,t){return n.visibility===void 0?e:xe(Oe(n.visibility),e,t)}function Ci(n,e,t,r){let s=Cr(n,e,t);for(let i of r){let o=s;for(let l of i.split(".")){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,l)){o=void 0;break}o=o[l]}if(o!==void 0&&!Tt(o)&&!(Array.isArray(o)&&o.every(l=>Tt(l))))throw new Error(`'${i}' is visible to ${t===null?"nobody in particular":t.peer}`)}}function ji(n){if(n.id.length===0)throw new h("invalid-data","a store definition needs a non-empty id");if(!Number.isSafeInteger(n.version)||n.version<1)throw new h("invalid-data",`store '${n.id}' needs a positive integer version, got ${String(n.version)}`);let e;try{e=n.empty()}catch(t){throw new h("invalid-data",`store '${n.id}' could not build its empty state: ${String(t)}`,{cause:t})}try{n.state(e)}catch(t){throw new h("invalid-data",`store '${n.id}': empty() is not a valid state, so a replica could not clear a projection with it: ${String(t)}`,{cause:t})}if(n.visibility!==void 0)try{Oe(n.visibility)}catch(t){throw new h("invalid-data",`store '${n.id}': ${t instanceof Error?t.message:String(t)}`,{cause:t})}if(n.interest!==void 0){for(let[t,r]of Object.entries(n.interest))if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': interest maps a top-level collection name to a key function, got '${t}'`)}if(n.entities!==void 0)for(let[t,r]of Object.entries(n.entities)){if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': entities maps a top-level collection name to a per-entity parser, got '${t}'`);let s=e[t];if(s!==void 0&&!Dt(s))throw new h("invalid-data",`store '${n.id}': entities names '${t}', but empty().${t} is not a record of entities`)}return Object.freeze({...n})}function Dt(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Hi=16;var T=class extends Error{constructor(t,r){super(t);this.reason=t;this.at=r}reason;at};function Ee(n){let e=new vn(n);try{return{ok:!0,value:e.document()}}catch(t){if(t instanceof T)return{ok:!1,reason:t.reason,at:t.at};throw t}}var vn=class{constructor(e){this.src=e}src;i=0;document(){if(this.skipWhitespace(),this.i>=this.src.length)throw new T("empty",this.i);let e=this.value(0);if(this.skipWhitespace(),this.i!==this.src.length)throw new T("trailing-content",this.i);return e}value(e){let t=this.src.charCodeAt(this.i);switch(t){case 123:return this.object(e+1);case 91:return this.array(e+1);case 34:return this.string();default:break}if(t===45||t>=48&&t<=57)return this.number();if(this.src.startsWith("true",this.i))return this.i+=4,!0;if(this.src.startsWith("false",this.i))return this.i+=5,!1;if(this.src.startsWith("null",this.i))return this.i+=4,null;throw new T(Number.isNaN(t)?"unexpected-end":"literal",this.i)}object(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=Object.create(null);if(this.skipWhitespace(),this.peek()===125)return this.i+=1,t;for(;;){if(this.skipWhitespace(),this.peek()!==34)throw new T("unexpected-token",this.i);let r=this.i,s=this.string();if(Object.prototype.hasOwnProperty.call(t,s))throw new T("duplicate-key",r);if(this.skipWhitespace(),this.peek()!==58)throw new T("unexpected-token",this.i);this.i+=1,this.skipWhitespace(),t[s]=this.value(e),this.skipWhitespace();let i=this.peek();if(i===44){this.i+=1;continue}if(i===125)return this.i+=1,t;throw new T(i===-1?"unexpected-end":"unexpected-token",this.i)}}array(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=[];if(this.skipWhitespace(),this.peek()===93)return this.i+=1,t;for(;;){this.skipWhitespace(),t.push(this.value(e)),this.skipWhitespace();let r=this.peek();if(r===44){this.i+=1;continue}if(r===93)return this.i+=1,t;throw new T(r===-1?"unexpected-end":"unexpected-token",this.i)}}string(){this.i+=1;let e="";for(;;){if(this.i>=this.src.length)throw new T("unexpected-end",this.i);let t=this.src.charCodeAt(this.i);if(t===34)return this.i+=1,e;if(t===92){e+=this.escape();continue}if(t<32)throw new T("string-control-char",this.i);e+=this.src[this.i],this.i+=1}}escape(){this.i+=1;let e=this.src[this.i];switch(this.i+=1,e){case'"':return'"';case"\\":return"\\";case"/":return"/";case"b":return"\b";case"f":return"\f";case"n":return`
2
+ `;case"r":return"\r";case"t":return" ";case"u":{let t=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t))throw new T("string-escape",this.i);return this.i+=4,String.fromCharCode(Number.parseInt(t,16))}default:throw new T("string-escape",this.i-1)}}number(){let e=this.i;if(this.peek()===45&&(this.i+=1),this.peek()===48){if(this.i+=1,this.isDigit(this.peek()))throw new T("number-grammar",e)}else if(this.isDigit(this.peek()))for(;this.isDigit(this.peek());)this.i+=1;else throw new T("number-grammar",e);if(this.peek()===46){if(this.i+=1,!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let t=this.src[this.i];if(t==="e"||t==="E"){this.i+=1;let s=this.peek();if((s===43||s===45)&&(this.i+=1),!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let r=Number(this.src.slice(e,this.i));if(!Number.isFinite(r))throw new T("number-not-finite",e);return r}isDigit(e){return e>=48&&e<=57}peek(){return this.i>=this.src.length?-1:this.src.charCodeAt(this.i)}skipWhitespace(){for(;;){let e=this.peek();if(e===32||e===9||e===10||e===13){this.i+=1;continue}return}}};var En=1,G=32,de=16,Nt=16,Hr=32,Lr=128,Tr=256,Dr=64,ye=1024*1024,ie=255,Wt=256,qt=8,Fe=64,Mr=256,Nr=18446744073709551615n,Li=20,Wr=["join","resume","resync","act","in","aud","alive","leave","int"],qr=["man","snap","delta","res","ok","no"],Ti={join:{required:["v","k","q","def","ver","store","key","aud"],optional:["int"]},resume:{required:["v","k","q","h","aud"],optional:["int"]},int:{required:["v","k","q","h","int"],optional:[]},resync:{required:["v","k","q","h","g","have"],optional:[]},aud:{required:["v","k","q","h","aud"],optional:[]},alive:{required:["v","k","q","h"],optional:[]},leave:{required:["v","k","q","h"],optional:[]},act:{required:["v","k","q","h","s","name","in"],optional:[]},in:{required:["v","k","h","name","s","in"],optional:[]},man:{required:["v","k","h","inc","g","r","n","bytes"],optional:["q"]},snap:{required:["v","k","h","g","r","i","n","d"],optional:[]},delta:{required:["v","k","h","g","base","r","ops"],optional:[]},res:{required:["v","k","q","h","s","out"],optional:[]},ok:{required:["v","k","q","h"],optional:[]},no:{required:["v","k","code"],optional:["q","h","s","detail"]}},Di={join:["v","k","q","def","ver","store","key","aud","int"],resume:["v","k","q","h","aud","int"],int:["v","k","q","h","int"],resync:["v","k","q","h","g","have"],aud:["v","k","q","h","aud"],alive:["v","k","q","h"],leave:["v","k","q","h"],act:["v","k","q","h","s","name","in"],in:["v","k","h","name","s","in"],man:["v","k","q","h","inc","g","r","n","bytes"],snap:["v","k","h","g","r","i","n","d"],delta:["v","k","h","g","base","r","ops"],res:["v","k","q","h","s","out"],ok:["v","k","q","h"],no:["v","k","q","h","code","s","detail"]},On=new Set(Wr),jr=new Set(qr),Mi=new Set(bn),Ni=/^[A-Za-z0-9+/]+={0,2}$/;function B(n,e,t="invalid-data"){return{ok:!1,code:t,stage:n,reason:e}}var Mt=class{constructor(e){this.refusal=e}refusal};function L(n,e,t="invalid-data"){return new Mt(B(n,e,t))}function O(n){return n instanceof Mt}function M(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.codePointAt(t);r>65535&&(t+=1),e+=r<=127?1:r<=2047?2:r<=65535?3:4}return e}function ke(n,e){if(M(n)>e.maxBytes)return B("bytes","frame-too-large","capacity");let r=Ee(n);if(!r.ok)return B("json",r.reason);let s=r.value;if(typeof s!="object"||s===null||Array.isArray(s))return B("json","not-an-object");let i=s;if(i.v!==En)return B("envelope","unknown-version");let o=i.k;if(typeof o!="string"||!(On.has(o)||jr.has(o)))return B("envelope","unknown-kind");let a=o;if(!(e.as==="owner"?On:jr).has(a))return B("direction",`wrong-direction:${a}`);let c=Ti[a],d=new Set([...c.required,...c.optional]);for(let u of Object.keys(i))if(!d.has(u))return B("payload","unknown-field");for(let u of c.required)if(!Object.prototype.hasOwnProperty.call(i,u))return B("payload","missing-field");return Wi(a,i)}function Wi(n,e){let t=(c,d)=>{let u=e[c];return typeof u!="string"||u.length!==d||!Ur(u)?L("payload",`non-canonical-hex:${c}`):u},r=c=>{let d=e[c];return typeof d!="string"||!kn(d)?L("payload",`non-canonical-decimal:${c}`):d},s=(c,d,u)=>{let p=e[c];return typeof p!="number"||!Number.isInteger(p)||p<d||p>u?L("payload",`bad-integer:${c}`):p},i=c=>{let d=e[c];return typeof d!="string"||d.length===0?L("payload",`bad-string:${c}`):d},o=c=>{let d=e[c];return typeof d!="object"||d===null||Array.isArray(d)?L("payload",`bad-object:${c}`):d},a=()=>{let c=e.aud;if(!Array.isArray(c))return L("payload","bad-audience");if(c.length>Hr)return L("payload","audience-too-many","capacity");let d=[];for(let u of c){if(typeof u!="string"||u.length===0)return L("payload","bad-audience-label");if(M(u)>Lr)return L("payload","audience-label-too-long","capacity");d.push(u)}return d},l=c=>{if(!Object.prototype.hasOwnProperty.call(e,"int"))return c?L("payload","missing-field"):void 0;let d=e.int;if(!Array.isArray(d))return L("payload","bad-interest");if(d.length>Tr)return L("payload","interest-too-many","capacity");let u=[];for(let p of d){if(typeof p!="string"||p.length===0)return L("payload","bad-interest-key");if(M(p)>Dr)return L("payload","interest-key-too-long","capacity");u.push(p)}return u};switch(n){case"int":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);if(O(d))return d.refusal;let u=l(!0);return O(u)?u.refusal:{ok:!0,message:{k:n,q:c,h:d,int:u}}}case"join":{let c=t("q",de);if(O(c))return c.refusal;let d=i("def");if(O(d))return d.refusal;let u=s("ver",0,Number.MAX_SAFE_INTEGER);if(O(u))return u.refusal;let p=i("store");if(O(p))return p.refusal;let y=i("key");if(O(y))return y.refusal;let f=a();if(O(f))return f.refusal;let b=l(!1);return O(b)?b.refusal:{ok:!0,message:b===void 0?{k:n,q:c,def:d,ver:u,store:p,key:y,aud:f}:{k:n,q:c,def:d,ver:u,store:p,key:y,aud:f,int:b}}}case"resume":case"aud":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);if(O(d))return d.refusal;let u=a();if(O(u))return u.refusal;if(n==="resume"){let p=l(!1);return O(p)?p.refusal:{ok:!0,message:p===void 0?{k:n,q:c,h:d,aud:u}:{k:n,q:c,h:d,aud:u,int:p}}}return{ok:!0,message:{k:n,q:c,h:d,aud:u}}}case"resync":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("have");return O(p)?p.refusal:{ok:!0,message:{k:n,q:c,h:d,g:u,have:p}}}case"alive":case"leave":case"ok":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);return O(d)?d.refusal:{ok:!0,message:{k:n,q:c,h:d}}}case"act":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=i("name");if(O(p))return p.refusal;let y=o("in");return O(y)?y.refusal:{ok:!0,message:{k:n,q:c,h:d,s:u,name:p,in:y}}}case"in":{let c=t("h",G);if(O(c))return c.refusal;let d=i("name");if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("in");return O(p)?p.refusal:{ok:!0,message:{k:n,h:c,name:d,s:u,in:p}}}case"res":{let c=t("q",de);if(O(c))return c.refusal;let d=t("h",G);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("out");return O(p)?p.refusal:{ok:!0,message:{k:n,q:c,h:d,s:u,out:p}}}case"man":{let c=t("h",G);if(O(c))return c.refusal;let d=t("inc",Nt);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let y=s("n",1,ie);if(O(y))return y.refusal;let f=r("bytes");if(O(f))return f.refusal;if(BigInt(f)>BigInt(ye))return B("payload","snapshot-too-large","capacity");if(Object.prototype.hasOwnProperty.call(e,"q")){let b=t("q",de);return O(b)?b.refusal:{ok:!0,message:{k:n,q:b,h:c,inc:d,g:u,r:p,n:y,bytes:f}}}return{ok:!0,message:{k:n,h:c,inc:d,g:u,r:p,n:y,bytes:f}}}case"snap":{let c=t("h",G);if(O(c))return c.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("r");if(O(u))return u.refusal;let p=s("n",1,ie);if(O(p))return p.refusal;let y=s("i",0,p-1);if(O(y))return y.refusal;let f=e.d;return typeof f!="string"||!Ut(f)?B("payload","non-canonical-base64:d"):{ok:!0,message:{k:n,h:c,g:d,r:u,i:y,n:p,d:f}}}case"delta":{let c=t("h",G);if(O(c))return c.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("base");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let y=qi(e.ops);return O(y)?y.refusal:{ok:!0,message:{k:n,h:c,g:d,base:u,r:p,ops:y}}}case"no":{let c=e.code;if(typeof c!="string"||!Mi.has(c))return B("payload","unknown-code");let d=Object.prototype.hasOwnProperty.call(e,"q"),u=Object.prototype.hasOwnProperty.call(e,"h"),p=Object.prototype.hasOwnProperty.call(e,"s");if(!d&&!u)return B("payload","no-names-nothing");if(!d){if(c!=="closed"&&c!=="owner-lost")return B("payload","unsolicited-no-must-be-closed-or-owner-lost");if(p)return B("payload","unsolicited-no-carries-no-sequence")}let y={k:"no",code:c};if(d){let f=t("q",de);if(O(f))return f.refusal;y.q=f}if(u){let f=t("h",G);if(O(f))return f.refusal;y.h=f}if(p){let f=r("s");if(O(f))return f.refusal;y.s=f}if(Object.prototype.hasOwnProperty.call(e,"detail")){let f=e.detail;if(typeof f!="string")return B("payload","bad-string:detail");if(M(f)>Mr)return B("payload","detail-too-long","capacity");y.detail=f}return{ok:!0,message:y}}}}function qi(n){if(!Array.isArray(n))return L("payload","bad-ops");if(n.length>Wt)return L("payload","ops-too-many","capacity");let e=[];for(let t of n){if(typeof t!="object"||t===null||Array.isArray(t))return L("payload","bad-op");let r=t,s=r.o;if(s!=="r"&&s!=="x")return L("payload","bad-op-kind");let i=s==="r"?["o","p","val"]:["o","p"];for(let l of Object.keys(r))if(!i.includes(l))return L("payload","unknown-field");if(s==="r"&&!Object.prototype.hasOwnProperty.call(r,"val"))return L("payload","missing-field");let o=r.p;if(!Array.isArray(o))return L("payload","bad-path");if(o.length>qt)return L("payload","path-too-deep","capacity");let a=[];for(let l of o){if(typeof l!="string"||l.length===0)return L("payload","bad-segment");if(M(l)>Fe)return L("payload","segment-too-long","capacity");a.push(l)}e.push(s==="r"?{o:s,p:a,val:r.val}:{o:s,p:a})}return e}function Ur(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e),r=t>=48&&t<=57,s=t>=97&&t<=102;if(!r&&!s)return!1}return n.length>0}function kn(n){if(n.length===0||n.length>Li)return!1;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t<48||t>57)return!1}return n.length>1&&n.charCodeAt(0)===48?!1:BigInt(n)<=Nr}function Ut(n){if(n.length===0)return!0;if(n.length%4!==0||!Ni.test(n))return!1;let e=n.endsWith("==")?2:n.endsWith("=")?1:0;if(e===0)return!0;let t=n.charCodeAt(n.length-e-1),r=Ui(t);return r<0?!1:(r&(e===2?15:3))===0}function Ui(n){return n>=65&&n<=90?n-65:n>=97&&n<=122?n-97+26:n>=48&&n<=57?n-48+52:n===43?62:n===47?63:-1}function oe(n){if(!kn(n))throw new RangeError(`not a canonical decimal: ${JSON.stringify(n)}`);return BigInt(n)}function Bt(n,e){return xn(n,e,new Set)}function xn(n,e,t){if(n===null)return null;switch(typeof n){case"boolean":case"string":return null;case"number":return Number.isFinite(n)?null:`non-finite-number:${e}`;case"object":{let r=n;if(t.has(r))return`circular:${e}`;if("toJSON"in r)return`to-json-transform:${e}`;if(r instanceof Map||r instanceof Set||r instanceof WeakMap||r instanceof WeakSet)return`map-or-set:${e}`;if(Object.getOwnPropertySymbols(r).length>0)return`symbol-key:${e}`;t.add(r);try{if(Array.isArray(n)){for(let s=0;s<n.length;s+=1){let i=xn(n[s],`${e}[${s}]`,t);if(i!==null)return i}return null}for(let[s,i]of Object.entries(n)){let o=xn(i,`${e}.${s}`,t);if(o!==null)return o}return null}finally{t.delete(r)}}default:return`not-json:${e}`}}function Bi(n){switch(n.k){case"act":case"in":return[["in",n.in]];case"res":return[["out",n.out]];case"delta":return n.ops.flatMap((e,t)=>e.o==="r"?[[`ops[${t}].val`,e.val]]:[]);default:return[]}}function I(n){for(let[o,a]of Bi(n)){let l=Bt(a,o);if(l!==null)throw new RangeError(`refusing to encode an invalid ${n.k}: ${l}`)}let e={v:En,k:n.k},t=n;for(let o of Di[n.k]){if(o==="v"||o==="k"||!Object.prototype.hasOwnProperty.call(t,o))continue;let a=t[o];a!==void 0&&(e[o]=a)}let r=JSON.stringify(e),s=On.has(n.k)?"owner":"replica",i=ke(r,{maxBytes:Number.MAX_SAFE_INTEGER,as:s});if(!i.ok)throw new RangeError(`refusing to encode an invalid ${n.k}: ${i.reason}`);return r}var $r=192,An=1024,Rn=197;function Fr(n){return Math.floor((n-$r)/4)*3}function _n(n){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new h("capacity",`the transport reported no usable event size (${String(n)})`);if(Rn>n)throw new h("capacity",`the frozen envelopes need ${Rn} B and the transport allows ${n} B`);let e=Fr(n);if(e<An)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk, below the ${An} B floor`);if(e*ie<ye)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk: ${ie} of them cover ${e*ie} B, below the ${ye} B snapshot bound`);return e}function Pn(n,e){if(e<1)throw new h("capacity",`a chunk budget of ${e} B cannot carry anything`);try{let i=Bt(n,"state");if(i!==null)throw new h("invalid-data",`the projected state is not JSON: ${i}`)}catch(i){throw i instanceof h?i:new h("invalid-data",`the projected state is not JSON: ${String(i)}`,{cause:i})}let t;try{t=JSON.stringify(n)}catch(i){throw new h("invalid-data","the projected state is not JSON",{cause:i})}if(t===void 0)throw new h("invalid-data","the projected state is not JSON");let r=new TextEncoder().encode(t);if(r.length>ye)throw new h("capacity",`the projection is ${r.length} B and the bound is ${ye} B`);let s=[];for(let i=0;i<r.length;i+=e)s.push(Jr(r.subarray(i,i+e)));if(s.length>ie)throw new h("capacity",`the projection needs ${s.length} chunks and the bound is ${ie}`);return{bytes:r.length,n:s.length,pieces:s}}var Br=32768;function Jr(n){let e="";for(let t=0;t<n.length;t+=Br)e+=String.fromCharCode(...n.subarray(t,t+Br));return btoa(e)}function In(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function $i(n){let e=JSON.stringify(n);if(e===void 0)throw new h("invalid-data","not JSON");return M(e)}var Ft=1e4,Vr=8*1024*1024;function K(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,fatal:e}}var $t=class{constructor(e,t){this.manifest=e;this.openedAt=t;this.pieces=new Array(e.n),this.encoded=new Array(e.n)}manifest;openedAt;pieces;encoded;admitted=0;held=0;closed=!1;get bytesHeld(){return this.held}get bytesReserved(){return this.closed?0:Math.max(Number(this.manifest.bytes),this.held)}get have(){return this.admitted}get reclaimed(){return this.closed}reclaim(){this.closed=!0,this.pieces.fill(void 0),this.encoded.fill(void 0),this.admitted=0,this.held=0}expired(e){return e-this.openedAt>=Ft}accept(e,t,r){if(this.closed)return K("chunk-wrong-assembly",!1);if(this.expired(r))return this.reclaim(),K("deadline",!0,"timeout");let s=this.manifest;if(e.h!==s.h||e.g!==s.g||e.r!==s.r||e.n!==s.n)return K("chunk-wrong-assembly",!1);if(!Number.isInteger(e.i)||e.i<0||e.i>=s.n)return K("chunk-index",!1);if(!Ut(e.d))return K("chunk-non-canonical",!1);let i=this.encoded[e.i];if(i!==void 0)return i===e.d?{ok:!0,done:!1,have:this.admitted}:(this.reclaim(),K("chunk-conflict",!0));let o=In(e.d),a=Number(s.bytes);if(this.held+o.length>a)return this.reclaim(),K("byte-total-mismatch",!0);if(this.encoded[e.i]=e.d,this.pieces[e.i]=o,this.admitted+=1,this.held+=o.length,this.admitted<s.n)return{ok:!0,done:!1,have:this.admitted};if(this.held!==a)return this.reclaim(),K("byte-total-mismatch",!0);let l=new Uint8Array(this.held),c=0;for(let p of this.pieces){if(p===void 0)return this.reclaim(),K("byte-total-mismatch",!0);l.set(p,c),c+=p.length}let d=new TextDecoder("utf-8",{fatal:!0}),u;try{let p=Ee(d.decode(l));if(!p.ok)return this.reclaim(),K("assembled-not-json",!0);u=p.value}catch{return this.reclaim(),K("assembled-not-json",!0)}try{t(u)}catch{return this.reclaim(),K("assembled-invalid",!0)}return this.reclaim(),{ok:!0,done:!0,document:u}}},it=class n{constructor(e=Vr){this.maxTotalBytes=e}maxTotalBytes;live=new Map;static key(e,t){return`${e}/${t}`}get bytesHeld(){let e=0;for(let t of this.live.values())e+=t.bytesHeld;return e}get bytesReserved(){let e=0;for(let t of this.live.values())e+=t.bytesReserved;return e}get size(){return this.live.size}get(e,t){return this.live.get(n.key(e,t))}open(e,t){if(!Number.isInteger(e.n)||e.n<1||e.n>ie)return K("manifest-chunk-count",!0);let r=Number(e.bytes);if(!Number.isSafeInteger(r)||r<0||r>ye)return K("manifest-bytes",!0,"capacity");let s=n.key(e.h,e.g),i=this.live.get(s),o=i?.bytesReserved??0;if(this.bytesReserved-o+r>this.maxTotalBytes)return K("assembly-too-large",!0,"capacity");i?.reclaim(),this.live.delete(s);let a=new $t(e,t);return this.live.set(s,a),a}reclaim(e,t){let r=n.key(e,t);this.live.get(r)?.reclaim(),this.live.delete(r)}reclaimHandle(e){for(let[t,r]of[...this.live])t.startsWith(`${e}/`)&&(r.reclaim(),this.live.delete(t))}sweep(e){let t=0;for(let[r,s]of[...this.live])s.expired(e)&&(s.reclaim(),this.live.delete(r),t+=1);return t}clear(){for(let e of this.live.values())e.reclaim();this.live.clear()}};function ue(n,e){if(Object.is(n,e))return e;if(Array.isArray(e)){let t=e;if(!Array.isArray(n))return Xr(t,void 0);let r=Xr(t,n);return n.length===t.length&&Fi(n,r)?n:r}if(Kr(e)){if(!Kr(n))return zr(e,void 0);let t=zr(e,n),r=Object.keys(e);return r.length===Object.keys(n).length&&r.every(s=>Gr(n,s)&&Object.is(n[s],t[s]))?n:t}return e}function Jt(n,e){let t=Object.keys(e);if(t.length===0)return n;let r=!1,s={...n};for(let i of t){let o=Yr(n,i),a=ue(o,e[i]);Object.is(o,a)||(Object.defineProperty(s,i,{value:a,enumerable:!0,writable:!0,configurable:!0}),r=!0)}return r?Object.freeze(s):n}function Kr(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Fi(n,e){for(let t=0;t<e.length;t+=1)if(!Object.is(n[t],e[t]))return!1;return!0}function Xr(n,e){let t=new Array(n.length);for(let r=0;r<n.length;r+=1)t[r]=ue(e?.[r],n[r]);return Object.freeze(t)}function Gr(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Yr(n,e){if(n!==void 0)return Gr(n,e)?n[e]:void 0}function zr(n,e){let t={};for(let r of Object.keys(n))Object.defineProperty(t,r,{value:ue(Yr(e,r),n[r]),enumerable:!0,writable:!1,configurable:!1});return Object.freeze(t)}var Qr=["__proto__","constructor","prototype"],Ji=new Set(Qr);function pe(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,resync:e}}function Cn(n,e,t){if(e.length>Wt)return pe("ops-too-many",!1,"capacity");for(let a of e){if(a.p.length>qt)return pe("path-too-deep",!1,"capacity");for(let l of a.p){if(M(l)>Fe)return pe("segment-too-long",!1,"capacity");if(Ji.has(l))return pe("segment-forbidden",!1)}if(a.o==="x"&&a.p.length===0)return pe("root-remove",!1)}let r=n,s=new WeakSet;for(let a of e){if(a.p.length===0){a.o==="r"&&(r=a.val);continue}if(!ts(r))return pe("parent-not-object",!0);let l=ns(r,s);r=l;let c=Vi(l,a.p.slice(0,-1),s);if(c===Zr)return pe("missing-parent",!0);if(c===es)return pe("parent-not-object",!0);let d=c,u=a.p[a.p.length-1];if(a.o==="x"){if(!Object.prototype.hasOwnProperty.call(d,u))return pe("missing-key",!0);delete d[u];continue}d[u]=a.val}let i;try{i=t(r)}catch{return pe("invalid-state",!0)}let o=ue(n,i);return{ok:!0,next:o,changed:!Object.is(o,n)}}var Zr=Symbol("missing-parent"),es=Symbol("parent-not-object");function Vi(n,e,t){let r=n;for(let s of e){let i=r;if(!Object.prototype.hasOwnProperty.call(i,s))return Zr;let o=i[s];if(!ts(o))return es;let a=ns(o,t);i[s]=a,r=a}return r}function ts(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ns(n,e){if(e.has(n))return n;let t=Object.assign(Object.create(null),n);return e.add(t),t}var ge=class{#e;#t=new Set;#r=new Set;#n;#s;#b=0;#l=null;#o=0;#u=!1;constructor(e){this.#e=e.definition,this.#n=ue(void 0,this.#d(e.initialState)),this.#s=Object.freeze({phase:e.phase??"ready",stale:!1,error:null})}getState(){return this.#n}get revision(){return this.#b}get inTransaction(){return this.#l!==null&&this.#l.active}subscribe(e,t,r){let s=t===void 0?this.#y(e):this.#O(e,t,r);this.#t.add(s);let i=!0;return()=>{i&&(i=!1,this.#t.delete(s))}}getStatus(){return this.#s}subscribeStatus(e){this.#r.add(e);let t=!0;return()=>{t&&(t=!1,this.#r.delete(e))}}setStatus(e){let t=this.#s,r={phase:e.phase??t.phase,stale:e.stale??t.stale,error:e.error===void 0?t.error:e.error};if(!(r.phase===t.phase&&r.stale===t.stale&&Object.is(r.error,t.error))){this.#s=Object.freeze(r);for(let s of[...this.#r])this.#r.has(s)&&Vt(()=>s(this.#s,t))}}transact(e,t){if(this.#a(),this.#l!==null)throw new h("action-rejected","a store transaction is already open on this store; handlers are synchronous and must not nest");let r={staged:this.#n,active:!0};this.#l=r;try{let s=e(this.#c(r,t));if(Ki(s))throw new h("action-rejected","a store handler returned a thenable; handlers are synchronous so that a throw can discard the whole transaction");return this.#m(r.staged),s}finally{r.active=!1,this.#l=null}}applyOwnerUpdate(e){this.#a();let t=this.#l;if(t!==null&&t.active){t.staged=this.#f(t.staged,e);return}let r=this.#f(this.#n,e);this.#m(r)}applySnapshot(e){this.#a();let t=this.#l;if(t!==null&&t.active){t.staged=this.#d(e);return}this.#m(this.#d(e))}applyEntities(e,t){this.#a();let r=this.#e.entities?.[e];if(r===void 0||!Object.prototype.hasOwnProperty.call(this.#e.entities,e))throw new h("invalid-data",`store '${this.#e.id}' declares no per-entity parser for '${e}'; declare it in \`entities\` or write through setState`);let s=this.#l,i=s!==null&&s.active?s.staged:this.#n,o=i[e];if(o!==void 0&&!Dt(o))throw new h("invalid-data",`store '${this.#e.id}': '${e}' is not an entity map in the current state`);let a=[];for(let p of Object.keys(t)){if(p.length===0)throw new h("invalid-data",`store '${this.#e.id}': an entity id in '${e}' is empty`);let y=t[p];if(y===void 0){a.push([p,void 0]);continue}try{a.push([p,this.runReadOnly(()=>r(y))])}catch(f){throw f instanceof h?f:new h("invalid-data",`entity '${e}.${p}' failed the '${this.#e.id}' entity validator: ${String(f)}`,{cause:f})}}if(s!==null&&s.active){let p={...o??{}};for(let[y,f]of a)f===void 0?delete p[y]:jn(p,y,f);s.staged=Jt(i,{[e]:p});return}let l=!1,c=[];for(let[p,y]of a){let f=o!==void 0&&Object.prototype.hasOwnProperty.call(o,p),b=f?o[p]:void 0;if(y===void 0){f&&(l=!0),c.push([p,void 0]);continue}let A=ue(b,y);Object.is(b,A)||(l=!0),c.push([p,A])}if(!l)return;let d={...o??{}};for(let[p,y]of c)y===void 0?delete d[p]:jn(d,p,y);let u={...i};jn(u,e,Object.freeze(d)),this.#p(Object.freeze(u))}applyDelta(e){this.#a();let t=Cn(this.#n,e,r=>this.#d(r));return t.ok&&t.changed&&this.#h(t.next),t}runReadOnly(e){this.#o+=1;try{return e()}finally{this.#o-=1}}close(){this.#u||(this.#u=!0,this.setStatus({phase:"closed",stale:!0}),this.#t.clear(),this.#r.clear())}#c(e,t){return{peer:t,getState:()=>(this.#w(e),e.staged),setState:r=>{if(this.#w(e),this.#o>0)throw new h("action-rejected","a read-only store callback may not write state; validators, authorize, project and update functions run with setters fenced");e.staged=this.#f(e.staged,r)}}}#f(e,t){let r=typeof t=="function"?this.runReadOnly(()=>t(e)):t;return Jt(e,r)}#m(e){this.#h(this.#d(e))}#h(e){let t=ue(this.#n,e);Object.is(t,this.#n)||this.#p(t)}#p(e){let t=this.#n;this.#n=e,this.#b+=1;for(let r of[...this.#t])this.#t.has(r)&&r.notify(e,t)}#d(e){try{return this.runReadOnly(()=>this.#e.state(e))}catch(t){throw t instanceof h?t:new h("invalid-data",`state failed the '${this.#e.id}' validator: ${String(t)}`,{cause:t})}}#y(e){return{notify:(t,r)=>{Vt(()=>e(t,r))}}}#O(e,t,r){let s=r?.equality??Object.is,i=this.runReadOnly(()=>e(this.#n));return r?.fireImmediately===!0&&Vt(()=>t(i,i)),{notify:o=>{let a=this.runReadOnly(()=>e(o)),l=i;s(a,l)||(i=a,Vt(()=>t(a,l)))}}}#w(e){if(!e.active)throw new h("action-rejected","this store transaction has already ended; its context cannot read or write from a later turn")}#a(){if(this.#u)throw new h("closed","this store handle is closed")}};function Ki(n){return n===null||typeof n!="object"&&typeof n!="function"?!1:typeof n.then=="function"}function Vt(n){try{n()}catch(e){console.error("[@net-mesh/browser] store listener threw",e)}}function jn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}var rs=32,ss=64*1024,is=6e4,os=2048,as=(1n<<64n)-1n,Xi="";function Ln(n,e){return`${n}${Xi}${Hn(e)}`}function Hn(n){if(n===null||typeof n=="boolean")return String(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new h("invalid-data","a canonical request cannot contain a non-finite number");return String(n)}if(typeof n=="string")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(s=>Hn(s)).join(",")}]`;let e=n;return`{${Object.keys(e).sort().map(s=>`${JSON.stringify(s)}:${Hn(e[s])}`).join(",")}}`}function ls(n){return new TextEncoder().encode(n).byteLength}function zt(n){return ls(n)>os}function Tn(n){if(zt(n))throw new h("invalid-data","this canonical form needs the digest path");return{form:"inline",value:n}}async function Dn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t=new Uint8Array(e),r="";for(let s of t)r+=s.toString(16).padStart(2,"0");return{form:"digest",value:r}}function zi(n,e){return n.form===e.form&&n.value===e.value}var Kt=class{constructor(e=rs,t=ss,r=is){this.maxEntries=e;this.maxBytes=t;this.maxAgeMs=r}maxEntries;maxBytes;maxAgeMs;#e=0n;#t=new Map;#r=0;get floor(){return this.#e.toString()}get size(){return this.#t.size}get bytesHeld(){return this.#r}disposition(e,t,r){if(this.expire(r),e>=as)return{kind:"exhausted"};let s=this.#t.get(e.toString());return s!==void 0?zi(s.binding,t)?{kind:"replay",outcome:s.outcome}:{kind:"conflict"}:e<=this.#e?{kind:"expired"}:{kind:"execute"}}retain(e,t,r,s){let i=Gi(t,r);this.#t.set(e.toString(),{s:e,binding:t,outcome:r,bytes:i,at:s}),this.#r+=i,this.evict(s)}expire(e){for(let t of this.ordered()){if(e-t.at<this.maxAgeMs)break;this.drop(t)}}evict(e){for(this.expire(e);this.#t.size>this.maxEntries||this.#r>this.maxBytes;){let t=this.ordered()[0];if(t===void 0)return;this.drop(t)}}drop(e){this.#t.delete(e.s.toString()),this.#r-=e.bytes,e.s>this.#e&&(this.#e=e.s)}ordered(){return[...this.#t.values()].sort((e,t)=>e.s<t.s?-1:e.s>t.s?1:0)}};function Gi(n,e){let t=e.kind==="result"?JSON.stringify(e.out):e.code;return M(n.value)+M(t)}var Xt=class{#e=new Map;#t=0;get dropped(){return this.#t}admit(e,t){let r=this.#e.get(e);return r!==void 0&&t<=r?(this.#t+=1,!1):(this.#e.set(e,t),!0)}latest(e){let t=this.#e.get(e);return t===void 0?null:t.toString()}},ot=class{#e=new Map;#t=new Map;ledger(e){let t=this.#e.get(e);return t===void 0&&(t=new Kt,this.#e.set(e,t)),t}inputs(e){let t=this.#t.get(e);return t===void 0&&(t=new Xt,this.#t.set(e,t)),t}forget(e){this.#e.delete(e),this.#t.delete(e)}get size(){return this.#e.size}};var us=32,ps=256,Mn=6e4,fs=256;function me(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var Yi="0".repeat(16),Qi="0".repeat(32),at=class{constructor(e){this.deps=e;if(this.chunkBytes=_n(e.maxEventBytes),this.incarnation=e.newIncarnation(),this.incarnation.length!==Nt)throw new h("invalid-data","newIncarnation must return 16 lowercase hex");let t=(typeof e.project=="function"?1:0)+(typeof e.projectFor=="function"?1:0),r=e.definition.visibility;if(t>1||t===0&&r===void 0)throw new h("invalid-data","a host needs one of `project` and `projectFor`, or a definition that declares `visibility`");this.visibility=r===void 0?null:Oe(r),this.perPlayer=typeof e.projectFor=="function"||this.visibility?.perPlayer===!0,this.core=new ge({definition:e.definition,initialState:e.definition.empty()})}deps;handles=new Map;counters={};chunkBytes;incarnation;core;pending=0;ledgers=new ot;deferred=new Map;revisionBeforeCommit=0;perPlayer;visibility;warned=new Set;warnOnce(e){if(!(this.deps.warn===void 0||this.warned.has(e))){this.warned.add(e);try{this.deps.warn(e)}catch{}}}viewKey(e,t){return this.perPlayer?JSON.stringify([e,t]):JSON.stringify(t)}get sparseViews(){return this.sparseViewCount}sparseViewCount=0;snapshotCounters(){return{...this.counters}}get handleCount(){return this.handles.size}handle(e){return this.handles.get(e)}commit(e){let t=this.core.inTransaction,r=this.core.getState();if(t||(this.revisionBeforeCommit=this.core.revision),this.core.applySnapshot(e),t)return this.accept([]);let s=this.core.getState();return Object.is(r,s)?this.accept([]):this.accept(this.propagate(r,s))}commitEntities(e,t){let r=this.core.inTransaction,s=this.core.getState();if(r||(this.revisionBeforeCommit=this.core.revision),this.core.applyEntities(e,t),r)return this.accept([]);let i=this.core.getState();return Object.is(s,i)?this.accept([]):this.accept(this.propagate(s,i))}propagate(e,t){let r=[],s=String(this.core.revision),i=new Map,o=new Map,a;for(let l of[...this.handles.values()]){if(this.deferred.has(l.h))continue;if(!this.permitsRead(l.peer,l.audience)){this.forget(l.h,"refused"),r.push(this.no(l.peer,l.h,"closed",null));continue}let c=this.viewKey(l.peer,l.audience),d;if(this.interestFns.length>0&&l.interest!==null){let y=i.get(c);if(y===void 0){if(a===void 0&&(a=this.entityDelta(e,t)),y=a===null?void 0:this.sparseInterestDiff(l.peer,l.audience,a),y===void 0){let f=this.project(l.peer,l.audience,e),b=this.project(l.peer,l.audience,t);y=f===null||b===null?null:this.interestDiff(f,b)}else this.sparseViewCount+=1;i.set(c,y)}d=y===null?null:this.interestOps(y,l.interest)}else if(d=o.get(c),d===void 0){let y=this.project(l.peer,l.audience,e),f=this.project(l.peer,l.audience,t);d=y===null||f===null?null:cs(y,f),o.set(c,d)}if(d===null){this.forget(l.h),r.push(this.no(l.peer,l.h,"closed",null));continue}if(d.length===0)continue;let u=ds({k:"delta",h:l.h,g:String(l.generation),base:String(l.revision),r:s,ops:d},this.deps.maxEventBytes);if(u!==null){r.push({peer:l.peer,h:l.h,frame:u}),this.handles.set(l.h,{...l,revision:this.core.revision});continue}let p=this.install(l,null);if(p===null){this.forget(l.h),r.push(this.no(l.peer,l.h,"closed",null));continue}r.push(...p)}return r}getState(){return this.core.getState()}subscribe(e){return this.core.subscribe((t,r)=>{e(t,r)})}get currentRevision(){return this.core.revision}localRead(e,t){return this.permitsRead(e,t)}localView(e,t,r=null){let s=this.project(e,t);return s===null?null:this.filterInterest(s,r)}localAct(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,e))return{outcome:{kind:"refusal",code:"invalid-data"},dispatched:this.refuse("local-act-unknown-name")};if(!this.permitsAction(r,e,t))return{outcome:{kind:"refusal",code:"forbidden"},dispatched:this.refuse("local-act-forbidden")};let s=this.deps.definition.actions[e],i=this.core.getState();this.revisionBeforeCommit=this.core.revision;let o;try{let c=this.deps.actions[e];o={kind:"result",out:this.core.transact(u=>{let p=s.output(c(s.input(t),u)),y=I({k:"res",q:Yi,h:Qi,s:"1",out:p});if(M(y)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return p},r)}}catch(c){o={kind:"refusal",code:c instanceof h&&c.code==="capacity"?"capacity":"action-rejected"}}let a=this.core.getState(),l=Object.is(i,a)?[]:this.propagate(i,a);return{outcome:o,dispatched:o.kind==="refusal"?this.refuse(`local-act-${o.code}`,l):this.accept(l)}}localInput(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,e))return this.refuse("local-in-unknown-name");if(!this.permitsInput(r,e,t))return this.refuse("local-in-forbidden");let s=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(o=>{let a=this.deps.definition.inputs[e],l=this.deps.inputs[e];l(a(t),o)},r)}catch{return this.refuse("local-in-rejected")}let i=this.core.getState();return this.accept(Object.is(s,i)?[]:this.propagate(s,i))}receive(e,t,r=this.deps.now()){let s=ke(e,{maxBytes:this.deps.maxEventBytes,as:"owner"});if(!s.ok)return this.refuse(s.reason,[]);let i=s.message;if(i.k==="join")return this.join(i,t,r);let o=this.bind(i.h,t,r);if(typeof o=="string")return this.refuse(o,[this.no(t,i.h,"closed",to(i))]);switch(i.k){case"alive":return this.handles.set(o.h,{...o,lastSeen:r}),this.accept([{peer:t,h:o.h,frame:I({k:"ok",q:i.q,h:o.h})}]);case"leave":return this.forget(o.h,"left"),this.accept([{peer:t,h:o.h,frame:I({k:"ok",q:i.q,h:o.h})}]);case"int":return this.interestChange(i,o,t,r);case"act":return this.action(i,o,t,r);case"in":return this.input(i,o,t,r);case"resync":{if(!this.permitsRead(t,o.audience))return this.refuse("resync-forbidden",[this.no(t,o.h,"forbidden",i.q)]);let a={...o,lastSeen:r};this.handles.set(o.h,a);let l=this.install(a,i.q);return l===null?(this.forget(o.h),this.refuse("resync-projection-capacity",[this.no(t,o.h,"capacity",i.q)])):this.accept(l)}case"aud":case"resume":{if(!this.permitsRead(t,i.aud))return this.refuse(`${i.k}-forbidden`,[this.no(t,o.h,"forbidden",i.q)]);let a={...o,audience:[...i.aud],interest:i.k==="resume"&&i.int!==void 0?[...i.int]:o.interest,lastSeen:r};if(this.handles.set(a.h,a),!this.deps.canProject())return this.deferred.set(a.h,{q:i.q,peer:t}),this.accept([]);let l=this.install(a,i.q);return l===null?(this.forget(a.h),this.refuse(`${i.k}-projection-capacity`,[this.no(t,a.h,"capacity",i.q)])):this.accept(l)}default:return this.refuse("unreachable-kind")}}action(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,i))return this.refuse("act-unknown-name",[this.no(r,t.h,"invalid-data",e.q)]);let o;try{o=Ln(i,e.in)}catch{return this.refuse("act-uncanonical",[this.no(r,t.h,"invalid-data",e.q)])}if(!zt(o))return this.decide(e,t,r,s,Tn(o));if(this.pending>=us)return this.refuse("act-pending-bound",[this.no(r,t.h,"capacity",e.q)]);this.pending+=1;let a=Dn(o).then(l=>{let c=this.deps.now(),d=this.bind(e.h,r,c);return typeof d=="string"?this.refuse(d,[this.no(r,e.h,"closed",e.q)]):this.decide(e,d,r,c,l)}).catch(()=>this.refuse("act-digest-failed",[this.no(r,e.h,"indeterminate",e.q)])).finally(()=>{this.pending-=1});return{out:[],refused:null,deferred:a}}decide(e,t,r,s,i){let o=this.ledgers.ledger(t.h),a=oe(e.s),l=o.disposition(a,i,s);switch(l.kind){case"exhausted":return this.refuse("act-sequence-exhausted",[this.no(r,t.h,"capacity",e.q)]);case"conflict":return this.refuse("act-binding-mismatch",[this.no(r,t.h,"invalid-data",e.q)]);case"expired":return this.refuse("act-result-expired",[this.no(r,t.h,"result-expired",e.q)]);case"replay":return this.permitsAction(r,e.name,e.in)?(this.renew(t,s),this.accept([this.reply(t,r,e.q,a,l.outcome)])):this.refuse("act-forbidden-replay",[this.no(r,t.h,"forbidden",e.q)]);case"execute":break}if(!this.permitsAction(r,e.name,e.in))return o.retain(a,i,{kind:"refusal",code:"forbidden"},s),this.renew(t,s),this.refuse("act-forbidden",[this.no(r,t.h,"forbidden",e.q)]);let c=this.deps.definition.actions[e.name],d=this.core.getState();this.revisionBeforeCommit=this.core.revision;let u;try{let f=this.deps.actions[e.name];u={kind:"result",out:this.core.transact(A=>{let R=c.input(e.in),F=c.output(f(R,A)),H=I({k:"res",q:e.q,h:t.h,s:e.s,out:F});if(M(H)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return F},r)}}catch(f){u={kind:"refusal",code:f instanceof h&&f.code==="capacity"?"capacity":"action-rejected"}}o.retain(a,i,u,s),this.renew(t,s);let p=this.core.getState(),y=Object.is(d,p)?[]:this.propagate(d,p);return this.accept([this.reply(t,r,e.q,a,u),...y])}input(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,i))return this.refuse("in-unknown-name");if(!this.ledgers.inputs(t.h).admit(i,oe(e.s)))return this.refuse("in-stale-sequence");if(!this.permitsInput(r,i,e.in))return this.refuse("in-forbidden");let o=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(l=>{let c=this.deps.definition.inputs[i],d=this.deps.inputs[i];d(c(e.in),l)},r)}catch{return this.refuse("in-rejected")}this.renew(t,s);let a=this.core.getState();return this.accept(Object.is(o,a)?[]:this.propagate(o,a))}reply(e,t,r,s,i){let o=i.kind==="result"?I({k:"res",q:r,h:e.h,s:s.toString(),out:i.out}):I({k:"no",q:r,h:e.h,code:i.code,s:s.toString()});return{peer:t,h:e.h,frame:o}}permitsAction(e,t,r){let s={type:"action",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}permitsInput(e,t,r){let s={type:"input",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}renew(e,t){let r=this.handles.get(e.h);r!==void 0&&this.handles.set(e.h,{...r,lastSeen:t})}forget(e,t="dropped"){let r=this.handles.get(e);this.handles.delete(e),this.ledgers.forget(e),this.deferred.delete(e),r!==void 0&&(this.presenceChanged(r.peer,t),this.membershipChanged())}present=new Set;localPlayers=new Set;pendingEvents=[];areas=new Map;areasAt=-1;ending=!1;get wantsEvents(){return this.deps.onEvent!==void 0||this.deps.areaOf!==void 0}isPresent(e){if(this.localPlayers.has(e))return!0;for(let t of this.handles.values())if(t.peer===e)return!0;return!1}presenceChanged(e,t,r=[]){if(!this.wantsEvents||this.ending)return;let s=this.isPresent(e),i=this.present.has(e);s!==i&&(s?(this.present.add(e),this.pendingEvents.push(Object.freeze({type:"join",peer:e,audience:Object.freeze([...r])}))):(this.present.delete(e),this.areas.delete(e),this.pendingEvents.push(Object.freeze({type:"leave",peer:e,reason:t??"dropped"}))))}localPresence(e,t,r=[],s="left"){t?this.localPlayers.add(e):this.localPlayers.delete(e),this.presenceChanged(e,t?null:s,r)}detectAreas(){let e=this.deps.areaOf;if(e===void 0||this.ending||this.areasAt===this.core.revision&&[...this.present].every(r=>this.areas.has(r)))return;this.areasAt=this.core.revision;let t=this.core.getState();for(let r of this.present){let s;try{let a=this.core.runReadOnly(()=>e(t,r));s=typeof a=="string"?a:null}catch{s=null}let i=this.areas.has(r),o=i?this.areas.get(r)??null:null;this.areas.set(r,s),(i?o!==s:s!==null)&&this.pendingEvents.push(Object.freeze({type:"area",peer:r,from:o,to:s}))}}drainEvents(){let e=[];if(!this.wantsEvents)return this.accept(e);for(let t=0;;t+=1){this.pendingEvents.length===0&&this.detectAreas();let r=this.pendingEvents.shift();if(r===void 0)break;if(t>=fs){this.pendingEvents.length=0,this.counters["event-rounds-bound"]=(this.counters["event-rounds-bound"]??0)+1;break}let s=this.deps.onEvent;if(s===void 0)continue;let i=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(a=>s(r,a),r.peer)}catch{this.counters["event-rejected"]=(this.counters["event-rejected"]??0)+1;continue}let o=this.core.getState();Object.is(i,o)||e.push(...this.propagate(i,o))}return this.accept(e)}membership=new Set;membershipChanged(){for(let e of[...this.membership])try{e()}catch{}}onMembership(e){return this.membership.add(e),()=>{this.membership.delete(e)}}peers(){return[...new Set([...this.handles.values()].map(e=>e.peer))]}reauthorize(){let e=[];for(let t of[...this.handles.values()])this.permitsRead(t.peer,t.audience)||(this.forget(t.h,"refused"),e.push(this.no(t.peer,t.h,"closed",null)));return this.accept(e)}resumeDeferred(e=this.deps.now()){if(!this.deps.canProject())return this.accept([]);let t=[];for(let[r,s]of[...this.deferred]){this.deferred.delete(r);let i=this.bind(r,s.peer,e);if(typeof i=="string"){this.counters[`deferred-${i}`]=(this.counters[`deferred-${i}`]??0)+1;continue}let o=this.install(i,s.q);if(o===null){this.forget(r),t.push(this.no(s.peer,r,"capacity",s.q));continue}t.push(...o)}return this.accept(t)}get deferredCount(){return this.deferred.size}get ledgerCount(){return this.ledgers.size}accept(e,t=null){return{out:e,refused:null,deferred:t}}sweep(e){let t=[];for(let[r,s]of[...this.handles])e-s.lastSeen>=Mn&&(this.forget(r,"expired"),t.push({h:r,peer:s.peer}));return t}farewell(){this.ending=!0,this.pendingEvents.length=0;let e=[];for(let[t,r]of[...this.handles])this.forget(t),e.push(this.no(r.peer,t,"owner-lost",null));return e}get incarnationHex(){return this.incarnation}join(e,t,r){if(e.store!==this.deps.store)return this.refuse("join-other-store",[]);if(e.def!==this.deps.definition.id)return this.refuse("join-wrong-definition",[this.no(t,null,"version-mismatch",e.q)]);if(e.ver!==this.deps.definition.version)return this.refuse("join-wrong-version",[this.no(t,null,"version-mismatch",e.q)]);if(this.handles.size>=ps)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);if(!this.permitsRead(t,e.aud))return this.refuse("join-forbidden",[this.no(t,null,"forbidden",e.q)]);let s=this.newHandle();if(s===null||s.length!==G||this.handles.has(s))return this.refuse("join-handle-unusable",[this.no(t,null,"owner-lost",e.q)]);let i={h:s,inc:this.incarnation,peer:t,audience:[...e.aud],interest:e.int===void 0?null:[...e.int],generation:0,revision:this.core.revision,lastSeen:r};this.handles.set(s,i);let o=this.install(i,e.q);return o===null?(this.forget(s),this.refuse("join-projection-capacity",[this.no(t,null,"capacity",e.q)])):(this.presenceChanged(t,null,e.aud),this.membershipChanged(),this.accept(o))}install(e,t){let r=this.project(e.peer,e.audience),s=r===null?null:this.filterInterest(r,e.interest);if(s===null)return null;let i;try{i=Pn(s,this.chunkBytes)}catch{return null}let o=e.generation+1;this.handles.set(e.h,{...e,generation:o,revision:this.core.revision});let a=String(o),l=String(this.core.revision),c=[{peer:e.peer,h:e.h,frame:I(t===null?{k:"man",h:e.h,inc:e.inc,g:a,r:l,n:i.n,bytes:String(i.bytes)}:{k:"man",q:t,h:e.h,inc:e.inc,g:a,r:l,n:i.n,bytes:String(i.bytes)})}];for(let d=0;d<i.n;d+=1)c.push({peer:e.peer,h:e.h,frame:I({k:"snap",h:e.h,g:a,r:l,i:d,n:i.n,d:i.pieces[d]})});return c}permitsRead(e,t){let r={type:"read",peer:e,audience:[...t]};try{return this.deps.authorize(r)===!0}catch{return!1}}newHandle(){try{return this.deps.newHandle()}catch{return null}}get interestFns(){return this.#e??=Object.entries(this.deps.definition.interest??{}).map(([e,t])=>[e,t]),this.#e}#e;interestKey(e,t,r){try{let s=this.core.runReadOnly(()=>e(t,r));return typeof s=="string"?s:null}catch{return null}}filterInterest(e,t){if(t===null||this.interestFns.length===0)return e;let r=new Set(t),s={...e};for(let[i,o]of this.interestFns){let a=s[i];if(!me(a))continue;let l={};for(let[c,d]of Object.entries(a)){let u=this.interestKey(o,d,c);(u===null||r.has(u))&&(l[c]=d)}s[i]=l}return s}entityDelta(e,t){if(this.deps.project!==void 0||this.deps.projectFor!==void 0)return null;let r=this.deps.definition.entities;if(r===void 0)return null;let s=new Set(this.interestFns.map(([l])=>l)),i=e,o=t,a=[];for(let l of new Set([...Object.keys(i),...Object.keys(o)])){let c=Object.prototype.hasOwnProperty.call(i,l)?i[l]:void 0,d=Object.prototype.hasOwnProperty.call(o,l)?o[l]:void 0;if(Object.is(c,d))continue;if(!s.has(l)||!Object.prototype.hasOwnProperty.call(r,l)||!me(c)||!me(d))return null;let u=[];for(let p of new Set([...Object.keys(c),...Object.keys(d)])){let y=Object.prototype.hasOwnProperty.call(c,p)?c[p]:void 0,f=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0;Object.is(y,f)||u.push(p)}a.push({collection:l,ids:u,before:c,after:d})}return{collections:a}}sparseInterestDiff(e,t,r){let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=(y,f,b)=>{Object.defineProperty(y,f,{value:b,enumerable:!0,writable:!0,configurable:!0})},o={},a={};for(let{collection:y,ids:f,before:b,after:A}of r.collections){let R={},F={};for(let H of f)Object.prototype.hasOwnProperty.call(b,H)&&i(R,H,b[H]),Object.prototype.hasOwnProperty.call(A,H)&&i(F,H,A[H]);i(o,y,R),i(a,y,F)}let l=this.visibility===null?o:xe(this.visibility,o,s),c=this.visibility===null?a:xe(this.visibility,a,s),d=new Map(this.interestFns),u=this.deps.definition.entities,p=[];for(let{collection:y,ids:f}of r.collections){let b=l[y],A=c[y];if(!me(b)||!me(A))return;let R=u[y],F=d.get(y),H=(x,_)=>{if(x===void 0||!_)return{ok:!0,value:x};try{return{ok:!0,value:this.core.runReadOnly(()=>R(x))}}catch{return{ok:!1,value:void 0}}};for(let x of f){let _=H(Object.prototype.hasOwnProperty.call(b,x)?b[x]:void 0,l!==o),P=H(Object.prototype.hasOwnProperty.call(A,x)?A[x]:void 0,c!==a);if(!_.ok||!P.ok)return;Object.is(_.value,P.value)||_.value!==void 0&&P.value!==void 0&&JSON.stringify(_.value)===JSON.stringify(P.value)||p.push({collection:y,id:x,before:_.value,after:P.value,beforeKey:_.value===void 0?null:this.interestKey(F,_.value,x),afterKey:P.value===void 0?null:this.interestKey(F,P.value,x)})}}return{rest:[],entities:p,whole:[]}}interestDiff(e,t){let r=new Set(this.interestFns.map(([l])=>l)),s=l=>{let c={};for(let[d,u]of Object.entries(l))r.has(d)||(c[d]=u);return c},i=cs(s(e),s(t)),o=[],a=[];for(let[l,c]of this.interestFns){let d=e[l],u=t[l];if(!me(d)||!me(u)){JSON.stringify(d)!==JSON.stringify(u)&&a.push({collection:l,after:u});continue}for(let p of new Set([...Object.keys(d),...Object.keys(u)])){let y=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0,f=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0;Object.is(y,f)||y!==void 0&&f!==void 0&&JSON.stringify(y)===JSON.stringify(f)||o.push({collection:l,id:p,before:y,after:f,beforeKey:y===void 0?null:this.interestKey(c,y,p),afterKey:f===void 0?null:this.interestKey(c,f,p)})}}return{rest:i,entities:o,whole:a}}interestOps(e,t){let r=new Set(t),s=o=>o===null||r.has(o),i=[...e.rest];for(let o of e.entities){let a=o.before!==void 0&&s(o.beforeKey);o.after!==void 0&&s(o.afterKey)?i.push({o:"r",p:[o.collection,o.id],val:o.after}):a&&i.push({o:"x",p:[o.collection,o.id]})}for(let o of e.whole){let a=this.filterInterest({[o.collection]:o.after},t);i.push({o:"r",p:[o.collection],val:a[o.collection]})}return i}interestChange(e,t,r,s){let i={...t,interest:[...e.int],lastSeen:s};this.handles.set(i.h,i);let o={peer:r,h:t.h,frame:I({k:"ok",q:e.q,h:t.h})};if(this.interestFns.length===0||this.deferred.has(t.h))return this.accept([o]);let a=this.project(r,t.audience);if(a===null)return this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)]);let l=this.filterInterest(a,t.interest),c=this.filterInterest(a,i.interest),d=[];for(let[f]of this.interestFns){let b=l[f],A=c[f];if(!(!me(b)||!me(A))){for(let R of Object.keys(A))Object.prototype.hasOwnProperty.call(b,R)||d.push({o:"r",p:[f,R],val:A[R]});for(let R of Object.keys(b))Object.prototype.hasOwnProperty.call(A,R)||d.push({o:"x",p:[f,R]})}}if(d.length===0)return this.accept([o]);let u=String(this.core.revision),p=t.revision===this.core.revision?ds({k:"delta",h:t.h,g:String(t.generation),base:u,r:u,ops:d},this.deps.maxEventBytes):null;if(p!==null)return this.accept([{peer:r,h:t.h,frame:p},o]);let y=this.install(i,null);return y===null?(this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)])):this.accept([...y,o])}project(e,t,r=this.core.getState()){try{let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=this.deps.projectFor!==void 0?this.deps.projectFor(r,s):this.deps.project!==void 0?this.deps.project(r,t):r;this.visibility===null&&i===r&&this.warnOnce(`store '${this.deps.definition.id}': every player receives the full state. Declare \`visibility: 'open'\` on the definition if that is intended, or rules for what is secret.`);let o=this.visibility===null?i:xe(this.visibility,i,s);if(o===r)return r;try{return this.deps.definition.state(o)}catch(a){throw this.warnOnce(`store '${this.deps.definition.id}': a projection failed the state validator, so the player got empty() \u2014 ${a instanceof Error?a.message:String(a)}`+(this.visibility===null?"":" (a hidden field is the HIDDEN marker: wrap its parser with hiddenOr)")),a}}catch{try{return this.deps.definition.empty()}catch{return null}}}bind(e,t,r){let s=this.handles.get(e);return s===void 0?"handle-unknown":r-s.lastSeen>=Mn?(this.forget(e,"expired"),"handle-expired"):s.peer!==t?"handle-foreign-peer":s}no(e,t,r,s){return{peer:e,h:t,frame:I(s===null?{k:"no",h:t,code:r}:t===null?{k:"no",q:s,code:r}:{k:"no",q:s,h:t,code:r})}}refuse(e,t=[]){return this.counters[e]=(this.counters[e]??0)+1,{out:t,refused:e,deferred:null}}};function cs(n,e){let t=[];for(let r of Object.keys(e)){let s=e[r];if(Object.prototype.hasOwnProperty.call(n,r)&&Object.is(n[r],s))continue;let i=Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0,o=i===void 0?null:eo(r,i,s);if(o!==null){t.push(...o);continue}i!==void 0&&JSON.stringify(i)===JSON.stringify(s)||t.push({o:"r",p:[r],val:s})}for(let r of Object.keys(n))Object.prototype.hasOwnProperty.call(e,r)||t.push({o:"x",p:[r]});return t}var Zi=128;function eo(n,e,t){let r=a=>typeof a=="object"&&a!==null&&!Array.isArray(a);if(!r(e)||!r(t))return null;let s=[],i=Math.min(Zi,Math.max(1,Math.floor(Object.keys(t).length/2))),o=a=>M(a)<=Fe&&!["__proto__","constructor","prototype"].includes(a);for(let a of Object.keys(t)){let l=t[a];if(!(Object.prototype.hasOwnProperty.call(e,a)&&(Object.is(e[a],l)||JSON.stringify(e[a])===JSON.stringify(l)))&&(!o(a)||(s.push({o:"r",p:[n,a],val:l}),s.length>i)))return null}for(let a of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,a)&&(!o(a)||(s.push({o:"x",p:[n,a]}),s.length>i)))return null;return s}function ds(n,e){let t;try{t=I(n)}catch{return null}return M(t)<=e?t:null}function to(n){return"q"in n&&typeof n.q=="string"?n.q:null}var gs=5e3,Wn=500;function lt(n){let e=/^\d+$/.test(n),t=/^(0x)?[0-9a-f]{1,16}$/i.test(n);try{if(e)return BigInt(n).toString(16).padStart(16,"0");if(t)return BigInt(n.startsWith("0x")?n:`0x${n}`).toString(16).padStart(16,"0")}catch{return null}return null}function ct(n){return/^[0-9a-f]{16}$/i.test(n)?n.toLowerCase():lt(n)}var Nn=new WeakMap,Gt=new WeakMap;function no(n){try{let e=JSON.parse(n);return e!==null&&typeof e=="object"&&e.k!=="join"&&typeof e.h=="string"?e.h:null}catch{return null}}var ms=new WeakMap;function dt(n){return ms.get(n)}function hs(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var ys=new TextEncoder,ro=new TextDecoder;function qn(n){let e=n.streamId??`store/${n.definition.id}`,t=n.store??n.definition.id,r=Nn.get(n.transport)??new Set;if(r.has(t))throw new h("invalid-data",`a store named ${t} is already hosted on this transport: name each store of one definition, or a join for that name is ambiguous`);r.add(t),Nn.set(n.transport,r);let s=new at({definition:n.definition,store:t,authorize:n.authorize,project:n.project,projectFor:n.projectFor,onEvent:n.onEvent,areaOf:n.areaOf,warn:n.dev===!0?w=>console.warn(`[@net-mesh/browser] ${w}`):typeof n.dev=="function"?n.dev:void 0,actions:n.actions,inputs:n.inputs,maxEventBytes:n.maxEventBytes,now:n.now??(()=>Date.now()),newHandle:n.newHandle??(()=>hs(16)),newIncarnation:n.newIncarnation??(()=>hs(8)),canProject:n.canProject??(()=>!0)});if(n.definition.visibility!==void 0){let w=xe(Oe(n.definition.visibility),n.initialState,null);try{n.definition.state(w)}catch(k){throw new h("invalid-data",`store '${n.definition.id}': the state validator rejects a view with secrets hidden \u2014 wrap each field a rule hides with hiddenOr(\u2026): ${k instanceof Error?k.message:String(k)}`,{cause:k})}}s.commit(n.initialState);let i=new Map,o=null,a=new Map,l={},c=!1,d=null;async function u(w){let k=i.get(w);if(k!==void 0)return k;let C=a.get(w);if(C!==void 0)return C;let J=Promise.resolve(n.transport.openStream({reliability:"reliable",peer:w,label:e})).then(q=>{if(a.delete(w),c){try{q.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return i.set(w,q),q}).catch(q=>{throw a.delete(w),q});return a.set(w,J),J}async function p(w){for(let k of w){if(c)return;let C=ys.encode(k.frame),N=await u(k.peer);try{await N.send(C)}catch(J){if(c)return;if(!st(J))throw J;if(i.get(k.peer)===N){i.delete(k.peer),a.delete(k.peer),l["reopened-stream"]=(l["reopened-stream"]??0)+1;try{N.close()}catch{}}await(await u(k.peer)).send(C)}}}function y(w){w.catch(()=>{l["send-failed"]=(l["send-failed"]??0)+1})}function f(w){y(p(w.out)),w.deferred!==null&&y(w.deferred.then(k=>f(k))),A()}let b=!1;function A(){if(!(b||c)){b=!0;try{let w=s.drainEvents();w.out.length>0&&y(p(w.out))}finally{b=!1}}}let R=Gt.get(n.transport)??new Set;R.add(s),Gt.set(n.transport,R);let F=n.transport.onEvent(w=>{if(w.type!=="stream_data")return;let k=w.peerNode;if(typeof k!="string"||k.length===0){l["no-authenticated-peer"]=(l["no-authenticated-peer"]??0)+1;return}let C=w.payload;if(C===void 0){l["no-payload"]=(l["no-payload"]??0)+1;return}let N=w.streamId;if(o!==null&&N!==void 0&&N!==o){l["foreign-stream"]=(l["foreign-stream"]??0)+1;return}let J;try{J=ro.decode(C)}catch{l["undecodable-frame"]=(l["undecodable-frame"]??0)+1;return}let q=lt(k);if(q===null){l["unusable-peer"]=(l["unusable-peer"]??0)+1;return}let g=Gt.get(n.transport);if(g!==void 0&&g.size>1){let E=no(J);if(E!==null&&s.handle(E)===void 0){let v=!1;for(let j of g)j!==s&&j.handle(E)!==void 0&&(v=!0);if(v||g.values().next().value!==s){l["sibling-handle"]=(l["sibling-handle"]??0)+1;return}}}let m=s.receive(J,q);N!==void 0&&o===null&&m.refused===null&&(o=N),f(m)}),H=n.schedule??((w,k)=>{let C=setInterval(w,k);return()=>{clearInterval(C)}}),x=H(()=>{if(c)return;let w=(n.now??(()=>Date.now()))(),k=s.sweep(w);k.length>0&&y(p(k.filter(C=>i.has(C.peer)).map(C=>({peer:C.peer,h:C.h,frame:I({k:"no",h:C.h,code:"closed"})})))),f(s.resumeDeferred(w))},gs);async function _(){c=!0,x(),F();let w=s.farewell();await Promise.all(w.map(async k=>{let C=i.get(k.peer);if(C===void 0){l["farewell-unreachable"]=(l["farewell-unreachable"]??0)+1;return}try{await P(Promise.resolve(C.send(ys.encode(k.frame))))}catch{l["farewell-failed"]=(l["farewell-failed"]??0)+1}}));for(let k of i.values())try{k.close()}catch{l["stream-close-failed"]=(l["stream-close-failed"]??0)+1}i.clear(),a.clear(),Nn.get(n.transport)?.delete(t),Gt.get(n.transport)?.delete(s)}function P(w){return new Promise((k,C)=>{let N=()=>{g(),C(new h("timeout","the farewell did not flush before the deadline"))},J=H(N,Wn),q=setTimeout(N,Wn),g=()=>{J(),clearTimeout(q)};w.then(()=>{g(),k()},m=>{g(),C(m instanceof Error?m:new Error(String(m)))})})}let X=n.transport.nodeIdHex()??s.incarnationHex,te=new Set,ae={authority:X,definition:n.definition,getState:()=>s.getState(),subscribe:w=>s.subscribe(w),setState:w=>{f(s.commit(w))},setEntities:(w,k)=>{f(s.commitEntities(w,k))},setEntity:(w,k,C)=>{let N={};Object.defineProperty(N,k,{value:C,enumerable:!0,writable:!0,configurable:!0}),f(s.commitEntities(w,N))},counts:()=>({handles:s.handleCount,ledgers:s.ledgerCount,deferred:s.deferredCount,sparseViews:s.sparseViews}),counters:()=>({...s.snapshotCounters(),...l}),close:()=>{if(d===null){d=_();for(let w of[...te])w();te.clear()}return d}};return ms.set(ae,{owner:s,peer:ct(X)??X,maxEventBytes:n.maxEventBytes,dispatched:f,isClosed:()=>c,onClose:w=>{te.add(w)}}),ae}var bs=3,ut=class{constructor(e){this.deps=e;this.#d=[...e.audience],this.#a=e.interest===void 0?null:[...e.interest]}deps;#e="joining";#t=null;#r=null;#n=null;#s=null;#b=null;#l=0n;#o=null;#u=!1;#c=null;#f=null;#m=0;#h=0;#p=null;#d;#y=0;#O=new it;#w={};#a;get interest(){return this.#a===null?null:[...this.#a]}set interest(e){this.#a=e===null?null:[...e]}get desired(){return[...this.#d]}get waiters(){return this.#y}get state(){return this.#e}get handle(){return this.#t}get installed(){return this.#n===null?null:this.#n.toString()}get revision(){return this.#s===null?null:this.#s.toString()}get retired(){return this.#l.toString()}get skipped(){return this.#o===null?null:this.#o.toString()}get dropped(){return{...this.#w}}join(){if(this.#e==="closed")throw new h("closed","a closed replica cannot join again");this.#h+=1,this.#y=1,this.#k();let e=this.deps.newQ();return this.#c=e,this.#f=this.deps.now(),this.#m=0,this.#e="joining",this.deps.core.setStatus({phase:"connecting",stale:this.#v()}),{kind:"join",q:e,frame:I({k:"join",q:e,def:this.deps.definition.id,store:this.deps.store,ver:this.deps.definition.version,key:this.deps.key,aud:[...this.#d],...this.#a===null?{}:{int:[...this.#a]}})}}setAudience(e){if(this.#e==="closed")throw new h("closed","a closed replica cannot change audience");this.#h+=1;let t=[...e];if(this.#e==="installing"&&io(t,this.#d))return this.#y+=1,[];this.#d=t;let r=this.#t;if(this.#g(),this.#n=null,this.#s=null,this.#o=null,this.#u=!1,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:"syncing",stale:!1,error:null}),r===null)return this.#y=1,[this.join()];let s=this.deps.newQ();return this.#c=s,this.#f=this.deps.now(),this.#y=1,this.#e="installing",[{kind:"aud",q:s,frame:I({k:"aud",q:s,h:r,aud:t})}]}reconnect(){if(this.#e==="closed")throw new h("closed","a closed replica cannot reconnect");this.#h+=1;let e=this.#t;if(this.#g(),e===null)return[this.join()];let t=this.deps.newQ();return this.#c=t,this.#e="installing",this.deps.core.setStatus({phase:"reconnecting",stale:this.#v()}),[{kind:"resume",q:t,frame:I({k:"resume",q:t,h:e,aud:[...this.#d],...this.#a===null?{}:{int:[...this.#a]}})}]}cancelWaiter(){this.#y>0&&(this.#y-=1),!(this.#y>0)&&this.#e==="installing"&&this.cancel()}receive(e){if(this.#e==="closed")return this.#i("closed");let t=ke(e,{maxBytes:this.deps.maxEventBytes,as:"replica"});if(!t.ok)return this.#i(t.reason);let r=t.message;if("h"in r&&r.h!==void 0&&this.#t!==null&&r.h!==this.#t)return this.#i("foreign-handle");switch(r.k){case"man":return this.#A(r);case"snap":return this.#R(r);case"delta":return this.#P(r);case"no":return this.#I(r.code,r.q);case"ok":case"res":return this.#i("unimplemented-kind")}}tick(){let e=this.deps.now();if(this.#e==="installing"&&this.#p!==null)return this.#p.expired(e)?this.#E("assembly-deadline"):[];if(this.#f===null||e-this.#f<Ft)return[];if(this.#e!=="joining"&&this.#e!=="installing")return[];if(this.#m>=bs)return this.#f=null,this.#e="fenced",this.#c=null,this.#g(),this.#S("failed",new h("timeout",`no store named ${this.deps.store} answered the join`)),[];let t=this.#m,r=this.join();return this.#m=t+1,[r]}cancel(){this.#e!=="closed"&&(this.#h+=1,this.#g(),this.#c=null,this.#e="fenced",this.#o=null,this.#u=!1,this.#S("failed"))}#A(e){let t=oe(e.g),r=e.q!==void 0&&e.q===this.#c;if(e.q!==void 0&&!r)return this.#i("stale-correlation");if(t<=this.#l)return this.#i("stale-generation");if(r){if(this.#e!=="joining"&&this.#e!=="installing"&&this.#e!=="fenced")return this.#i("unexpected-manifest")}else{if(this.#e==="fenced")return this.#i("fenced");if(this.#e!=="ready")return this.#o=this.#o===null?t:so(this.#o,t),this.#i("mid-transition")}if(this.#t===null)this.#t=e.h,this.#r=e.inc;else if(this.#r!==null&&e.inc!==this.#r)return this.#i("foreign-incarnation");this.#g(),this.#l=t;let s={h:e.h,g:e.g,r:e.r,n:e.n,bytes:e.bytes},i=this.#O.open(s,this.deps.now());return"accept"in i?(this.#b=t,this.#p=i,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),{out:[],dropped:null}):{out:this.#E(i.reason),dropped:i.reason}}#R(e){let t=this.#p;if(t===null)return this.#i("no-open-assembly");let r=this.#h,s=t.accept({h:e.h,g:e.g,r:e.r,n:e.n,i:e.i,d:e.d},i=>this.deps.definition.state(i),this.deps.now());return this.#h!==r?this.#i("superseded-installation"):s.ok?s.done?this.#_(s.document,e.g,e.r,r):{out:[],dropped:null}:s.fatal?{out:this.#E(s.reason),dropped:s.reason}:this.#i(s.reason)}#_(e,t,r,s){return this.deps.core.applySnapshot(e),this.#b=null,this.#p=null,this.#O.reclaim(this.#t,t),this.#h!==s?(this.#n=null,this.#s=null,this.#S("failed"),this.#i("superseded-installation")):(this.#n=oe(t),this.#s=oe(r),this.#c=null,this.#e="ready",this.deps.core.setStatus({phase:"ready",stale:!1,error:null}),{out:this.#C(),dropped:null})}#P(e){if(this.#e!=="ready")return this.#u=!0,this.#i("not-ready");let t=oe(e.g),r=this.#n;if(r===null||t!==r)return r!==null&&t>r?{out:this.#x("generation-ahead"),dropped:"generation-ahead"}:this.#i("stale-generation");if(this.#s===null||oe(e.base)!==this.#s)return{out:this.#x("gap"),dropped:"gap"};let s=this.deps.core.applyDelta(e.ops);return s.ok?(this.#s=oe(e.r),{out:[],dropped:null}):{out:this.#x(s.reason),dropped:s.reason}}#I(e,t){if(e==="owner-lost")return this.#g(),this.#e="closed",this.#t=null,this.#S("closed"),{out:[],dropped:"owner-lost"};if(e==="closed"){let r=this.#e==="fenced";return this.#k(),r?(this.#S("failed"),{out:[],dropped:"closed-while-fenced"}):(this.#S("connecting"),{out:[this.join()],dropped:"closed"})}return t===void 0||t!==this.#c?this.#i("stale-correlation"):(this.#g(),this.#c=null,this.#e="fenced",this.#S("failed",new h(e,`the request was refused: ${e}`)),{out:[],dropped:`refused-${e}`})}#E(e){return this.#g(),this.#b=null,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),this.#x(e)}#x(e){let t=this.#t;if(t===null)return[];let r=this.deps.newQ();return this.#c=r,this.#f=this.deps.now(),this.#e="installing",this.#o=null,this.#u=!1,this.deps.core.setStatus({phase:this.#v()?"reconnecting":"syncing",stale:this.#v()}),[{kind:"resync",q:r,frame:I({k:"resync",q:r,h:t,g:this.#n===null?"0":this.#n.toString(),have:this.#s===null?"0":this.#s.toString()})}]}#C(){let e=this.#o,t=this.#u;return!t&&(e===null||this.#n===null||e<=this.#n)?(this.#o=null,this.#u=!1,[]):this.#x(t?"behind":"skipped-refresh")}#k(){this.#g(),this.#t=null,this.#r=null,this.#n=null,this.#s=null,this.#l=0n,this.#o=null,this.#u=!1,this.#c=null}#g(){this.#p!==null&&(this.#p.reclaim(),this.#p=null),this.#t!==null&&this.#O.reclaimHandle(this.#t),this.#b=null}#v(){return this.#n!==null}#S(e,t=null){this.#n=null,this.#s=null,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:e,stale:!1,error:t})}#i(e){return this.#w[e]=(this.#w[e]??0)+1,{out:[],dropped:e}}};function so(n,e){return n>e?n:e}function io(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var ws=2e4,Un=1e4,vs=6e4,Os=1e3,Bn=64,Ss=new TextEncoder,oo=new TextDecoder;function pt(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function $n(n){let e=n.transport.nodeIdHex(),t=ct(n.host);if(e!==null&&t!==null&&ct(e)===t)throw new h("invalid-data","a replica cannot join the node it runs on: hold the hostStore handle instead");let r=n.streamId??`store/${n.definition.id}`,s=n.now??(()=>Date.now()),i=n.schedule??((g,m)=>{let E=setInterval(g,m);return()=>{clearInterval(E)}}),o=new ge({definition:n.definition,initialState:n.definition.empty()}),a=new ut({definition:n.definition,core:o,maxEventBytes:n.maxEventBytes,now:s,newQ:()=>(n.newQ??(()=>pt(8)))(),audience:n.audience,store:n.store??n.definition.id,key:n.key,...n.interest===void 0?{}:{interest:n.interest}}),l=new Map,c=new Map,d=0n,u=!1,p=null,y=null,f=[],b=null;async function A(){return p!==null?p:y!==null?y:t===null?Promise.reject(new h("invalid-data",`the host id is not a node id: ${n.host}`)):(y=Promise.resolve(n.transport.connectPeer?.(t)).catch(()=>{}).then(()=>n.transport.openStream({reliability:"reliable",peer:t,label:r})).then(g=>{if(y=null,u){try{g.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return p=g,g}).catch(g=>{throw y=null,g}),y)}async function R(g){for(let m of g){if(u)return;let E=Ss.encode(m),v=await A();try{await v.send(E)}catch(j){if(u)return;if(!st(j))throw j;if(p===v){p=null,y=null;try{v.close()}catch{}}await(await A()).send(E)}}}function F(g){let m=g instanceof h?g:new h("indeterminate",`the transport could not carry a store frame: ${String(g)}`);for(let E of f.splice(0,f.length))E.reject(m);P(m);for(let[E,v]of[...l])l.delete(E),v.reject(m)}function H(g){R(g).catch(F)}let x=g=>g.map(m=>m.frame);function _(g){if(a.state==="ready"){P(null);for(let E of f.splice(0,f.length))E.resolve();return}if(a.state!=="fenced"&&a.state!=="closed")return;let m=g??new h(a.state==="closed"?"owner-lost":"aborted",`the store handle is ${a.state}`);P(m);for(let E of f.splice(0,f.length))E.reject(m)}function P(g){let m=b;if(m!==null){b=null,m.q!==null&&l.delete(m.q);for(let E of[...m.calls])m.calls.delete(E),g===null?E.resolve():E.reject(g)}}function X(g){return P(new h("aborted","a newer transition superseded this one before it installed")),b={q:g,calls:new Set},g===null?null:l.size>=Bn?new h("capacity","too many requests are already outstanding"):(l.set(g,{resolve:()=>P(null),reject:m=>P(m),at:s(),transition:!0}),null)}function te(){return new Promise((g,m)=>{let E={resolve:g,reject:m,deadlineAt:s()+vs},v=b??{q:null,calls:new Set};b=v,v.calls.add(E)})}let ae=n.transport.onEvent(g=>{if(u||g.type!=="stream_data"||typeof g.peerNode!="string"||t===null||lt(g.peerNode)!==t)return;let m=g.payload;if(m===void 0)return;let E=oo.decode(m),v=ke(E,{maxBytes:n.maxEventBytes,as:"replica"});if(v.ok&&"q"in v.message&&typeof v.message.q=="string"){let Y=l.get(v.message.q);if(Y!==void 0&&(v.message.k==="res"||v.message.k==="ok")){l.delete(v.message.q),Y.resolve(v.message.k==="res"?v.message.out:void 0);return}Y!==void 0&&v.message.k==="no"&&(l.delete(v.message.q),Y.reject(new h(v.message.code,`the store refused: ${v.message.code}`)))}let j=null;v.ok&&v.message.k==="no"&&(j=new h(v.message.code,`the store refused: ${v.message.code}`));let V=a.receive(E);H(x(V.out)),_(j)}),w=i(()=>{if(u)return;let g=a.handle;g!==null&&H([I({k:"alive",q:pt(8),h:g})])},ws),k=i(()=>{if(u)return;let g=s(),m=b;if(m!==null){for(let E of[...m.calls])g<E.deadlineAt||(m.calls.delete(E),a.cancelWaiter(),E.reject(new h("indeterminate","the transition did not install before its deadline")));m.q!==null&&m.calls.size===0&&P(null)}for(let[E,v]of[...l])v.transition||g-v.at<Un||(l.delete(E),v.reject(new h("indeterminate","the store did not answer before the deadline")))},Un),C=i(()=>{u||(H(x(a.tick())),_(o.getStatus().error??null))},Os),N;try{N=a.join()}catch(g){throw new h("invalid-data","the join request cannot be encoded",{cause:g})}X(null),H(x([N]));function J(g){return l.size>=Bn?Promise.reject(new h("capacity","too many requests are already outstanding")):new Promise((m,E)=>{l.set(g,{resolve:v=>{m(v)},reject:E,at:s(),transition:!1})})}let q={getState:()=>o.getState(),subscribe:g=>o.subscribe(g),getStatus:()=>o.getStatus(),subscribeStatus:g=>o.subscribeStatus(g),ready:()=>new Promise((g,m)=>{if(u){m(new h("closed","this store handle is closed"));return}if(a.state==="ready"){g();return}if(a.state==="closed"){m(new h("owner-lost","the store owner closed this handle"));return}f.push({resolve:g,reject:m})}),act:async(g,m)=>{if(u)throw new h("closed","this store handle is closed");if(a.state==="closed")throw new h("owner-lost","the store owner closed this handle");let E=a.handle;if(E===null)throw new h("not-ready","no handle yet: the join has not been answered");d+=1n;let v=(n.newQ??(()=>pt(8)))(),j;try{j=I({k:"act",q:v,h:E,s:d.toString(),name:g,in:m})}catch(Y){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:Y})}let V=J(v);return V.catch(()=>{}),await R([j]),await V},input:(g,m)=>{if(u)return{type:"dropped",reason:"not-ready"};let E=a.handle;if(E===null||a.state!=="ready")return{type:"dropped",reason:"not-ready"};let v=(c.get(g)??0n)+1n;c.set(g,v);let j;try{j=I({k:"in",h:E,s:v.toString(),name:g,in:m})}catch(V){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:V})}return H([j]),{type:v===1n?"queued":"replaced"}},setAudience:async g=>{if(u)throw new h("closed","this store handle is closed");let m;try{m=a.setAudience(g)}catch(j){throw new h("invalid-data","the audience cannot be encoded",{cause:j})}let E=m[0];if(E!==void 0){let j=X(E.q);if(j!==null)throw j}let v=te();v.catch(()=>{}),E!==void 0&&await R(x(m)),await v},setInterest:async g=>{if(u)throw new h("closed","this store handle is closed");let m=[...g],E="0".repeat(32),v;try{v=I({k:"int",q:"0".repeat(16),h:E,int:m})}catch(Je){throw new h("invalid-data","the interest set cannot be encoded",{cause:Je})}if(M(v)>n.maxEventBytes)throw new h("capacity","the interest set does not fit one message");a.interest=m;let j=a.handle;if(j===null||a.state!=="ready")return await q.ready(),a.interest===null||a.interest.join("\0")!==m.join("\0")?void 0:q.setInterest(m);let V=(n.newQ??(()=>pt(8)))(),Y=J(V);Y.catch(()=>{}),await R([I({k:"int",q:V,h:j,int:m})]),await Y},reconnect:async()=>{if(u)throw new h("closed","this store handle is closed");p=null,y=null;let g;try{g=a.reconnect()}catch(m){throw new h("invalid-data","the reconnect request cannot be encoded",{cause:m})}g[0]!==void 0&&X(null),await R(x(g))},close:async()=>{if(u)return;u=!0,w(),k(),C();let g=a.handle;if(g!==null)try{await(await A()).send(Ss.encode(I({k:"leave",q:pt(8),h:g})))}catch{}ae(),P(new h("aborted","the store handle closed before this request was answered"));for(let m of l.values())m.reject(new h("aborted","the store handle closed before this request was answered"));l.clear();for(let m of f.splice(0,f.length))m.reject(new h("closed","the store handle closed before a view was installed"));p?.close(),p=null,o.close()}};return q}var Es="0".repeat(16),Fn="0".repeat(32);function xs(n,e,t){let r;try{r=t==="act"?I({k:"act",q:Es,h:Fn,s:"1",name:n,in:e}):I({k:"in",h:Fn,s:"1",name:n,in:e})}catch(i){throw new h("invalid-data",`the input for '${n}' cannot be encoded`,{cause:i})}let s=Ee(r);if(!s.ok||typeof s.value!="object"||s.value===null||Array.isArray(s.value))throw new h("invalid-data",`the input for '${n}' cannot be encoded`);return s.value.in}function ao(n){let e=Ee(JSON.stringify(n));return e.ok?e.value:n}function Jn(n,e){let t=dt(n);if(t===void 0)throw new h("invalid-data","hostPlayer needs a handle returned by hostStore");let{owner:r,peer:s}=t,i=n.definition,o=new ge({definition:i,initialState:i.empty(),phase:"syncing"}),a=[...e.audience],l=e.interest===void 0?null:[...e.interest],c=!1,d=!1,u=new Map;function p(x,_){d=!0,_?.code==="forbidden"&&queueMicrotask(()=>A("refused")),o.applySnapshot(i.empty()),o.setStatus({phase:x,stale:!1,error:_})}function y(){if(c||d)return;if(t.isClosed()){p("closed",null);return}if(!r.localRead(s,a)){p("failed",new h("forbidden","the store refused: forbidden"));return}let x=r.localView(s,a,l);if(x===null){p("failed",new h("capacity","the store refused: capacity"));return}o.applySnapshot(x),o.setStatus({phase:"ready",stale:!1,error:null})}let f=r.subscribe(()=>{y()});t.onClose(()=>{f(),!c&&!d&&p("closed",null)}),y();let b=!1;o.getStatus().phase==="ready"&&(b=!0,r.localPresence(s,!0,a),t.dispatched({out:[],refused:null,deferred:null}));function A(x){!b||t.isClosed()||(b=!1,r.localPresence(s,!1,a,x),t.dispatched({out:[],refused:null,deferred:null}))}function R(){return c?new h("closed","this store handle is closed"):t.isClosed()?new h("owner-lost","the store owner closed this handle"):d?o.getStatus().error??new h("owner-lost","the store owner closed this handle"):null}function F(){let x=[...u];if(u.clear(),R()===null)for(let[_,P]of x)t.dispatched(r.localInput(_,P,s))}function H(x,_,P){return _===void 0?o.subscribe(x):o.subscribe(x,_,P)}return{getState:()=>o.getState(),subscribe:H,getStatus:()=>o.getStatus(),subscribeStatus:x=>o.subscribeStatus(x),ready:()=>{let x=o.getStatus();return x.phase==="ready"?Promise.resolve():Promise.reject(x.error??new h(c?"closed":"owner-lost","this store handle is not ready"))},act:async(x,_)=>{let P=R();if(P!==null)throw P;let X=xs(x,_,"act");await Promise.resolve();let te=R();if(te!==null)throw te;let{outcome:ae,dispatched:w}=r.localAct(x,X,s);if(t.dispatched(w),ae.kind==="refusal")throw new h(ae.code,`the store refused: ${ae.code}`);return ao(ae.out)},input:(x,_)=>{if(R()!==null||o.getStatus().phase!=="ready")return{type:"dropped",reason:"not-ready"};let P=xs(x,_,"in"),X=u.size===0,te=u.has(x);return u.set(x,P),X&&queueMicrotask(F),{type:te?"replaced":"queued"}},setAudience:async x=>{let _=R();if(_!==null)throw _;try{I({k:"aud",q:Es,h:Fn,aud:[...x]})}catch(X){throw new h("invalid-data","the audience cannot be encoded",{cause:X})}await Promise.resolve();let P=R();if(P!==null)throw P;if(!r.localRead(s,x))throw new h("forbidden","the store refused: forbidden");a=[...x],y()},setInterest:async x=>{let _=R();if(_!==null)throw _;let P=[...x];await Promise.resolve(),l=P,y()},reconnect:()=>Promise.resolve(),close:()=>(c||(c=!0,A("left"),u.clear(),f(),o.close()),Promise.resolve())}}var fe=class extends Error{constructor(t,r){super(r);this.code=t;this.name="InventoryError"}code},Vn=64,Kn=Object.freeze({});function lo(){return Kn}function ks(n){if(typeof n!="string"||n.length===0||n.length>Vn||n==="__proto__")throw new fe("invalid",`an item id is 1-${Vn} characters, got ${JSON.stringify(n)}`)}function As(n){if(!Number.isSafeInteger(n)||n<1)throw new fe("invalid",`a count is a whole number of at least 1, got ${String(n)}`)}function co(n,e){let t=e?.maxCount;return t===void 0?Number.MAX_SAFE_INTEGER:typeof t=="number"?t:Object.prototype.hasOwnProperty.call(t,n)?t[n]:Number.MAX_SAFE_INTEGER}function Yt(n,e){return n===void 0||!Object.prototype.hasOwnProperty.call(n,e)?0:n[e]??0}function uo(n,e,t=1){return Yt(n,e)>=t}function Rs(n,e,t,r){ks(e),As(t);let s=Yt(n,e),i=s+t;if(!Number.isSafeInteger(i)||i>co(e,r))throw new fe("full",`no room for ${String(t)} more ${e}`);if(s===0&&r?.maxKinds!==void 0&&Object.keys(n).length>=r.maxKinds)throw new fe("full",`no room for another kind of item (${String(r.maxKinds)} at most)`);return Object.freeze({...n,[e]:i})}function po(n,e,t){ks(e),As(t);let r=Yt(n,e);if(r<t)throw new fe("insufficient",`has ${String(r)} ${e}, needs ${String(t)}`);let s={...n};return r===t?delete s[e]:s[e]=r-t,Object.freeze(s)}function fo(n,e){if(typeof n!="object"||n===null||Array.isArray(n))throw new fe("invalid","an inventory is an object of item id \u2192 count");let t=Kn;for(let[r,s]of Object.entries(n)){if(typeof s!="number")throw new fe("invalid",`the count of ${r} is not a number`);t=Rs(t,r,s,e)}return t}function ho(n,e){return Object.prototype.hasOwnProperty.call(n,e)?n[e]:Kn}function yo(n,e){return Object.prototype.hasOwnProperty.call(n,e)?{[e]:n[e]}:{}}function _s(n){if(!(n>0)||!Number.isFinite(n))throw new RangeError(`a cell size is a positive number, got ${String(n)}`)}function go(n,e,t){return _s(t),`${String(Math.floor(n/t))}:${String(Math.floor(e/t))}`}function mo(n){let e=/^(-?\d+):(-?\d+)$/.exec(n);return e===null?null:[Number(e[1]),Number(e[2])]}function Ps(n,e,t){_s(t.size);let r=t.radius??1,s=Math.floor(n/t.size),i=Math.floor(e/t.size),o=[`${String(s)}:${String(i)}`];for(let a=-r;a<=r;a+=1)for(let l=-r;l<=r;l+=1)(a!==0||l!==0)&&o.push(`${String(s+a)}:${String(i+l)}`);return o}function bo(n,e,t,r){let s=Ps(e,t,r),o=(r.radius??1)+(r.margin??1),a=Math.floor(e/r.size),l=Math.floor(t/r.size),c=new Set(s);for(let d of n){if(c.has(d))continue;let u=mo(d);u!==null&&Math.abs(u[0]-a)<=o&&Math.abs(u[1]-l)<=o&&(s.push(d),c.add(d))}return s}function So(n,e){if(n.length!==e.length)return!1;let t=new Set(n);return e.every(r=>t.has(r))}var $=class extends Error{constructor(t,r){super(r);this.code=t;this.name="LobbyError"}code},Is=64,Cs=256,Xn=512,js=256,Qt="ABCDEFGHJKMNPQRSTUVWXYZ23456789",zn=6,Ls=2e3,Ts=8104,wo=/^[a-z0-9][a-z0-9._-]{0,63}$/,Ds=1,ft=new TextEncoder,vo=new TextDecoder;function Gn(n){if(!wo.test(n))throw new $("invalid",`a game name is 1-64 of a-z 0-9 . _ - (starting with a letter or digit), got ${JSON.stringify(n)}`)}function Yn(n){let e=n.toUpperCase().replace(/[\s-]/g,"");if(e.length!==zn||[...e].some(t=>!Qt.includes(t)))throw new $("invalid",`not a lobby code: ${JSON.stringify(n)}`);return e}function Oo(){let n=256-256%Qt.length,e="";for(;e.length<zn;){let t=new Uint8Array(16);crypto.getRandomValues(t);for(let r of t)r<n&&e.length<zn&&(e+=Qt[r%Qt.length])}return e}function xo(n,e){return`net-lobby:${n}:seek:${e}`}function Ms(n){return`net-lobby:${n}`}function Qn(n){return`net-lobby:${n}:rec:`}async function Ns(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft.encode(`net-lobby${n}${e}`))),r="";for(let s of t.subarray(0,16))r+=s.toString(16).padStart(2,"0");return`net-lobby:${n}:code:${r}`}function Eo(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ko(n){if(!/^[A-Za-z0-9_-]*$/.test(n))return null;try{let e=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(e,t=>t.charCodeAt(0))}catch{return null}}function Ws(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new $("invalid","lobby info is a flat object of strings, numbers and booleans");let e={};for(let[t,r]of Object.entries(n)){if(typeof r=="number"?!Number.isFinite(r):typeof r!="string"&&typeof r!="boolean")throw new $("invalid",`lobby info.${t} must be a string, a finite number or a boolean`);e[t]=r}if(ft.encode(JSON.stringify(e)).length>Cs)throw new $("invalid",`lobby info is over ${Cs} bytes of JSON`);return Object.freeze(e)}function qs(n){if(typeof n!="string"||n.trim().length===0||[...n].length>Is)throw new $("invalid",`a lobby name is 1-${Is} characters`);return n}function Us(n){if(typeof n!="number"||!Number.isInteger(n)||n<1||n>js)throw new $("invalid",`capacity is a whole number from 1 to ${js}`);return n}function Hs(n,e){let t=JSON.stringify({v:Ds,c:e.code,n:e.name,p:e.players,m:e.capacity,s:e.store,i:e.info}),r=Qn(n)+Eo(ft.encode(t));if(ft.encode(r).length>Xn)throw new $("invalid",`the lobby record is over ${Xn} bytes: shorten the name or info`);return r}function Ao(n,e){if(ft.encode(e).length>Xn)return null;let t=ko(e.slice(Qn(n).length));if(t===null)return null;let r;try{r=JSON.parse(vo.decode(t))}catch{return null}if(typeof r!="object"||r===null)return null;let s=r;try{if(s.v!==Ds||typeof s.c!="string"||typeof s.s!="string"||s.s.length>200)return null;let i=Us(s.m),o=s.p;return typeof o!="number"||!Number.isInteger(o)||o<0||o>i?null:{code:Yn(s.c),name:qs(s.n),players:o,capacity:i,store:s.s,info:Ws(s.i??{})}}catch{return null}}function Zt(n){let e=n.startsWith("0x")?n.slice(2):n;if(/^[0-9a-fA-F]{1,16}$/.test(e))return e.toLowerCase().padStart(16,"0");throw new $("invalid",`not a peer id: ${JSON.stringify(n)}`)}async function ec(n){let{node:e,game:t}=n;Gn(t);let r=qs(n.name),s=Us(n.capacity),i=Ws(n.info??{}),o=n.visibility??"public",a=Oo(),l=`${n.definition.id}@${n.definition.version}`,c=await Ns(t,a);Hs(t,{code:a,name:r,players:s,capacity:s,store:l,info:i});let d=e.nodeIdHex();if(d===null)throw new $("invalid","the node has no id yet: connect it before opening a lobby");let u=Zt(d),p=new Set,y=n.authorize??(()=>!0),f=()=>[],b=W=>{let ne=W.peer;return p.has(ne)||W.type==="read"&&ne!==u&&!f().includes(ne)&&1+f().filter(zs=>zs!==u).length>=s?!1:y(W)},{audience:A,tags:R,announceEveryMs:F,maxEventBytes:H}=n,{node:x,game:_,name:P,capacity:X,visibility:te,info:ae,audience:w,tags:k,announceEveryMs:C,maxEventBytes:N,authorize:J,...q}=n,g=qn({...q,transport:e,maxEventBytes:H??Ts,authorize:b}),m=dt(g);f=()=>m.owner.peers();let E=Jn(g,{audience:A??[]});function v(){return[u,...m.owner.peers().filter(W=>W!==u)]}let j=new Set,V=!1,Y=null,Je=!1;function Vs(){let W=[...R??[],c];return o==="public"&&W.push(Ms(t),Hs(t,{code:a,name:r,players:v().length,capacity:s,store:l,info:i})),W}function ht(){if(!V){if(Y!==null){Je=!0;return}Y=e.announce(Vs()).catch(()=>{}).finally(()=>{Y=null,Je&&(Je=!1,ht())})}}let Zn=v().join(),Ks=m.owner.onMembership(()=>{queueMicrotask(()=>{if(V)return;let W=v();if(W.join()!==Zn){Zn=W.join(),ht();for(let ne of[...j])try{ne(W)}catch{}}})});ht();let Xs=setInterval(ht,F??Ls);return{code:a,game:t,visibility:o,host:g,self:E,players:v,subscribePlayers:W=>(j.add(W),()=>{j.delete(W)}),link:W=>{let ne=new URL(W??globalThis.location?.href??"about:blank");return ne.searchParams.set("lobby",a),ne.toString()},kick:W=>{let ne=Zt(W);if(ne===u)throw new $("invalid","the host cannot kick itself; close the lobby instead");p.add(ne),m.dispatched(m.owner.reauthorize())},close:async()=>{V||(V=!0,clearInterval(Xs),Ks(),j.clear(),await E.close(),await g.close(),await e.announce([...R??[]]).catch(()=>{}))}}}async function tc(n){Gn(n.game);let e=Qn(n.game),t=[],r=new Set;for(let s of await n.node.query(Ms(n.game))){if(r.has(s.peerIdHex))continue;let i=s.capabilities.find(a=>a.startsWith(e));if(i===void 0)continue;let o=Ao(n.game,i);o!==null&&(r.add(s.peerIdHex),t.push({...o,host:s.peerIdHex}))}return t}async function nc(n){Gn(n.game);let e;if(n.lobby!==void 0)e=Zt(n.lobby.host);else if(n.code!==void 0){let p=await Ns(n.game,Yn(n.code)),y=Date.now()+(n.timeoutMs??2e4),f=[];for(;f=[...new Set((await n.node.query(p)).map(b=>b.peerIdHex))],!(f.length>0||Date.now()>=y);)await new Promise(b=>setTimeout(b,250));if(f.length===0)throw new $("not-found",`no lobby answered to code ${n.code}`);if(f.length>1)throw new $("ambiguous",`${f.length} nodes claim code ${n.code}; join from the list instead`);e=f[0]}else throw new $("invalid","joinLobby needs a code or a lobby");let t=n.node.nodeIdHex();if(t!==null&&Zt(t)===e)throw new h("invalid-data","this node hosts that lobby: use lobby.self to play in it");let r=n.node,s=[...n.tags??[]],i=[...s,xo(n.game,e)],o=!1,a=()=>{o||r.announce(i).catch(()=>{})};a();let l=setInterval(a,Ls),c=()=>{o||(o=!0,clearInterval(l),r.announce(s).catch(()=>{}))};if(r.connectPeer!==void 0){let p=Date.now()+(n.timeoutMs??2e4);for(;;)try{await r.connectPeer(e);break}catch(y){if(Date.now()>=p)throw c(),new $("not-found",`could not reach the lobby's host ${e}: ${String(y?.message??y)}`);await new Promise(f=>setTimeout(f,500))}}let d;try{d=$n({definition:n.definition,transport:r,host:e,audience:n.audience??[],key:n.key??"player",maxEventBytes:n.maxEventBytes??Ts,...n.interest===void 0?{}:{interest:n.interest}})}catch(p){throw c(),p}let u=d.close.bind(d);return d.close=async()=>{c(),await u()},d}function rc(n){try{let e=new URL(n??globalThis.location?.href??"").searchParams.get("lobby");return e===null?null:Yn(e)}catch{return null}}var Fs="net-mesh:identity";function Bs(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var $s=/^[0-9a-f]{64}$/;function Ro(n){if(n===null)return null;try{let e=JSON.parse(n);if(typeof e.entitySecretHex=="string"&&typeof e.noiseSecretHex=="string"&&$s.test(e.entitySecretHex)&&$s.test(e.noiseSecretHex))return{entitySecretHex:e.entitySecretHex,noiseSecretHex:e.noiseSecretHex}}catch{}return null}function _o(n=Fs,e){let t=e;try{t??=globalThis.localStorage}catch{t=void 0}let r=null;try{r=Ro(t?.getItem(n)??null)}catch{t=void 0}if(r!==null)return r;let s={entitySecretHex:Bs(32),noiseSecretHex:Bs(32)};try{t?.setItem(n,JSON.stringify(s))}catch{}return s}var qe=class extends Error{constructor(t,r,s=null){super(r);this.kind=t;this.status=s}kind;status;name="CredentialRequestError"},Js={unknown_game:"unknown-game",rate_limited:"rate-limited",malformed_request:"malformed-request"};async function Po(n){let e=n.fetch??globalThis.fetch;if(typeof e!="function")throw new qe("unreachable","requestCredential needs fetch");let t=`${n.anchorUrl.replace(/\/+$/,"")}/credential`,r;try{r=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({game:n.game}),...n.signal===void 0?{}:{signal:n.signal}})}catch(o){throw n.signal?.aborted?o:new qe("unreachable",`could not reach ${t}: ${String(o)}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){let o=s?.refusal,a=s?.message,l=typeof o=="string"&&o in Js?Js[o]:r.status===404?"unreachable":"unexpected",c=l==="unreachable"?`${t} issues no credentials (is the anchor started with --game?)`:typeof a=="string"?a:`the anchor answered ${r.status}`;throw new qe(l,c,r.status)}let i=s;if(typeof i?.credentialB64!="string"||typeof i.bootstrapUrl!="string"||typeof i.game!="string")throw new qe("unexpected","the anchor answered without a credential",r.status);return{credentialB64:i.credentialB64,bootstrapUrl:i.bootstrapUrl,game:i.game}}export{ws as ALIVE_INTERVAL_MS,Ft as ASSEMBLY_DEADLINE_MS,$t as Assembly,it as AssemblyTable,Ae as AsyncQueue,os as BINDING_INLINE_MAX_BYTES,Pt as BrowserNode,Wr as CALLER_KINDS,gt as ControlPlaneError,qe as CredentialRequestError,Fs as DEFAULT_IDENTITY_KEY,je as EventHub,Wn as FAREWELL_DEADLINE_MS,Qr as FORBIDDEN_SEGMENTS,G as HANDLE_HEX_LENGTH,Mn as HANDLE_LEASE_MS,Lt as HIDDEN,gs as HOST_SWEEP_MS,Kt as HandleLedger,Nt as INCARNATION_HEX_LENGTH,mt as IceServerConflictError,be as IdentityError,Xt as InputSequences,fe as InventoryError,Rn as LARGEST_FROZEN_ENVELOPE,is as LEDGER_MAX_AGE_MS,ss as LEDGER_MAX_BYTES,rs as LEDGER_MAX_ENTRIES,Ls as LOBBY_ANNOUNCE_MS,Qt as LOBBY_CODE_ALPHABET,zn as LOBBY_CODE_LENGTH,z as LeafError,De as LeafStream,ot as LedgerTable,$ as LobbyError,Vr as MAX_ASSEMBLY_BYTES_TOTAL,Hr as MAX_AUDIENCE_LABELS,Lr as MAX_AUDIENCE_LABEL_BYTES,Nr as MAX_DECIMAL,Mr as MAX_DETAIL_BYTES,fs as MAX_EVENT_ROUNDS,ps as MAX_HANDLES,Tr as MAX_INTEREST_KEYS,Dr as MAX_INTEREST_KEY_BYTES,Vn as MAX_ITEM_ID_CHARS,bs as MAX_JOIN_REASKS,Hi as MAX_JSON_DEPTH,js as MAX_LOBBY_CAPACITY,Cs as MAX_LOBBY_INFO_BYTES,Is as MAX_LOBBY_NAME_CHARS,Xn as MAX_LOBBY_RECORD_TAG_BYTES,Bn as MAX_OUTSTANDING,Wt as MAX_PATCH_OPS,qt as MAX_PATH_SEGMENTS,Fe as MAX_PATH_SEGMENT_BYTES,us as MAX_PENDING_ACTIONS,as as MAX_SEQUENCE,ye as MAX_SNAPSHOT_BYTES,ie as MAX_SNAPSHOT_CHUNKS,An as MIN_CHUNK_BYTES,Ht as MeshSession,on as NO_ANNOUNCEMENT_PREFIX,dr as NO_LIVE_ATTEMPT_PREFIX,ur as NO_OFFER_PREFIX,bt as NotLeaderError,Ys as ORG_SINK_BUDGET_REFUSAL,Ot as ORG_SINK_CLOSED_REFUSAL,Qs as ORG_UPLOAD_SINK_BUDGET_REFUSAL,Gs as ORG_UPLOAD_SINK_CLOSED_REFUSAL,qr as OWNER_KINDS,he as OrgAdmissionDeniedError,D as OrgCancelledError,Te as OrgDuplex,He as OrgHandleRegistry,Ve as OrgIndeterminateError,Re as OrgInternalError,ee as OrgLeaderLostError,Be as OrgMalformedError,Ke as OrgRefusedError,ze as OrgRequests,Pe as OrgRevokedError,Q as OrgServe,Ce as OrgSessionLostError,Xe as OrgSink,we as OrgStream,Z as OrgStreamError,Ie as OrgTimeoutError,Le as OrgUpload,hr as PEER_OFFER_WAIT_MS,fr as PEER_TICK_MS,Me as PeerAttempts,pr as REPLACED_ATTEMPT_MARKER,Un as REQUEST_DEADLINE_MS,de as REQUEST_HEX_LENGTH,St as RpcError,ce as RtcError,$r as SNAP_ENVELOPE_RESERVE,bn as STORE_ERROR_CODES,wr as STUN_NO_RESPONSE_CODE,_e as SessionError,ge as StoreCore,h as StoreError,at as StoreOwner,ut as StoreReplica,kt as StreamIdentityError,Os as TICK_INTERVAL_MS,vs as TRANSITION_DEADLINE_MS,ar as U64_EVENT_KEYS,Ue as UnknownLeafError,En as WIRE_VERSION,yt as WireError,nt as acceptPeer,Rs as addItems,Cn as applyPatch,xe as applyVisibility,mn as asSessionModule,_n as assertChunkingFits,Ci as assertHidden,Jr as base64,It as buildConnectRequest,cn as candidateLineIsReflexive,ls as canonicalBytes,Ln as canonicalRequest,go as cellKey,Ps as cellsAround,Fr as chunkBytesFor,Pn as chunkSnapshot,hi as classifyRtcError,Sr as classifyRtcFailure,Rt as classifyRtcFailureAll,Ze as clientStreamOrgTrampoline,wt as coarseAdmissionReason,Oe as compileVisibility,wi as connect,tt as connectPeer,Yt as countItems,ec as createLobby,oe as decimalValue,ke as decodeMessage,ji as defineStore,Or as diagnosticStunUrl,Dn as digestBinding,an as driveAttempt,et as duplexOrgTrampoline,lo as emptyInventory,I as encodeMessage,lr as fromBase64,S as fromWasmError,At as handshakePeer,uo as hasItems,Ri as hiddenOr,dt as hostInternals,Jn as hostPlayer,qn as hostStore,ve as idArg,Bt as inadmissibleValue,Tn as inlineBinding,ho as inventoryOf,Ut as isCanonicalBase64,kn as isCanonicalDecimal,Ur as isCanonicalHex,Dt as isEntityMap,Tt as isHidden,gn as isLifecycleEvent,st as isStaleStream,oi as isUdpBlocked,nc as joinLobby,$n as joinStore,$i as jsonByteLength,tc as listLobbies,rt as loadLeafWasm,rc as lobbyCodeFromUrl,Jt as mergeShallow,zt as needsDigest,ct as nodeHexOf,Yn as normalizeLobbyCode,yo as onlyOwn,Ai as openSession,ei as orgRetireError,xt as orgRetireReason,en as orgTerminalError,Ne as parseAttemptStatus,Ct as parseCounters,jt as parseDescriptors,Se as parseEvent,fo as parseInventory,Et as parseJsonPreservingU64,rr as parseLeafError,Ge as parseOrgCaller,tr as parseOrgError,Rr as parseRetryReport,ir as parseRpcFailure,sr as parseRtcFailure,Ar as parseRtcStats,yn as parseSessionEvent,Ee as parseStoreJson,lt as peerHexOf,kr as peerIdHex,pn as probeBootstrapReachable,dn as probeEventAnswers,vr as probeStunBinding,un as probeStunBindings,Cr as projectVisible,ue as reconcile,hn as refineIceFailure,xr as reflexiveAddress,_o as rememberedIdentity,po as removeItems,Po as requestCredential,So as sameCells,bo as stickyCells,Qe as streamingOrgTrampoline,fi as stunProbeAnswered,br as stunProbeVerdict,sn as toBase64,re as toWasmOrgCallOptions,se as toWasmOrgServeOptions,vt as udpBlockedEvidence,Ye as unaryOrgTrampoline,M as utf8Length};