tempest.games 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # tempest.games
2
2
 
3
+ ## 0.0.9
4
+
5
+ ### Patch Changes
6
+
7
+ - 28a83df: ✨ Redirect /index.html to /
8
+
3
9
  ## 0.0.8
4
10
 
5
11
  ### Patch Changes
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{join as bo,normalize as go,resolve as no}from"path";function fe(e=Math.random){return e().toString(36).slice(2)}class be extends Promise{fate;resolve;reject;done=!1;constructor(e){let t,o;super((n,i)=>{t=n,o=i});this.resolve=t,this.reject=o,this.use(e instanceof Promise?e:new Promise(e))}pass(e,t){if(e===this.fate)this.resolve(t),this.done=!0}fail(e,t){if(e===this.fate)this.reject(t),this.done=!0}use(e){if(e instanceof Promise){const t=e;this.fate=t,t.then((o)=>{this.pass(t,o)},(o)=>{this.fail(t,o)})}else this.resolve(e),this.fate=void 0}}function y(e){while(e.child!==null)e=e.child;return e}function gt(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=ro[e.type],r={key:n,type:i};if(i==="molecule")Object.assign(r,{key:t,family:e});else Object.assign(r,{family:{key:e.key,subKey:o}});return Object.assign(r,{counterfeit:!0}),r}var ro={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function U(e){const t={key:e.key,type:e.type};if("family"in e)t.family=e.family;return t}function ue(e){return At(K.STORE,e)}function me(e){return xt(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},ao={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class Ye{e;t;o;constructor(e,t,o=ao){this.logLevel=e;this.filter=t;this.logger=o}error=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!==null)this.logger.error(...e)};info=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel==="info")this.logger.info(...e)};warn=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...e)}}function he(e){return Le(K.STORE,e)}function xe(e){return qe(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;getRelatedKeys(e){return this.relations.get(e)}addRelation(e,t){let o=this.relations.get(e),n=this.relations.get(t);if(o)o.add(t);else o=new Set([t]),this.relations.set(e,o);if(n)n.add(e);else n=new Set([e]),this.relations.set(t,n)}deleteRelation(e,t){const o=this.relations.get(e);if(o){if(o.delete(t),o.size===0)this.relations.delete(e);const n=this.relations.get(t);if(n){if(n.delete(e),n.size===0)this.relations.delete(t)}}}replaceRelationsUnsafely(e,t){this.relations.set(e,new Set(t));for(let o of t){const n=new Set([e]);this.relations.set(o,n)}}replaceRelationsSafely(e,t){const o=this.relations.get(e);if(o)for(let n of o){const i=this.relations.get(n);if(i){if(i.size===1)this.relations.delete(n);else i.delete(e);this.contents.delete(this.makeContentKey(e,n))}}this.relations.set(e,new Set(t));for(let n of t){let i=this.relations.get(n);if(i)i.add(e);else i=new Set([e]),this.relations.set(n,i)}}getContentInternal(e){return this.contents.get(e)}setContent(e,t){this.contents.set(e,t)}deleteContent(e){this.contents.delete(e)}constructor(e,t){if(this.a=e.between[0],this.b=e.between[1],this.cardinality=e.cardinality,!t?.externalStore)this.relations=new Map(e.relations?.map(([o,n])=>[o,new Set(n)])),this.contents=new Map(e.contents);if(this.isContent=t?.isContent??null,t?.makeContentKey)this.makeContentKey=t.makeContentKey;if(t?.externalStore){const o=t.externalStore;if(this.has=(n,i)=>o.has(n,i),this.addRelation=(n,i)=>{o.addRelation(n,i)},this.deleteRelation=(n,i)=>{o.deleteRelation(n,i)},this.replaceRelationsSafely=(n,i)=>{o.replaceRelationsSafely(n,i)},this.replaceRelationsUnsafely=(n,i)=>{o.replaceRelationsUnsafely(n,i)},this.getRelatedKeys=(n)=>o.getRelatedKeys(n),o.getContent)this.getContentInternal=(n)=>{return o.getContent(n)},this.setContent=(n,i)=>{o.setContent(n,i)},this.deleteContent=(n)=>{o.deleteContent(n)};for(let[n,i]of e.relations??[])for(let r of i)this.addRelation(n,r);for(let[n,i]of e.contents??[])this.setContent(n,i)}}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([e,t])=>[e,[...t]]),contents:[...this.contents.entries()]}}set(e,...t){const o=typeof t[0]==="string"?t[0]:e[this.b],n=t[1]??typeof t[0]==="string"?void 0:t[0];switch(e=typeof e==="string"?e:e[this.a],this.cardinality){case"1:1":{const i=this.getRelatedKey(e);if(i&&i!==o)this.delete(i,e)}case"1:n":{const i=this.getRelatedKey(o);if(i&&i!==e)this.delete(i,o)}}if(n){const i=this.makeContentKey(e,o);this.setContent(i,n)}return this.addRelation(e,o),this}delete(e,t){t=typeof t==="string"?t:e[this.b];const o=typeof e==="string"?e:e[this.a];if(o===void 0&&typeof t==="string"){const n=this.getRelatedKeys(t);if(n)for(let i of n)this.delete(i,t)}if(typeof o==="string"&&t===void 0){const n=this.getRelatedKeys(o);if(n)for(let i of n)this.delete(o,i)}if(typeof o==="string"&&typeof t==="string"){this.deleteRelation(o,t);const n=this.makeContentKey(o,t);this.deleteContent(n)}return this}getRelatedKey(e){const t=this.getRelatedKeys(e);if(t){if(t.size>1)console.warn(`${t.size} related keys were found for key "${e}": (${[...t].map((o)=>`"${o}"`).join(", ")}). Only one related key was expected.`);for(let o of t)return o}}replaceRelations(e,t,o){const n=!Array.isArray(t),i=n?Object.keys(t):t;if(o?.reckless)this.replaceRelationsUnsafely(e,i);else this.replaceRelationsSafely(e,i);if(n)for(let r of i){const a=this.makeContentKey(e,r),s=t[r];this.setContent(a,s)}return this}getContent(e,t){const o=this.makeContentKey(e,t);return this.getContentInternal(o)}getRelationEntries(e){const t=e[this.a],o=e[this.b];if(t!==void 0&&o===void 0){const n=this.getRelatedKeys(t);if(n)return[...n].map((i)=>{return[i,this.getContent(t,i)??null]})}if(t===void 0&&o!==void 0){const n=this.getRelatedKeys(o);if(n)return[...n].map((i)=>{return[i,this.getContent(i,o)??null]})}return[]}has(e,t){if(t)return this.getRelatedKeys(e)?.has(t)??!1;return this.relations.has(e)}}class b{Subscriber;subscribers=new Map;subscribe(e,t){return this.subscribers.set(e,t),()=>{this.unsubscribe(e)}}unsubscribe(e){this.subscribers.delete(e)}next(e){const t=this.subscribers.values();for(let o of t)o(e)}}class Qe extends b{state;constructor(e){super();this.state=e}next(e){this.state=e,super.next(e)}}function P(e){return"epoch"in e.transactionMeta}function R(e){return"phase"in e.transactionMeta}var Ft=(e)=>{const t=y(e);if(!R(t)){e.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}e.logger.info("\uD83E\uDE82","transaction",t.transactionMeta.update.key,"Aborting transaction"),t.parent.child=null};function Q(e){return e.type.split("_").map(lo).join(" ")}var lo=(e)=>e[0].toUpperCase()+e.slice(1);class N extends Error{constructor(...e){const t=e[0],o=e.length===2?e[1]:e[2];if(e.length===2)super(`${Q(t)} ${S(t.key)} not found in store "${o.config.name}".`);else{const n=e[1];super(`${Q(t)} "${t.key}" member ${S(n)} not found in store "${o.config.name}".`)}}}function ye(e,t,o){return(...n)=>{const i=d(e,o);if(i)return i.run(n,t);throw new N(e,o)}}var $e=(e)=>(t)=>e instanceof Function?e(t):e;var ie=(e,t)=>{if(t.valueMap.has(e.key))return t.logger.info("\uD83D\uDCD6",e.type,e.key,"reading cached value"),Mt(e,t);if(e.type==="selector"||e.type==="readonly_selector")return t.logger.info("\uD83E\uDDEE",e.type,e.key,"computing value"),e.get();const o=e.default instanceof Function?e.default():e.default;return t.logger.info("\uD83D\uDC81","atom",e.key,"could not find cached value; using default",o),e.default instanceof Function?e.default():e.default};var Rt=(e,t)=>{if(e.operation.open){const o=performance.now();return e.logger.info("\u2757",t.type,t.key,`deferring setState at T-${o} until setState for "${e.operation.token.key}" is done`),o}e.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:t},e.logger.info("\u2B55",t.type,t.key,`operation start in store "${e.config.name}"${!R(e)?"":` ${e.transactionMeta.phase} "${e.transactionMeta.update.key}"`}`)},Ct=(e)=>{if(e.operation.open)e.logger.info("\uD83D\uDD34",e.operation.token.type,e.operation.token.key,`operation done in store "${e.config.name}"`);e.operation={open:!1},e.on.operationClose.next(e.operation)},Kt=(e,t)=>{if(!e.operation.open)return e.logger.error("\uD83D\uDC1E","unknown",t,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return e.operation.done.has(t)},Te=(e,t)=>{if(!e.operation.open){e.logger.error("\uD83D\uDC1E","unknown",t,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}e.operation.done.add(t)};var Jt=(e,t,o)=>{switch(e.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",e.type,e.key,"is now (",t.newValue,") subscribers:",e.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",e.type,e.key,"went (",t.oldValue,"->",t.newValue,") subscribers:",e.subject.subscribers)}e.subject.next(t)};var Ze=(e,t)=>{const o=y(t),n=o.selectorAtoms.getRelatedKeys(e.key);if(o.logger.info("\uD83E\uDDF9",e.type,e.key,n?`evicting ${n.size} states downstream:`:"no downstream states",n??"to evict"),n){if(o.operation.open)o.logger.info("\uD83E\uDDF9",e.type,e.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let i of n){if(Kt(o,i))continue;wt(i,o),Te(o,i)}}};function so(e,t){if($t(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var ht=(e,t,o)=>{const{key:n}=e,i=y(o);if(!R(i)||i.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",n,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!so(n,t))return;const a={type:"atom_update",key:n,...t};if(e.family)a.family=e.family;i.transactionMeta.update.updates.push(a),o.logger.info("\uD83D\uDCC1","atom",n,"stowed (",t.oldValue,"->",t.newValue,")")};var Ot=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=Y(e.key,i,e.subject,o),vt(e.key,o))It(e.key,o);Te(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(P(o))Jt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)ht(e,r,o);else if(e.key.startsWith("*")){const a=e.key.slice(1),s=o.atoms.get(a);let l=o.valueMap.get(a);if(s.type==="mutable_atom"&&R(o)){const{parent:m}=o;l=Ae(s,m,o)}if(l.do(r.newValue)===null)Ze(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":Ot(e,t,o);break;case"selector":e.set(t);break}};function re(e,t,o){const n={key:t.key,type:"atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=t.default,v={key:u,default:C instanceof Function?C(l):C};if(t.effects)v.effects=t.effects(l);const G=ae(F,v,m);return r.next({type:"state_creation",token:G}),G},n,{subject:r,install:(l)=>re(l,t),internalRoles:o});return e.families.set(t.key,s),e.defaults.set(t.key,t.default),n}function xt(e,t){if("mutable"in t)return Fe(e,t);return re(e,t)}function ve(e,t){if(t.family){const o=e.families.get(t.family.key);if(o)return o}}function _(e,...t){let o,n,i;if(t.length===1){if(o=t[0],o.type!=="molecule"){if(n=ve(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}}else{n=t[0],i=t[1];let r;if(n.type==="molecule_family")r=$(e,n,i)??pe(n,i);else r=h(e,n,i);o=r}if("counterfeit"in o&&"family"in o){n=o.type==="molecule"?d(o.family,e):e.families.get(o.family.key);const r=o.type==="molecule"?o.key:o.family.subKey,a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);switch(e.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${e.config.name}".`,a?`This state was previously disposed:\n${a.trace}`:"No previous disposal trace was found."),n.type){case"atom_family":case"mutable_atom_family":return e.defaults.get(n.key);case"selector_family":case"readonly_selector_family":{if(e.defaults.has(n.key))return e.defaults.get(o.family.key);const s=d(n,e).default(r);return e.defaults.set(n.key,s),s}case"molecule_family":throw new N(n,r,e)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return ie(d(o,e),e);case"molecule":return d(o,e).instance}}var Ie=(e,t)=>y(t).atoms.has(e),co=(e,t)=>y(t).selectors.has(e),mo=(e,t)=>y(t).readonlySelectors.has(e),Wt=(e,t)=>Ie(e,t)||co(e,t)||mo(e,t);var We=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>Wt(n,t))};var Ge=(e,t,o)=>{const n=[],i=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},_t=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ge(r,i,t))};var jt=(e,t,o,n)=>{const i=y(n);if(t.type==="atom"||t.type==="mutable_atom")i.selectorAtoms.set({selectorKey:e,atomKey:t.key}),n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atom "${t.key}"`);else{const r=Ge(t.key,o,n);n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atoms: [ ${r.map((a)=>`"${a}"`).join(", ")} ]`);for(let a of r)i.selectorAtoms=i.selectorAtoms.set({selectorKey:e,atomKey:a})}o.add(t.key)};var _e=(e,t,o)=>({get:(...n)=>{const i=y(o);let r;if(n.length===2){const[l,c]=n;switch(l.type){case"molecule_family":return _(o,l,c);default:if(o.config.lifespan==="ephemeral")r=h(o,l,c);else{const m=$(o,l,c);if(m)r=m;else throw new N(l,c,o)}}}else[r]=n;if(r.type==="molecule")return _(o,r);const a=d(r,o),s=ie(a,o);return o.logger.info("\uD83D\uDD0C","selector",e,`registers dependency ( "${r.key}" =`,s,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:e},{source:r.key}),jt(e,r,t,o),s},set:(...n)=>{let i,r;if(n.length===2)i=n[0],r=n[1];else{const l=n[0],c=n[1];r=n[2];const m=o.config.lifespan==="ephemeral"?h(o,l,c):$(o,l,c);if(!m)throw new N(l,c,o);i=m}const a=y(o),s=d(i,a);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Me=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=_e(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return Y(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Me(v,t,o),get:m,type:"readonly_selector",...o&&{family:o}};n.readonlySelectors.set(t.key,u);const F=m();e.logger.info("\u2728",u.type,u.key,"=",F);const C={key:t.key,type:"readonly_selector"};if(o)C.family=o;return C};var Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=_e(t.key,r,n),{find:s,get:l,seek:c,json:m}=a,u={find:s,get:l,seek:c,json:m},F=(I=t.get,W=y(e))=>{const w=I(u);return Y(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),q=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",q,")"),Y(t.key,q,i,W),Te(W,t.key),P(W))i.next({newValue:q,oldValue:w});t.set(a,q)},type:"selector",...o&&{family:o}};n.selectors.set(t.key,v);const G=F();e.logger.info("\u2728",v.type,v.key,"=",G);const k={key:t.key,type:"selector"};if(o)k.family=o;return k};function ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function Bt(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{const r=o.molecules.get(i.family.subKey);if(r)r.tokens.delete(n);switch(e.type){case"selector":o.selectors.delete(n),d({key:i.family.key,type:"selector_family"},t).subject.next({type:"state_disposal",token:e});break;case"readonly_selector":o.readonlySelectors.delete(n),d({key:i.family.key,type:"readonly_selector_family"},t).subject.next({type:"state_disposal",token:e});break}if(o.valueMap.delete(n),o.selectorAtoms.delete(n),o.selectorGraph.delete(n),t.logger.info("\uD83D\uDD25",e.type,n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.selectorDisposal.next(e)}}function le(e,t,o){const n={key:t.key,type:"readonly_selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","readonly_selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Me(F,{key:u,get:t.get(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>le(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Ce(e,t,o){const n={key:t.key,type:"selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Re(F,{key:u,get:t.get(l),set:t.set(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>Ce(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Le(e,t){if("set"in t)return Ce(e,t);return le(e,t)}function je(e,t){let o;o=d(e,t);const{family:n}=e;for(let a of o.joins.values())a.relations.delete(o.key),a.molecules.delete(o.stringKey);const i=[];for(let a of o.above.values())i.push(U(a));const r=[];for(let a of o.tokens.values()){const s=a.family;r.push([s.key,t.valueMap.get(a.key)])}if(n){const a=d(n,t),s={type:"molecule_disposal",token:e,family:n,context:i,values:r};if(e.family)s.family=e.family;for(let c of o.tokens.values())D(t,c);for(let c of o.below.values())if(c.family?.dependsOn==="all")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(c,t);if(o.below.clear(),R(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push(s);else a.subject.next(s);t.molecules.delete(o.stringKey)}for(let a of o.above.values())a.below.delete(o.stringKey)}function Et(e,t){const o=new b,n={type:"molecule_family",key:t.key,dependsOn:t.dependsOn??"all"},i={...n,subject:o,new:t.new};return e.moleculeFamilies.set(t.key,i),n}function Z(e,t,o){const n=te(o,t,e.key);e.tokens.set(n.key,n);const i=R(o)&&o.transactionMeta.phase==="building",r=o.moleculeInProgress===e.key;if(!i&&!r)e.subject.next({type:"state_creation",token:n});return n}class z extends Set{mode="record";subject=new b;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(e,t=0){super(e);if(e instanceof z)this.parent=e,this.cacheUpdateNumber=e.cacheUpdateNumber;if(t)this.cacheLimit=t,this.cache=new Array(t),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(e){const t=new z(e.members,e.cacheLimit);return t.cache=e.cache,t.cacheIdx=e.cacheIdx,t.cacheUpdateNumber=e.cacheUpdateNumber,t}add(e){const t=super.add(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S(e)}`);return t}clear(){const e=this.mode==="record"?[...this]:null;if(super.clear(),e)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(e)}`)}delete(e){const t=super.delete(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S(e)}`);return t}parent;child=null;transactionUpdates=null;transaction(e){this.mode="transaction",this.transactionUpdates=[],this.child=new z(this);const t=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(e(this.child)){for(let n of this.transactionUpdates)this.doStep(n);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{t(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(e,t){return this.subject.subscribe(e,t)}subscribe(e,t){return this.subject.subscribe(e,(o)=>{t(`${this.cacheUpdateNumber}=${o}`)})}emit(e){this.subject.next(e)}doStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.add(JSON.parse(n));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(n));break;case"tx":for(let i of n.split(";"))this.doStep(i)}}getUpdateNumber(e){const t=e.indexOf("=");return Number(e.substring(0,t))}do(e){const t=e.indexOf("="),o=Number(e.substring(0,t)),n=o-this.cacheUpdateNumber;if(n>0){if(n===1){this.mode="playback";const r=e.substring(t+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(n)<this.cacheLimit){const r=this.cacheIdx+n;if(this.cache[r]===e)return null;this.mode="playback";let s=!1;while(!s){this.cacheIdx%=this.cacheLimit;const c=this.cache[this.cacheIdx];if(this.cacheIdx--,!c)return"OUT_OF_RANGE";this.undo(c),s=this.cacheIdx===r-1}const l=e.substring(t+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{const i=JSON.parse(n);for(let r of i)this.add(r);break}case"tx":{const i=n.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(e){const t=e.indexOf("=");if(Number(e.substring(0,t))===this.cacheUpdateNumber){this.mode="playback";const n=e.substring(t+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function O(e){return e[0].toUpperCase()+e.slice(1)}function Be(e,t,o=K.STORE){return et(o).set(e.key,new ot(e,t,o)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function et(e){if("joins"in e&&e.joins instanceof Map)return e.joins;const t=new Map;return e.joins=t,t}function Ke(e,t){const o=et(t);let n=o.get(e.key);if(n===void 0){if(n=et(K.STORE).get(e.key)?.in(t),n===void 0)throw new Error(`Join "${e.key}" not found in store "${t.config.name}"`);o.set(e.key,n)}return n}function zt(e,t,o){const n=Ke(e,o);let i;switch(e.cardinality){case"1:1":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeyOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntryOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"1:n":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"n:n":{const r=`${e.a}KeysOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntriesOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}}}return i}function Pt(e,t){return zt(e,t,K.STORE)}function Ee(e,t,o){const n=Ke(e,o),i=y(o);if(R(i)){const{toolkit:r}=i.transactionMeta;n.transact(r,({relations:a})=>{t(a)})}else t(n.relations)}function yo(e,t){return Ke(e,t).core.findRelatedKeysState}function Vt(e){return yo(e,K.STORE)}class ot{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(e,t){const o=this.toolkit;this.toolkit=e,t(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(e){const t=e.config.name,o=this.alternates.get(t);if(o)return o;const n=new ot(this.options,this.defaultContent,e);return this.alternates.set(t,n),n.alternates=this.alternates,n}constructor(e,t,o=K.STORE){this.store=o,this.options=e,this.defaultContent=t,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${e.key}`,this),this.retrieve=(f,p)=>{const g=this.toolkit.seek(f,p);if(g)return g;const x=this.molecules.get(S(p));if(x){const A=d(f,o);return Z(x,A,o)}if(o.config.lifespan==="immortal")throw new N(f,p,o);return te(o,f,p)},this.toolkit={get:(...f)=>_(o,...f),set:(...f)=>{j(o,...f)},find:this.retrieve,seek:(...f)=>$(o,...f),json:(f)=>V(o,f),dispose:(...f)=>{D(o,...f)}};const n=e.between[0],i=e.between[1],r=Fe(o,{key:`${e.key}/relatedKeys`,default:()=>new z,mutable:!0,fromJson:(f)=>z.fromJSON(f),toJson:(f)=>f.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};const a=({get:f},p)=>f(this.retrieve(r,p)),s=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);x(A,(M)=>M.add(g)),x(T,(M)=>M.add(p))},l=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);let M,J;x(A,(B)=>{if(B.delete(g),B.size===0)M=`"${p}"`;return B}),x(T,(B)=>{if(B.delete(p),B.size===0)J=`"${g}"`;return B})},c=(f,p,g)=>{const{get:x,set:A}=f,T=this.retrieve(r,p),M=x(T);for(let J of M){if(g.includes(J))continue;const ne=this.retrieve(r,J);A(ne,(ee)=>{return ee.delete(p),ee})}A(T,(J)=>{return J.transaction((B)=>{B.clear();for(let ne of g){const ee=a(f,ne),kt=ee.has(p);if(this.relations.cardinality==="1:n"){const bt=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)bt.push(Se)}if(!kt&&ee.size>0)ee.clear();for(let Se of bt){const ke=[ne,Se].sort(),io=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(io)}}if(!kt)ee.add(p);B.add(ne)}return!0}),J})},m=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p);x(A,(T)=>{return T.transaction((M)=>{for(let J of g)M.add(J);return!0}),T});for(let T of g){const M=this.retrieve(r,T);x(M,(J)=>{return J.add(p),J})}return!0},u=(f,p,g)=>{const x=a(f,p);return g?x.has(g):x.size>0},F={getRelatedKeys:(f)=>a(this.toolkit,f),addRelation:(f,p)=>{s(this.toolkit,f,p)},deleteRelation:(f,p)=>{l(this.toolkit,f,p)},replaceRelationsSafely:(f,p)=>{c(this.toolkit,f,p)},replaceRelationsUnsafely:(f,p)=>{m(this.toolkit,f,p)},has:(f,p)=>u(this.toolkit,f,p)};let C,v,G;if(t){v=re(o,{key:`${e.key}/content`,default:t},["join","content"]);const f={key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality};G=Et(o,{key:`${e.key}/content-molecules`,new:class T{J;constructor(M,J){this.key=J}}});const p=({get:T},M)=>T(this.retrieve(v,M)),g=({set:T},M,J)=>{T(this.retrieve(v,M),J)},x=(T,M)=>{const J=o.molecules.get(`"${M}"`);if(J)this.toolkit.dispose(J),this.molecules.delete(`"${M}"`)};C=Object.assign(F,{getContent:(T)=>{return p(this.toolkit,T)},setContent:(T,M)=>{g(this.toolkit,T,M)},deleteContent:(T)=>{x(this.toolkit,T)}})}else C=F;const k=new X(e,{externalStore:C,makeContentKey:(...f)=>{const p=f.sort(),g=`${p[0]}:${p[1]}`,[x,A]=p.map((T)=>this.molecules.get(S(T)));if(o.config.lifespan==="immortal"&&x&&A){const T=y(o),M=oe(T,[x,A],G,g);this.molecules.set(`"${g}"`,d(M,T))}return g}}),I=()=>le(o,{key:`${e.key}/singleRelatedKey`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x)return A;return null}},["join","keys"]),W=()=>{return le(o,{key:`${e.key}/multipleRelatedKeys`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members}},["join","keys"])},w=()=>le(o,{key:`${e.key}/singleRelatedEntry`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x){const T=k.makeContentKey(f,A),M=this.retrieve(v,T),J=p(M);return[A,J]}return null}},["join","entries"]),q=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members.map((T)=>{const M=k.makeContentKey(f,T),J=this.retrieve(v,M),B=p(J);return[T,B]})}},["join","entries"]);switch(e.cardinality){case"1:1":{const f=I(),p=`${n}KeyOf${O(i)}`,g=`${i}KeyOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=w(),M=`${n}EntryOf${O(i)}`,J=`${i}EntryOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A;break}case"1:n":{const f=I(),p=W(),g=`${n}KeyOf${O(i)}`,x=`${i}KeysOf${O(n)}`,A={[g]:f,[x]:p};let T;if(t){const M=w(),J=q(),B=`${n}EntryOf${O(i)}`,ne=`${i}EntriesOf${O(n)}`,ee={[B]:M,[ne]:J};T=Object.assign(A,ee)}else T=A;this.relations=k,this.states=T;break}default:{const f=W(),p=`${n}KeysOf${O(i)}`,g=`${i}KeysOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=q(),M=`${n}EntriesOf${O(i)}`,J=`${i}EntriesOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A}}}}function ze(e){return{store:e}}class Pe{t;type="molecule";stringKey;family;subject=new b;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(e,t,o){this.key=t;if(this.stringKey=S(t),o)this.family=o;if(e)if(Array.isArray(e))for(let n of e)this.above.set(n.stringKey,n);else this.above.set(e.stringKey,e)}}function Nt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=gt(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Pe)return k;const I=S(k.key),W=e.molecules.get(I);if(!W)throw new Error(`Molecule ${I} not found in store "${e.config.name}"`);return W}),m=new Pe(c,n,o);a.molecules.set(s,m);for(let k of c)k.below.set(m.stringKey,m);const u={get:(...k)=>_(y(r),...k),set:(...k)=>{j(y(r),...k)},seek:(k,I)=>$(y(r),k,I),json:(k)=>V(y(r),k),run:(k,I=fe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{D(y(r),k)},env:()=>ze(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Ke(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const q=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)q(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Pt(k,n),g=p[`${f}KeysOf${Nt(W)}`],x=p[`${f}EntriesOf${Nt(W)}`];let A={relatedKeys:g};if(x)A=Object.assign(A,{relatedEntries:x});return A}return Z(m,d(k,r),y(r))},claim:(k,I)=>{const{exclusive:W}=I,w=y(e).molecules.get(S(k.key));if(w)if(W){for(let q of w.above.values())q.below.delete(w.stringKey);w.above.clear(),w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)}else w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)},spawn:(k,I,...W)=>oe(y(e),[m],d(k,e),I,...W)},F=d(o,e),C=F.new;m.instance=new C(u,n,...i);const v={type:"molecule",key:n,family:o},G={type:"molecule_creation",token:v,family:o,context:l,params:i};if(P(a))F.subject.next(G);else if(R(a)&&a.on.transactionApplying.state===null)a.transactionMeta.update.updates.push(G);return a.moleculeInProgress=null,v}function te(e,t,o){const n=e.families.get(t.key);if(n===void 0)throw new N(t,e);const i=n(o),r=y(e);if(i.family&&r.moleculeInProgress===null){if(P(r))switch(i.type){case"atom":case"mutable_atom":e.on.atomCreation.next(i);break;case"selector":case"readonly_selector":e.on.selectorCreation.next(i);break}else if(R(r)&&r.on.transactionApplying.state===null)r.transactionMeta.update.updates.push({type:"state_creation",token:i})}return i}function $(e,t,o){const n=S(o),i=`${t.key}(${n})`,r=y(e);let a;switch(t.type){case"atom_family":case"mutable_atom_family":a=r.atoms.get(i);break;case"selector_family":a=r.selectors.get(i);break;case"readonly_selector_family":a=r.readonlySelectors.get(i);break;case"molecule_family":a=r.molecules.get(S(o))}if(a)return U(a);return a}function h(e,t,o){let n=$(e,t,o);if(n)return n;const i=e.molecules.get(S(o));if(i)return Z(i,t,e);if(e.config.lifespan==="immortal"){const r=pe(t,o);return e.logger.error("\u274C",r.type,r.key,`was not found in store "${e.config.name}"; returned a counterfeit token.`),r}return n=te(e,t,o),n}function D(e,...t){let o,n;if(t.length===1)o=t[0],n=o.key;else{const r=t[0],a=t[1];o=r.type==="molecule_family"?$(e,r,a)??pe(r,a):h(e,r,a)}try{d(o,e)}catch(r){const a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${e.config.name}".`,a?`\n This state was most recently disposed\n${a.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":nt(o,e);break;case"selector":case"readonly_selector":Bt(o,e);break;case"molecule":je(o,e);break}const{stack:i}=new Error;if(i){const r=i?.split("\n")?.slice(3)?.join("\n");e.disposalTraces.add({key:o.key,trace:r})}}function j(e,...t){let o,n,i,r;if(t.length===2){if(o=t[0],r=t[1],n=ve(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}else n=t[0],i=t[1],r=t[2],o=h(e,n,i);if("counterfeit"in o){const l=e.disposalTraces.buffer.find((c)=>c?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${e.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found.");return}const a=Rt(e,o);if(a){const l=e.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${a}`,()=>{l(),e.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${a}`),j(e,o,r)});return}const s=d(o,e);Oe(s,r,e),Ct(e)}function Ve(e,t,o){const{key:n,newValue:i,oldValue:r}=t,a=e==="newValue"?i:r,s={key:n,type:"atom"};if(t.family)Object.assign(s,{family:t.family});j(o,s,a)}function it(e,t,o){switch(t){case"newValue":{Xt(e,o);break}case"oldValue":{D(o,e.token);break}}}function rt(e,t,o){switch(t){case"newValue":{D(o,e.token);break}case"oldValue":{Xt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Xt(e,t){const{family:o}=e.token;if(o){const n=t.families.get(o.key);if(n)h(t,n,E(o.subKey))}}function at(e,t,o){switch(t){case"newValue":oe(o,e.context,e.family,e.token.key,...e.params);break;case"oldValue":D(o,e.token);break}}function lt(e,t,o){switch(t){case"newValue":D(o,e.token);break;case"oldValue":{const n=oe(o,e.context,e.family,e.token.key);for(let[i,r]of e.values){const a=`${i}(${S(n.key)})`,s=d(n,o),l=s.tokens.has(a),c=o.families.get(i);if(c&&!l)Z(s,c,o);o.valueMap.set(a,r)}}break}}function Ne(e,t,o){const n=e==="newValue"?t.updates:[...t.updates].reverse();for(let i of n)switch(i.type){case"atom_update":case"selector_update":Ve(e,i,o);break;case"state_creation":it(i,e,o);break;case"state_disposal":rt(i,e,o);break;case"molecule_creation":at(i,e,o);break;case"molecule_disposal":lt(i,e,o);break;case"transaction_update":Ne(e,i,o);break}}function Dt(e,t,o){if(!P(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(e);if(i!==void 0)o.transactionMeta.epoch.set(i,t)}var Ht=(e,t)=>{const o=y(t),{parent:n}=o;if(n===null||!R(o)||o.transactionMeta?.phase!=="building"){t.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=e,n.child=null,n.on.transactionApplying.next(o.transactionMeta);const{updates:i}=o.transactionMeta.update;if(t.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${i.length} updates:`,i),Ne("newValue",o.transactionMeta.update,n),P(n))Dt(o.transactionMeta.update.key,o.transactionMeta.update.epoch,n),d({key:o.transactionMeta.update.key,type:"transaction"},t)?.subject.next(o.transactionMeta.update),t.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(R(n))n.transactionMeta.update.updates.push(o.transactionMeta.update);n.on.transactionApplying.next(null)};class L extends Map{e;deleted=new Set;constructor(e){super();this.source=e}get(e){if(super.has(e))return super.get(e);if(!this.deleted.has(e)&&this.source.has(e))return this.source.get(e);return}set(e,t){return this.deleted.delete(e),super.set(e,t)}hasOwn(e){return super.has(e)}has(e){return!this.deleted.has(e)&&(super.has(e)||this.source.has(e))}delete(e){return this.deleted.add(e),super.delete(e)}}var Ut=(e,t,o,n)=>{const i=y(o),r={parent:i,child:null,on:i.on,loggers:i.loggers,logger:i.logger,config:i.config,atoms:new L(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new L(i.families),operation:{open:!1},readonlySelectors:new L(i.readonlySelectors),timelines:new L(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new L(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new L(i.selectors),valueMap:new L(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new L(i.molecules),moleculeFamilies:new L(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new L(i.miscResources)},a=Yt(e,o),s={phase:"building",update:{type:"transaction_update",key:e,id:n,epoch:a===void 0?Number.NaN:a+1,updates:[],params:t,output:void 0},toolkit:{get:(...c)=>_(l,...c),set:(...c)=>{j(l,...c)},run:(c,m=fe())=>ye(c,m,l),find:(c,m)=>h(l,c,m),seek:(c,m)=>$(l,c,m),json:(c)=>V(l,c),make:(c,m,u,...F)=>oe(l,c,m,u,...F),dispose:(...c)=>{D(l,...c)},env:()=>ze(l)}},l=Object.assign(r,{transactionMeta:s});return i.child=l,o.logger.info("\uD83D\uDEEB","transaction",e,"Building transaction with params:",t),l};function qe(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Ut(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Ht(m,l),m}catch(l){throw Ft(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>qe(e,r),subject:new b},n=y(t);n.transactions.set(o.key,o);const i=U(o);return t.on.transactionCreation.next(i),i}function Yt(e,t){const o=P(t),n=o?t.transactionMeta.actionContinuities.getRelatedKey(e):void 0;return o&&n!==void 0?t.transactionMeta.epoch.get(n):void 0}class Xe{_buffer;_index=0;constructor(e){let t;if(typeof e==="number")t=e;else t=e.length;this._buffer=Array.from({length:t})}get buffer(){return this._buffer}get index(){return this._index}add(e){this._buffer[this._index]=e,this._index=(this._index+1)%this._buffer.length}copy(){const e=new Xe([...this._buffer]);return e._index=this._index,e}}class Lt{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new X({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new X({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...e)=>e.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new X({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new X({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Xe(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new b,atomDisposal:new b,selectorCreation:new b,selectorDisposal:new b,timelineCreation:new b,transactionCreation:new b,transactionApplying:new Qe(null),operationClose:new b,moleculeCreationStart:new b,moleculeCreationDone:new b,moleculeDisposal:new b};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Ye("warn",(e,t,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...e)=>{for(let t of this.loggers)t.error(...e)},info:(...e)=>{for(let t of this.loggers)t.info(...e)},warn:(...e)=>{for(let t of this.loggers)t.warn(...e)}};constructor(e,t=null){if(this.config={...t?.config,...e},t!==null){if(this.valueMap=new Map(t?.valueMap),this.operation={...t?.operation},P(t))this.transactionMeta={epoch:new Map(t?.transactionMeta.epoch),actionContinuities:new X(t?.transactionMeta.actionContinuities.toJSON())};for(let[,n]of t.families){if(n.internalRoles?.includes("mutable")||n.internalRoles?.includes("join"))continue;n.install(this)}const o=new Set;for(let[,n]of t.atoms){if(o.has(n.key))continue;if(n.install(this),n.type==="mutable_atom"){const i=V(t,n),r=se(n);o.add(i.key),o.add(r.key)}}for(let[,n]of t.readonlySelectors)n.install(this);for(let[,n]of t.selectors){if(o.has(n.key))continue;n.install(this)}for(let[,n]of t.transactions)n.install(this);for(let[,n]of t.timelines)n.install(this)}}}var K={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new Lt({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(e,t){let o,n=t;while(n!==null){switch(e.type){case"atom":case"mutable_atom":o=n.atoms.get(e.key);break;case"selector":o=n.selectors.get(e.key);break;case"readonly_selector":o=n.readonlySelectors.get(e.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=n.families.get(e.key);break;case"timeline":o=n.timelines.get(e.key);break;case"transaction":o=n.transactions.get(e.key);break;case"molecule":o=n.molecules.get(S(e.key));break;case"molecule_family":o=n.moleculeFamilies.get(e.key);break}if(o)return o;n=n.child}throw new N(e,t)}var qt=(e,t)=>{const o=y(t);if(o.operation.open)return o.operation.prev.get(e.key);return o.valueMap.get(e.key)};var ct=(e,t)=>{const o=y(t);return _t(e,t).map((i)=>{const r=o.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${e.key}", not found in store "${t.config.name}".`);return r.subject.subscribe(`${e.type}:${e.key}`,(a)=>{t.logger.info("\uD83D\uDCE2",e.type,e.key,"root",i,"went",a.oldValue,"->",a.newValue);const s=qt(e,o),l=ie(e,o);t.logger.info("\u2728",e.type,e.key,"went",s,"->",l),e.subject.next({newValue:l,oldValue:s})})})};function H(e,t,o,n){function i(u){if(n.operation.open){const F=n.on.operationClose.subscribe(`state subscription ${o}`,()=>{F(),t(u)})}else t(u)}const r=d(e,n);n.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${o}"`);const a=r.type==="selector"||r.type==="readonly_selector";let s=null,l=i;if(a)s=ct(r,n),l=(u)=>{if(s)s.length=0,s.push(...ct(r,n));i(u)};const c=r.subject.subscribe(o,l);return()=>{if(n.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${o}"`),c(),s)for(let u of s)u()}}var st=(e,t,o,n)=>{const i=d(e,n);n.logger.info("\uD83D\uDC40","timeline",e.key,`Adding subscription "${o}"`);const r=i.subject.subscribe(o,t);return()=>{n.logger.info("\uD83D\uDE48","timeline",e.key,`Removing subscription "${o}" from timeline`),r()}};class ce{Update;initializeState(e,t){const o=`*${e.key}`;t.atoms.delete(o),t.valueMap.delete(o);const n=e.family?{key:`*${e.family.key}`,subKey:e.family.subKey}:void 0,i=ae(t,{key:o,default:null},n);if(t.parent?.valueMap.has(o)){const r=t.parent.valueMap.get(o);t.valueMap.set(o,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`,i=_(o,e);this.unsubscribeFromInnerValue=i.subscribe(n,(r)=>{j(o,t,r)}),this.unsubscribeFromState=H(e,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(n,(a)=>{j(o,t,a)})},n,o)}updateCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`;H(t,({newValue:i,oldValue:r})=>{const a=o.timelineTopics.getRelatedKey(t.key);if(a){if(o.timelines.get(a)?.timeTraveling){const c=st({key:a,type:"timeline"},(m)=>{c(),j(o,e,(u)=>{if(m==="redo"&&i)u.do(i);else if(m==="undo"&&r)u.undo(r);return u})},n,o);return}}const s=o.on.operationClose.subscribe(n,()=>{s();const l=_(o,e),c=i===null?-1:l.getUpdateNumber(i),m=c-l.cacheUpdateNumber;if(i&&m===1)j(o,e,(u)=>(u.do(i),u));else o.logger.info("\u274C","mutable_atom",e.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${c}`)})},n,o)}mutableState;latestUpdateState;dispose;constructor(e,t){this.mutableState=e;const o=y(t);this.latestUpdateState=this.initializeState(e,o),this.observeCore(e,this.latestUpdateState,o),this.updateCore(e,this.latestUpdateState,o),o.trackers.set(e.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(e.key)}}}function Je(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="mutable_atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"mutable_atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),Je(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),De(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}if(new ce(l,e),!o)Qt(l,t,e);return l}class mt{Update;latestUpdateAtoms;mutableAtoms;constructor(e,t){const o=re(t,{key:`*${e.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(o,t),this.mutableAtoms=e,this.mutableAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey);$(t,this.latestUpdateAtoms,i),new ce(n.token,t)}}),this.latestUpdateAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey),r=$(t,this.mutableAtoms,i);if(r)new ce(r,t)}})}}function Fe(e,t,o){const n={key:t.key,type:"mutable_atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","mutable_atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C={key:u,default:()=>t.default(l),toJson:t.toJson,fromJson:t.fromJson,mutable:!0};if(t.effects)C.effects=t.effects(l);const v=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Zt(s,t,e),new mt(s,e),n}var tt=(e,t)=>{const o=y(t),n=`${e.key}:JSON`;return o.families.get(n)};var V=(e,t)=>{if(t.family){const n=y(e),r={key:`${t.family.key}:JSON`,type:"selector_family"},a=d(r,n),s=JSON.parse(t.family.subKey);return h(e,a,s)}return{type:"selector",key:`${t.key}:JSON`}};var se=(e)=>{const o={type:"atom",key:`*${e.key}`};if(e.family)o.family={key:`*${e.family.key}`,subKey:e.family.subKey};return o};function $t(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(e,t,o){const n=t.valueMap.get(e.key),i=o.valueMap.get(e.key);if(n===i){if(n===void 0)return typeof e.default==="function"?e.default():e.default;t.logger.info("\uD83D\uDCC3","atom",e.key,"copying");const r=e.toJson(n),a=e.fromJson(r);return o.valueMap.set(e.key,a),new ce(e,t),a}return i}function Y(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof be)i.use(t);if(t instanceof Promise){const r=new be(t);return n.valueMap.set(e,r),r.then((a)=>{Y(e,a,o,n),o.next({newValue:a,oldValue:r})}).catch((a)=>{n.logger.error("\uD83D\uDCA5","state",e,"rejected:",a)}),r}return n.valueMap.set(e,t),t}var Mt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},wt=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){const n=o,i=t.selectors.get(e)??t.readonlySelectors.get(e);if(i)n.use(i.get());return}if(t.operation.open)t.operation.prev.set(e,o);t.valueMap.delete(e),t.logger.info("\uD83D\uDDD1","state",e,"evicted")};var vt=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},De=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},It=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(y(t).atomsThatAreDefault),o.atomsThatAreDefault.delete(e)};function ae(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),ae(c,t,o)},subject:r};if(o)a.family=o;let s=t.default;if(t.default instanceof Function)s=t.default();n.atoms.set(a.key,a),De(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}return l}function At(e,t){if("mutable"in t){const i=Je(e,t,void 0);return e.on.atomCreation.next(i),i}const n=ae(e,t,void 0);return e.on.atomCreation.next(n),n}function nt(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{i.cleanup?.();const r=t.valueMap.get(i.key);d({key:i.family.key,type:"atom_family"},t).subject.next({type:"state_disposal",token:e,value:r});const s=o.molecules.get(i.family.subKey);if(s)s.tokens.delete(n);if(o.atoms.delete(n),o.valueMap.delete(n),o.selectorAtoms.delete(n),o.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),e.type==="mutable_atom"){const l=se(e);nt(l,t),t.trackers.delete(n)}if(t.logger.info("\uD83D\uDD25","atom",n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.atomDisposal.next(e)}}var Qt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Zt(e,t,o=K.STORE){const n=Ce(o,{key:`${e.key}:JSON`,get:(r)=>({seek:a,get:s})=>{const l=a(e,r);if(l)return t.toJson(s(l));const c=S(r),m=o.molecules.get(c);if(m){const F=Z(m,e,o);return t.toJson(s(F))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${c}"`);const u=te(o,e,r);return t.toJson(s(u))},set:(r)=>({seek:a,set:s},l)=>{const c=a(e,r);if(c)s(c,t.fromJson(l));else{const m=S(r),u=o.molecules.get(m);if(u){const F=Z(u,e,o);s(F,t.fromJson(l))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${m}"`);s(te(o,e,r),t.fromJson(l))}}}},["mutable","json"]);return d(e,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(r)=>{if(r.token.family)$(o,n,E(r.token.family.subKey))}),n}var E=(e)=>JSON.parse(e),S=(e)=>JSON.stringify(e),Nm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{e;listeners;globalListeners;handleEvent(e,...t){for(let n of this.globalListeners)n(e,...t);const o=this.listeners.get(e);if(o)for(let n of o)n(...t)}id="no_id_retrieved";constructor(e){this.emit=e;this.listeners=new Map,this.globalListeners=new Set}on(e,t){const o=this.listeners.get(e);if(o)o.add(t);else this.listeners.set(e,new Set([t]));return this}onAny(e){return this.globalListeners.add(e),this}off(e,t){const o=this.listeners.get(e);if(o)if(t)o.delete(t);else this.listeners.delete(e);return this}offAny(e){return this.globalListeners.delete(e),this}}class yt extends de{e;t;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(e){if(Array.isArray(e)){const[t,...o]=e;switch(t){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(e,t,o=console){super((n,...i)=>{const r=JSON.stringify([n,...i])+"\x03",a=(s)=>{if(s.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",a)};return this.process.stdin.once("error",a),this.process.stdin.write(r),this});this.process=e;this.key=t;this.logger=o;if(this.process=e,this.process.stdout.on("data",(n)=>{const i=n.toString();if(i==="\u2728")return;this.unprocessedEvents.push(...i.split("\x03"));const r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let a=E(this.incompleteData);this.handleEvent(...a);while(this.unprocessedEvents.length>0){const s=this.unprocessedEvents.shift();if(s){if(this.unprocessedEvents.length===0)this.incompleteData=s;a=E(s),this.handleEvent(...a)}}this.incompleteData=""}catch(a){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(a)}}),this.process.stderr.on("data",(n)=>{const i=n.toString();this.unprocessedLogs.push(...i.split("\x03"));const r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let a=E(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=E(this.incompleteLog),this.handleLog(a)}catch(a){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(a),console.error("\u274C\u274C\u274C\uFE0F")}}),e.pid)this.id=e.pid.toString()}}class Gt extends de{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(e){super((...t)=>{return this.out.next(t),this});this.id=e,this.in=new b,this.out=new b,this.in.subscribe("socket",(t)=>{this.handleEvent(...t)})}dispose(){for(let e of this.disposalFunctions)e()}}class ft extends de{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...e){this.process.stderr.write(S(e.map((t)=>t instanceof z?`{ ${t.toJSON().members.join(" | ")} }`:t))+"\x03")}logger={info:(...e)=>{this.log("i",...e)},warn:(...e)=>{this.log("w",...e)},error:(...e)=>{this.log("e",...e)}};constructor(){super((e,...t)=>{const o=JSON.stringify([e,...t]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(e)=>{const t=e.toString();this.unprocessedEvents.push(...t.split("\x03"));const o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{const n=E(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){const i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;const r=E(i);this.handleEvent(...r)}}this.incompleteData=""}catch(n){if(n instanceof Error)this.logger.error("\u2757",n.message,n.cause,n.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(e)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${e}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(e)=>{this.logger.info("\uD83D\uDC64","user",e,"joined");const t=new Gt(`user:${e}`);this.relays.set(e,t),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){const n=o(t);if(n)t.disposalFunctions.push(n)}this.on(`user:${e}`,(...o)=>{t.in.next(o)}),t.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(e)=>{const t=this.relays.get(e);if(this.off(`relay:${e}`),t)t.dispose(),this.relays.delete(e)}),process.stdout.write("\u2728")}relay(e){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(e)}}class eo extends Map{set(e,t){if(this.has(e))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:e,value:t}),this;return super.set(e,t)}clear(){throw new Error("Cannot clear an InvariantMap")}}class pt{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new eo;static create(e,t){const o=new pt(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return pt.existing.set(e,s),s}add(...e){switch(e[0].type){case"atom":case"mutable_atom":this.globals.push(...e);break;case"transaction":this.actions.push(...e);break;case"atom_family":{const[o,n]=e;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:n})}break}return this}}var Sy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ut=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),po={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},po),ky=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Vt(we);return[t(o,e)]}});import{spawn as uo}from"child_process";var Tt=me({key:"roomArguments",default:["echo",["Hello World!"]]}),to=he({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(Tt,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=uo(r,a,{env:process.env}),m=(u)=>{if(u.toString()==="\u2728")c.stdout.off("data",m),l(c)};c.stdout.on("data",m)});return new yt(s,e)}});var Oy=xe({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(Tt,n);t(s,a),t(ut,(m)=>m.add(n));const l=o(to,n);return e(l)}}),vy=xe({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Iy=xe({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Wy=xe({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(ut,(o)=>(o.delete(t),o))}});var By=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),To=me({key:"unacknowledgedUpdates",default:()=>[]});var So=me({key:"sockets",default:null}),Ny=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),Xy=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ko=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:oo,serve:xo}=globalThis.Bun;var{MODE:Cf,FRONTEND_PORT:dt,BACKEND_PORT:Kf}=process.env;var He=new ft;He.logger.info(" ready");var St=no(import.meta.dir,"..","app");xo({port:dt??3333,static:{"/":new Response(await Bun.file(no(St,"index.html")).bytes(),{headers:{"Content-Type":"text/html"}})},async fetch(e,t){const o=new URL(e.url),n=t.requestIP(e)?.address??"??";He.logger.info(`[${n}]`,e.method,o.pathname);const i=bo(St,o.pathname),r=go(i);if(!r.startsWith(St))return new Response("403: Forbidden",{status:403});return await oo(r).exists()?new Response(oo(r)):new Response("404: Not Found",{status:404})}});process.on("exit",()=>{He.logger.info("\uD83D\uDEEC frontend server exiting")});He.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${dt??3333}/`);
3
+ import{join as bo,normalize as go,resolve as no}from"path";function fe(e=Math.random){return e().toString(36).slice(2)}class be extends Promise{fate;resolve;reject;done=!1;constructor(e){let t,o;super((n,i)=>{t=n,o=i});this.resolve=t,this.reject=o,this.use(e instanceof Promise?e:new Promise(e))}pass(e,t){if(e===this.fate)this.resolve(t),this.done=!0}fail(e,t){if(e===this.fate)this.reject(t),this.done=!0}use(e){if(e instanceof Promise){const t=e;this.fate=t,t.then((o)=>{this.pass(t,o)},(o)=>{this.fail(t,o)})}else this.resolve(e),this.fate=void 0}}function y(e){while(e.child!==null)e=e.child;return e}function gt(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=ro[e.type],r={key:n,type:i};if(i==="molecule")Object.assign(r,{key:t,family:e});else Object.assign(r,{family:{key:e.key,subKey:o}});return Object.assign(r,{counterfeit:!0}),r}var ro={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function U(e){const t={key:e.key,type:e.type};if("family"in e)t.family=e.family;return t}function ue(e){return At(K.STORE,e)}function me(e){return xt(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},ao={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class Ye{e;t;o;constructor(e,t,o=ao){this.logLevel=e;this.filter=t;this.logger=o}error=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!==null)this.logger.error(...e)};info=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel==="info")this.logger.info(...e)};warn=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...e)}}function he(e){return Le(K.STORE,e)}function xe(e){return qe(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;getRelatedKeys(e){return this.relations.get(e)}addRelation(e,t){let o=this.relations.get(e),n=this.relations.get(t);if(o)o.add(t);else o=new Set([t]),this.relations.set(e,o);if(n)n.add(e);else n=new Set([e]),this.relations.set(t,n)}deleteRelation(e,t){const o=this.relations.get(e);if(o){if(o.delete(t),o.size===0)this.relations.delete(e);const n=this.relations.get(t);if(n){if(n.delete(e),n.size===0)this.relations.delete(t)}}}replaceRelationsUnsafely(e,t){this.relations.set(e,new Set(t));for(let o of t){const n=new Set([e]);this.relations.set(o,n)}}replaceRelationsSafely(e,t){const o=this.relations.get(e);if(o)for(let n of o){const i=this.relations.get(n);if(i){if(i.size===1)this.relations.delete(n);else i.delete(e);this.contents.delete(this.makeContentKey(e,n))}}this.relations.set(e,new Set(t));for(let n of t){let i=this.relations.get(n);if(i)i.add(e);else i=new Set([e]),this.relations.set(n,i)}}getContentInternal(e){return this.contents.get(e)}setContent(e,t){this.contents.set(e,t)}deleteContent(e){this.contents.delete(e)}constructor(e,t){if(this.a=e.between[0],this.b=e.between[1],this.cardinality=e.cardinality,!t?.externalStore)this.relations=new Map(e.relations?.map(([o,n])=>[o,new Set(n)])),this.contents=new Map(e.contents);if(this.isContent=t?.isContent??null,t?.makeContentKey)this.makeContentKey=t.makeContentKey;if(t?.externalStore){const o=t.externalStore;if(this.has=(n,i)=>o.has(n,i),this.addRelation=(n,i)=>{o.addRelation(n,i)},this.deleteRelation=(n,i)=>{o.deleteRelation(n,i)},this.replaceRelationsSafely=(n,i)=>{o.replaceRelationsSafely(n,i)},this.replaceRelationsUnsafely=(n,i)=>{o.replaceRelationsUnsafely(n,i)},this.getRelatedKeys=(n)=>o.getRelatedKeys(n),o.getContent)this.getContentInternal=(n)=>{return o.getContent(n)},this.setContent=(n,i)=>{o.setContent(n,i)},this.deleteContent=(n)=>{o.deleteContent(n)};for(let[n,i]of e.relations??[])for(let r of i)this.addRelation(n,r);for(let[n,i]of e.contents??[])this.setContent(n,i)}}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([e,t])=>[e,[...t]]),contents:[...this.contents.entries()]}}set(e,...t){const o=typeof t[0]==="string"?t[0]:e[this.b],n=t[1]??typeof t[0]==="string"?void 0:t[0];switch(e=typeof e==="string"?e:e[this.a],this.cardinality){case"1:1":{const i=this.getRelatedKey(e);if(i&&i!==o)this.delete(i,e)}case"1:n":{const i=this.getRelatedKey(o);if(i&&i!==e)this.delete(i,o)}}if(n){const i=this.makeContentKey(e,o);this.setContent(i,n)}return this.addRelation(e,o),this}delete(e,t){t=typeof t==="string"?t:e[this.b];const o=typeof e==="string"?e:e[this.a];if(o===void 0&&typeof t==="string"){const n=this.getRelatedKeys(t);if(n)for(let i of n)this.delete(i,t)}if(typeof o==="string"&&t===void 0){const n=this.getRelatedKeys(o);if(n)for(let i of n)this.delete(o,i)}if(typeof o==="string"&&typeof t==="string"){this.deleteRelation(o,t);const n=this.makeContentKey(o,t);this.deleteContent(n)}return this}getRelatedKey(e){const t=this.getRelatedKeys(e);if(t){if(t.size>1)console.warn(`${t.size} related keys were found for key "${e}": (${[...t].map((o)=>`"${o}"`).join(", ")}). Only one related key was expected.`);for(let o of t)return o}}replaceRelations(e,t,o){const n=!Array.isArray(t),i=n?Object.keys(t):t;if(o?.reckless)this.replaceRelationsUnsafely(e,i);else this.replaceRelationsSafely(e,i);if(n)for(let r of i){const a=this.makeContentKey(e,r),s=t[r];this.setContent(a,s)}return this}getContent(e,t){const o=this.makeContentKey(e,t);return this.getContentInternal(o)}getRelationEntries(e){const t=e[this.a],o=e[this.b];if(t!==void 0&&o===void 0){const n=this.getRelatedKeys(t);if(n)return[...n].map((i)=>{return[i,this.getContent(t,i)??null]})}if(t===void 0&&o!==void 0){const n=this.getRelatedKeys(o);if(n)return[...n].map((i)=>{return[i,this.getContent(i,o)??null]})}return[]}has(e,t){if(t)return this.getRelatedKeys(e)?.has(t)??!1;return this.relations.has(e)}}class b{Subscriber;subscribers=new Map;subscribe(e,t){return this.subscribers.set(e,t),()=>{this.unsubscribe(e)}}unsubscribe(e){this.subscribers.delete(e)}next(e){const t=this.subscribers.values();for(let o of t)o(e)}}class Qe extends b{state;constructor(e){super();this.state=e}next(e){this.state=e,super.next(e)}}function P(e){return"epoch"in e.transactionMeta}function R(e){return"phase"in e.transactionMeta}var Ft=(e)=>{const t=y(e);if(!R(t)){e.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}e.logger.info("\uD83E\uDE82","transaction",t.transactionMeta.update.key,"Aborting transaction"),t.parent.child=null};function Q(e){return e.type.split("_").map(lo).join(" ")}var lo=(e)=>e[0].toUpperCase()+e.slice(1);class N extends Error{constructor(...e){const t=e[0],o=e.length===2?e[1]:e[2];if(e.length===2)super(`${Q(t)} ${S(t.key)} not found in store "${o.config.name}".`);else{const n=e[1];super(`${Q(t)} "${t.key}" member ${S(n)} not found in store "${o.config.name}".`)}}}function ye(e,t,o){return(...n)=>{const i=d(e,o);if(i)return i.run(n,t);throw new N(e,o)}}var $e=(e)=>(t)=>e instanceof Function?e(t):e;var ie=(e,t)=>{if(t.valueMap.has(e.key))return t.logger.info("\uD83D\uDCD6",e.type,e.key,"reading cached value"),Mt(e,t);if(e.type==="selector"||e.type==="readonly_selector")return t.logger.info("\uD83E\uDDEE",e.type,e.key,"computing value"),e.get();const o=e.default instanceof Function?e.default():e.default;return t.logger.info("\uD83D\uDC81","atom",e.key,"could not find cached value; using default",o),e.default instanceof Function?e.default():e.default};var Rt=(e,t)=>{if(e.operation.open){const o=performance.now();return e.logger.info("\u2757",t.type,t.key,`deferring setState at T-${o} until setState for "${e.operation.token.key}" is done`),o}e.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:t},e.logger.info("\u2B55",t.type,t.key,`operation start in store "${e.config.name}"${!R(e)?"":` ${e.transactionMeta.phase} "${e.transactionMeta.update.key}"`}`)},Ct=(e)=>{if(e.operation.open)e.logger.info("\uD83D\uDD34",e.operation.token.type,e.operation.token.key,`operation done in store "${e.config.name}"`);e.operation={open:!1},e.on.operationClose.next(e.operation)},Kt=(e,t)=>{if(!e.operation.open)return e.logger.error("\uD83D\uDC1E","unknown",t,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return e.operation.done.has(t)},Te=(e,t)=>{if(!e.operation.open){e.logger.error("\uD83D\uDC1E","unknown",t,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}e.operation.done.add(t)};var Jt=(e,t,o)=>{switch(e.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",e.type,e.key,"is now (",t.newValue,") subscribers:",e.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",e.type,e.key,"went (",t.oldValue,"->",t.newValue,") subscribers:",e.subject.subscribers)}e.subject.next(t)};var Ze=(e,t)=>{const o=y(t),n=o.selectorAtoms.getRelatedKeys(e.key);if(o.logger.info("\uD83E\uDDF9",e.type,e.key,n?`evicting ${n.size} states downstream:`:"no downstream states",n??"to evict"),n){if(o.operation.open)o.logger.info("\uD83E\uDDF9",e.type,e.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let i of n){if(Kt(o,i))continue;wt(i,o),Te(o,i)}}};function so(e,t){if($t(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var ht=(e,t,o)=>{const{key:n}=e,i=y(o);if(!R(i)||i.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",n,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!so(n,t))return;const a={type:"atom_update",key:n,...t};if(e.family)a.family=e.family;i.transactionMeta.update.updates.push(a),o.logger.info("\uD83D\uDCC1","atom",n,"stowed (",t.oldValue,"->",t.newValue,")")};var Ot=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=Y(e.key,i,e.subject,o),vt(e.key,o))It(e.key,o);Te(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(P(o))Jt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)ht(e,r,o);else if(e.key.startsWith("*")){const a=e.key.slice(1),s=o.atoms.get(a);let l=o.valueMap.get(a);if(s.type==="mutable_atom"&&R(o)){const{parent:m}=o;l=Ae(s,m,o)}if(l.do(r.newValue)===null)Ze(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":Ot(e,t,o);break;case"selector":e.set(t);break}};function re(e,t,o){const n={key:t.key,type:"atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=t.default,v={key:u,default:C instanceof Function?C(l):C};if(t.effects)v.effects=t.effects(l);const G=ae(F,v,m);return r.next({type:"state_creation",token:G}),G},n,{subject:r,install:(l)=>re(l,t),internalRoles:o});return e.families.set(t.key,s),e.defaults.set(t.key,t.default),n}function xt(e,t){if("mutable"in t)return Fe(e,t);return re(e,t)}function ve(e,t){if(t.family){const o=e.families.get(t.family.key);if(o)return o}}function _(e,...t){let o,n,i;if(t.length===1){if(o=t[0],o.type!=="molecule"){if(n=ve(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}}else{n=t[0],i=t[1];let r;if(n.type==="molecule_family")r=$(e,n,i)??pe(n,i);else r=h(e,n,i);o=r}if("counterfeit"in o&&"family"in o){n=o.type==="molecule"?d(o.family,e):e.families.get(o.family.key);const r=o.type==="molecule"?o.key:o.family.subKey,a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);switch(e.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${e.config.name}".`,a?`This state was previously disposed:\n${a.trace}`:"No previous disposal trace was found."),n.type){case"atom_family":case"mutable_atom_family":return e.defaults.get(n.key);case"selector_family":case"readonly_selector_family":{if(e.defaults.has(n.key))return e.defaults.get(o.family.key);const s=d(n,e).default(r);return e.defaults.set(n.key,s),s}case"molecule_family":throw new N(n,r,e)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return ie(d(o,e),e);case"molecule":return d(o,e).instance}}var Ie=(e,t)=>y(t).atoms.has(e),co=(e,t)=>y(t).selectors.has(e),mo=(e,t)=>y(t).readonlySelectors.has(e),Wt=(e,t)=>Ie(e,t)||co(e,t)||mo(e,t);var We=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>Wt(n,t))};var Ge=(e,t,o)=>{const n=[],i=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},_t=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ge(r,i,t))};var jt=(e,t,o,n)=>{const i=y(n);if(t.type==="atom"||t.type==="mutable_atom")i.selectorAtoms.set({selectorKey:e,atomKey:t.key}),n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atom "${t.key}"`);else{const r=Ge(t.key,o,n);n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atoms: [ ${r.map((a)=>`"${a}"`).join(", ")} ]`);for(let a of r)i.selectorAtoms=i.selectorAtoms.set({selectorKey:e,atomKey:a})}o.add(t.key)};var _e=(e,t,o)=>({get:(...n)=>{const i=y(o);let r;if(n.length===2){const[l,c]=n;switch(l.type){case"molecule_family":return _(o,l,c);default:if(o.config.lifespan==="ephemeral")r=h(o,l,c);else{const m=$(o,l,c);if(m)r=m;else throw new N(l,c,o)}}}else[r]=n;if(r.type==="molecule")return _(o,r);const a=d(r,o),s=ie(a,o);return o.logger.info("\uD83D\uDD0C","selector",e,`registers dependency ( "${r.key}" =`,s,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:e},{source:r.key}),jt(e,r,t,o),s},set:(...n)=>{let i,r;if(n.length===2)i=n[0],r=n[1];else{const l=n[0],c=n[1];r=n[2];const m=o.config.lifespan==="ephemeral"?h(o,l,c):$(o,l,c);if(!m)throw new N(l,c,o);i=m}const a=y(o),s=d(i,a);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Me=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=_e(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return Y(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Me(v,t,o),get:m,type:"readonly_selector",...o&&{family:o}};n.readonlySelectors.set(t.key,u);const F=m();e.logger.info("\u2728",u.type,u.key,"=",F);const C={key:t.key,type:"readonly_selector"};if(o)C.family=o;return C};var Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=_e(t.key,r,n),{find:s,get:l,seek:c,json:m}=a,u={find:s,get:l,seek:c,json:m},F=(I=t.get,W=y(e))=>{const w=I(u);return Y(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),q=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",q,")"),Y(t.key,q,i,W),Te(W,t.key),P(W))i.next({newValue:q,oldValue:w});t.set(a,q)},type:"selector",...o&&{family:o}};n.selectors.set(t.key,v);const G=F();e.logger.info("\u2728",v.type,v.key,"=",G);const k={key:t.key,type:"selector"};if(o)k.family=o;return k};function ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function Bt(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{const r=o.molecules.get(i.family.subKey);if(r)r.tokens.delete(n);switch(e.type){case"selector":o.selectors.delete(n),d({key:i.family.key,type:"selector_family"},t).subject.next({type:"state_disposal",token:e});break;case"readonly_selector":o.readonlySelectors.delete(n),d({key:i.family.key,type:"readonly_selector_family"},t).subject.next({type:"state_disposal",token:e});break}if(o.valueMap.delete(n),o.selectorAtoms.delete(n),o.selectorGraph.delete(n),t.logger.info("\uD83D\uDD25",e.type,n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.selectorDisposal.next(e)}}function le(e,t,o){const n={key:t.key,type:"readonly_selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","readonly_selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Me(F,{key:u,get:t.get(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>le(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Ce(e,t,o){const n={key:t.key,type:"selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Re(F,{key:u,get:t.get(l),set:t.set(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>Ce(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Le(e,t){if("set"in t)return Ce(e,t);return le(e,t)}function je(e,t){let o;o=d(e,t);const{family:n}=e;for(let a of o.joins.values())a.relations.delete(o.key),a.molecules.delete(o.stringKey);const i=[];for(let a of o.above.values())i.push(U(a));const r=[];for(let a of o.tokens.values()){const s=a.family;r.push([s.key,t.valueMap.get(a.key)])}if(n){const a=d(n,t),s={type:"molecule_disposal",token:e,family:n,context:i,values:r};if(e.family)s.family=e.family;for(let c of o.tokens.values())D(t,c);for(let c of o.below.values())if(c.family?.dependsOn==="all")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(c,t);if(o.below.clear(),R(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push(s);else a.subject.next(s);t.molecules.delete(o.stringKey)}for(let a of o.above.values())a.below.delete(o.stringKey)}function Et(e,t){const o=new b,n={type:"molecule_family",key:t.key,dependsOn:t.dependsOn??"all"},i={...n,subject:o,new:t.new};return e.moleculeFamilies.set(t.key,i),n}function Z(e,t,o){const n=te(o,t,e.key);e.tokens.set(n.key,n);const i=R(o)&&o.transactionMeta.phase==="building",r=o.moleculeInProgress===e.key;if(!i&&!r)e.subject.next({type:"state_creation",token:n});return n}class z extends Set{mode="record";subject=new b;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(e,t=0){super(e);if(e instanceof z)this.parent=e,this.cacheUpdateNumber=e.cacheUpdateNumber;if(t)this.cacheLimit=t,this.cache=new Array(t),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(e){const t=new z(e.members,e.cacheLimit);return t.cache=e.cache,t.cacheIdx=e.cacheIdx,t.cacheUpdateNumber=e.cacheUpdateNumber,t}add(e){const t=super.add(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S(e)}`);return t}clear(){const e=this.mode==="record"?[...this]:null;if(super.clear(),e)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(e)}`)}delete(e){const t=super.delete(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S(e)}`);return t}parent;child=null;transactionUpdates=null;transaction(e){this.mode="transaction",this.transactionUpdates=[],this.child=new z(this);const t=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(e(this.child)){for(let n of this.transactionUpdates)this.doStep(n);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{t(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(e,t){return this.subject.subscribe(e,t)}subscribe(e,t){return this.subject.subscribe(e,(o)=>{t(`${this.cacheUpdateNumber}=${o}`)})}emit(e){this.subject.next(e)}doStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.add(JSON.parse(n));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(n));break;case"tx":for(let i of n.split(";"))this.doStep(i)}}getUpdateNumber(e){const t=e.indexOf("=");return Number(e.substring(0,t))}do(e){const t=e.indexOf("="),o=Number(e.substring(0,t)),n=o-this.cacheUpdateNumber;if(n>0){if(n===1){this.mode="playback";const r=e.substring(t+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(n)<this.cacheLimit){const r=this.cacheIdx+n;if(this.cache[r]===e)return null;this.mode="playback";let s=!1;while(!s){this.cacheIdx%=this.cacheLimit;const c=this.cache[this.cacheIdx];if(this.cacheIdx--,!c)return"OUT_OF_RANGE";this.undo(c),s=this.cacheIdx===r-1}const l=e.substring(t+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{const i=JSON.parse(n);for(let r of i)this.add(r);break}case"tx":{const i=n.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(e){const t=e.indexOf("=");if(Number(e.substring(0,t))===this.cacheUpdateNumber){this.mode="playback";const n=e.substring(t+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function O(e){return e[0].toUpperCase()+e.slice(1)}function Be(e,t,o=K.STORE){return et(o).set(e.key,new ot(e,t,o)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function et(e){if("joins"in e&&e.joins instanceof Map)return e.joins;const t=new Map;return e.joins=t,t}function Ke(e,t){const o=et(t);let n=o.get(e.key);if(n===void 0){if(n=et(K.STORE).get(e.key)?.in(t),n===void 0)throw new Error(`Join "${e.key}" not found in store "${t.config.name}"`);o.set(e.key,n)}return n}function zt(e,t,o){const n=Ke(e,o);let i;switch(e.cardinality){case"1:1":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeyOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntryOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"1:n":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"n:n":{const r=`${e.a}KeysOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntriesOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}}}return i}function Pt(e,t){return zt(e,t,K.STORE)}function Ee(e,t,o){const n=Ke(e,o),i=y(o);if(R(i)){const{toolkit:r}=i.transactionMeta;n.transact(r,({relations:a})=>{t(a)})}else t(n.relations)}function yo(e,t){return Ke(e,t).core.findRelatedKeysState}function Vt(e){return yo(e,K.STORE)}class ot{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(e,t){const o=this.toolkit;this.toolkit=e,t(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(e){const t=e.config.name,o=this.alternates.get(t);if(o)return o;const n=new ot(this.options,this.defaultContent,e);return this.alternates.set(t,n),n.alternates=this.alternates,n}constructor(e,t,o=K.STORE){this.store=o,this.options=e,this.defaultContent=t,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${e.key}`,this),this.retrieve=(f,p)=>{const g=this.toolkit.seek(f,p);if(g)return g;const x=this.molecules.get(S(p));if(x){const A=d(f,o);return Z(x,A,o)}if(o.config.lifespan==="immortal")throw new N(f,p,o);return te(o,f,p)},this.toolkit={get:(...f)=>_(o,...f),set:(...f)=>{j(o,...f)},find:this.retrieve,seek:(...f)=>$(o,...f),json:(f)=>V(o,f),dispose:(...f)=>{D(o,...f)}};const n=e.between[0],i=e.between[1],r=Fe(o,{key:`${e.key}/relatedKeys`,default:()=>new z,mutable:!0,fromJson:(f)=>z.fromJSON(f),toJson:(f)=>f.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};const a=({get:f},p)=>f(this.retrieve(r,p)),s=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);x(A,(M)=>M.add(g)),x(T,(M)=>M.add(p))},l=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);let M,J;x(A,(B)=>{if(B.delete(g),B.size===0)M=`"${p}"`;return B}),x(T,(B)=>{if(B.delete(p),B.size===0)J=`"${g}"`;return B})},c=(f,p,g)=>{const{get:x,set:A}=f,T=this.retrieve(r,p),M=x(T);for(let J of M){if(g.includes(J))continue;const ne=this.retrieve(r,J);A(ne,(ee)=>{return ee.delete(p),ee})}A(T,(J)=>{return J.transaction((B)=>{B.clear();for(let ne of g){const ee=a(f,ne),kt=ee.has(p);if(this.relations.cardinality==="1:n"){const bt=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)bt.push(Se)}if(!kt&&ee.size>0)ee.clear();for(let Se of bt){const ke=[ne,Se].sort(),io=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(io)}}if(!kt)ee.add(p);B.add(ne)}return!0}),J})},m=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p);x(A,(T)=>{return T.transaction((M)=>{for(let J of g)M.add(J);return!0}),T});for(let T of g){const M=this.retrieve(r,T);x(M,(J)=>{return J.add(p),J})}return!0},u=(f,p,g)=>{const x=a(f,p);return g?x.has(g):x.size>0},F={getRelatedKeys:(f)=>a(this.toolkit,f),addRelation:(f,p)=>{s(this.toolkit,f,p)},deleteRelation:(f,p)=>{l(this.toolkit,f,p)},replaceRelationsSafely:(f,p)=>{c(this.toolkit,f,p)},replaceRelationsUnsafely:(f,p)=>{m(this.toolkit,f,p)},has:(f,p)=>u(this.toolkit,f,p)};let C,v,G;if(t){v=re(o,{key:`${e.key}/content`,default:t},["join","content"]);const f={key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality};G=Et(o,{key:`${e.key}/content-molecules`,new:class T{J;constructor(M,J){this.key=J}}});const p=({get:T},M)=>T(this.retrieve(v,M)),g=({set:T},M,J)=>{T(this.retrieve(v,M),J)},x=(T,M)=>{const J=o.molecules.get(`"${M}"`);if(J)this.toolkit.dispose(J),this.molecules.delete(`"${M}"`)};C=Object.assign(F,{getContent:(T)=>{return p(this.toolkit,T)},setContent:(T,M)=>{g(this.toolkit,T,M)},deleteContent:(T)=>{x(this.toolkit,T)}})}else C=F;const k=new X(e,{externalStore:C,makeContentKey:(...f)=>{const p=f.sort(),g=`${p[0]}:${p[1]}`,[x,A]=p.map((T)=>this.molecules.get(S(T)));if(o.config.lifespan==="immortal"&&x&&A){const T=y(o),M=oe(T,[x,A],G,g);this.molecules.set(`"${g}"`,d(M,T))}return g}}),I=()=>le(o,{key:`${e.key}/singleRelatedKey`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x)return A;return null}},["join","keys"]),W=()=>{return le(o,{key:`${e.key}/multipleRelatedKeys`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members}},["join","keys"])},w=()=>le(o,{key:`${e.key}/singleRelatedEntry`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x){const T=k.makeContentKey(f,A),M=this.retrieve(v,T),J=p(M);return[A,J]}return null}},["join","entries"]),q=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members.map((T)=>{const M=k.makeContentKey(f,T),J=this.retrieve(v,M),B=p(J);return[T,B]})}},["join","entries"]);switch(e.cardinality){case"1:1":{const f=I(),p=`${n}KeyOf${O(i)}`,g=`${i}KeyOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=w(),M=`${n}EntryOf${O(i)}`,J=`${i}EntryOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A;break}case"1:n":{const f=I(),p=W(),g=`${n}KeyOf${O(i)}`,x=`${i}KeysOf${O(n)}`,A={[g]:f,[x]:p};let T;if(t){const M=w(),J=q(),B=`${n}EntryOf${O(i)}`,ne=`${i}EntriesOf${O(n)}`,ee={[B]:M,[ne]:J};T=Object.assign(A,ee)}else T=A;this.relations=k,this.states=T;break}default:{const f=W(),p=`${n}KeysOf${O(i)}`,g=`${i}KeysOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=q(),M=`${n}EntriesOf${O(i)}`,J=`${i}EntriesOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A}}}}function ze(e){return{store:e}}class Pe{t;type="molecule";stringKey;family;subject=new b;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(e,t,o){this.key=t;if(this.stringKey=S(t),o)this.family=o;if(e)if(Array.isArray(e))for(let n of e)this.above.set(n.stringKey,n);else this.above.set(e.stringKey,e)}}function Nt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=gt(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Pe)return k;const I=S(k.key),W=e.molecules.get(I);if(!W)throw new Error(`Molecule ${I} not found in store "${e.config.name}"`);return W}),m=new Pe(c,n,o);a.molecules.set(s,m);for(let k of c)k.below.set(m.stringKey,m);const u={get:(...k)=>_(y(r),...k),set:(...k)=>{j(y(r),...k)},seek:(k,I)=>$(y(r),k,I),json:(k)=>V(y(r),k),run:(k,I=fe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{D(y(r),k)},env:()=>ze(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Ke(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const q=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)q(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Pt(k,n),g=p[`${f}KeysOf${Nt(W)}`],x=p[`${f}EntriesOf${Nt(W)}`];let A={relatedKeys:g};if(x)A=Object.assign(A,{relatedEntries:x});return A}return Z(m,d(k,r),y(r))},claim:(k,I)=>{const{exclusive:W}=I,w=y(e).molecules.get(S(k.key));if(w)if(W){for(let q of w.above.values())q.below.delete(w.stringKey);w.above.clear(),w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)}else w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)},spawn:(k,I,...W)=>oe(y(e),[m],d(k,e),I,...W)},F=d(o,e),C=F.new;m.instance=new C(u,n,...i);const v={type:"molecule",key:n,family:o},G={type:"molecule_creation",token:v,family:o,context:l,params:i};if(P(a))F.subject.next(G);else if(R(a)&&a.on.transactionApplying.state===null)a.transactionMeta.update.updates.push(G);return a.moleculeInProgress=null,v}function te(e,t,o){const n=e.families.get(t.key);if(n===void 0)throw new N(t,e);const i=n(o),r=y(e);if(i.family&&r.moleculeInProgress===null){if(P(r))switch(i.type){case"atom":case"mutable_atom":e.on.atomCreation.next(i);break;case"selector":case"readonly_selector":e.on.selectorCreation.next(i);break}else if(R(r)&&r.on.transactionApplying.state===null)r.transactionMeta.update.updates.push({type:"state_creation",token:i})}return i}function $(e,t,o){const n=S(o),i=`${t.key}(${n})`,r=y(e);let a;switch(t.type){case"atom_family":case"mutable_atom_family":a=r.atoms.get(i);break;case"selector_family":a=r.selectors.get(i);break;case"readonly_selector_family":a=r.readonlySelectors.get(i);break;case"molecule_family":a=r.molecules.get(S(o))}if(a)return U(a);return a}function h(e,t,o){let n=$(e,t,o);if(n)return n;const i=e.molecules.get(S(o));if(i)return Z(i,t,e);if(e.config.lifespan==="immortal"){const r=pe(t,o);return e.logger.error("\u274C",r.type,r.key,`was not found in store "${e.config.name}"; returned a counterfeit token.`),r}return n=te(e,t,o),n}function D(e,...t){let o,n;if(t.length===1)o=t[0],n=o.key;else{const r=t[0],a=t[1];o=r.type==="molecule_family"?$(e,r,a)??pe(r,a):h(e,r,a)}try{d(o,e)}catch(r){const a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${e.config.name}".`,a?`\n This state was most recently disposed\n${a.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":nt(o,e);break;case"selector":case"readonly_selector":Bt(o,e);break;case"molecule":je(o,e);break}const{stack:i}=new Error;if(i){const r=i?.split("\n")?.slice(3)?.join("\n");e.disposalTraces.add({key:o.key,trace:r})}}function j(e,...t){let o,n,i,r;if(t.length===2){if(o=t[0],r=t[1],n=ve(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}else n=t[0],i=t[1],r=t[2],o=h(e,n,i);if("counterfeit"in o){const l=e.disposalTraces.buffer.find((c)=>c?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${e.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found.");return}const a=Rt(e,o);if(a){const l=e.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${a}`,()=>{l(),e.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${a}`),j(e,o,r)});return}const s=d(o,e);Oe(s,r,e),Ct(e)}function Ve(e,t,o){const{key:n,newValue:i,oldValue:r}=t,a=e==="newValue"?i:r,s={key:n,type:"atom"};if(t.family)Object.assign(s,{family:t.family});j(o,s,a)}function it(e,t,o){switch(t){case"newValue":{Xt(e,o);break}case"oldValue":{D(o,e.token);break}}}function rt(e,t,o){switch(t){case"newValue":{D(o,e.token);break}case"oldValue":{Xt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Xt(e,t){const{family:o}=e.token;if(o){const n=t.families.get(o.key);if(n)h(t,n,E(o.subKey))}}function at(e,t,o){switch(t){case"newValue":oe(o,e.context,e.family,e.token.key,...e.params);break;case"oldValue":D(o,e.token);break}}function lt(e,t,o){switch(t){case"newValue":D(o,e.token);break;case"oldValue":{const n=oe(o,e.context,e.family,e.token.key);for(let[i,r]of e.values){const a=`${i}(${S(n.key)})`,s=d(n,o),l=s.tokens.has(a),c=o.families.get(i);if(c&&!l)Z(s,c,o);o.valueMap.set(a,r)}}break}}function Ne(e,t,o){const n=e==="newValue"?t.updates:[...t.updates].reverse();for(let i of n)switch(i.type){case"atom_update":case"selector_update":Ve(e,i,o);break;case"state_creation":it(i,e,o);break;case"state_disposal":rt(i,e,o);break;case"molecule_creation":at(i,e,o);break;case"molecule_disposal":lt(i,e,o);break;case"transaction_update":Ne(e,i,o);break}}function Dt(e,t,o){if(!P(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(e);if(i!==void 0)o.transactionMeta.epoch.set(i,t)}var Ht=(e,t)=>{const o=y(t),{parent:n}=o;if(n===null||!R(o)||o.transactionMeta?.phase!=="building"){t.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=e,n.child=null,n.on.transactionApplying.next(o.transactionMeta);const{updates:i}=o.transactionMeta.update;if(t.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${i.length} updates:`,i),Ne("newValue",o.transactionMeta.update,n),P(n))Dt(o.transactionMeta.update.key,o.transactionMeta.update.epoch,n),d({key:o.transactionMeta.update.key,type:"transaction"},t)?.subject.next(o.transactionMeta.update),t.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(R(n))n.transactionMeta.update.updates.push(o.transactionMeta.update);n.on.transactionApplying.next(null)};class L extends Map{e;deleted=new Set;constructor(e){super();this.source=e}get(e){if(super.has(e))return super.get(e);if(!this.deleted.has(e)&&this.source.has(e))return this.source.get(e);return}set(e,t){return this.deleted.delete(e),super.set(e,t)}hasOwn(e){return super.has(e)}has(e){return!this.deleted.has(e)&&(super.has(e)||this.source.has(e))}delete(e){return this.deleted.add(e),super.delete(e)}}var Ut=(e,t,o,n)=>{const i=y(o),r={parent:i,child:null,on:i.on,loggers:i.loggers,logger:i.logger,config:i.config,atoms:new L(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new L(i.families),operation:{open:!1},readonlySelectors:new L(i.readonlySelectors),timelines:new L(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new L(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new L(i.selectors),valueMap:new L(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new L(i.molecules),moleculeFamilies:new L(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new L(i.miscResources)},a=Yt(e,o),s={phase:"building",update:{type:"transaction_update",key:e,id:n,epoch:a===void 0?Number.NaN:a+1,updates:[],params:t,output:void 0},toolkit:{get:(...c)=>_(l,...c),set:(...c)=>{j(l,...c)},run:(c,m=fe())=>ye(c,m,l),find:(c,m)=>h(l,c,m),seek:(c,m)=>$(l,c,m),json:(c)=>V(l,c),make:(c,m,u,...F)=>oe(l,c,m,u,...F),dispose:(...c)=>{D(l,...c)},env:()=>ze(l)}},l=Object.assign(r,{transactionMeta:s});return i.child=l,o.logger.info("\uD83D\uDEEB","transaction",e,"Building transaction with params:",t),l};function qe(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Ut(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Ht(m,l),m}catch(l){throw Ft(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>qe(e,r),subject:new b},n=y(t);n.transactions.set(o.key,o);const i=U(o);return t.on.transactionCreation.next(i),i}function Yt(e,t){const o=P(t),n=o?t.transactionMeta.actionContinuities.getRelatedKey(e):void 0;return o&&n!==void 0?t.transactionMeta.epoch.get(n):void 0}class Xe{_buffer;_index=0;constructor(e){let t;if(typeof e==="number")t=e;else t=e.length;this._buffer=Array.from({length:t})}get buffer(){return this._buffer}get index(){return this._index}add(e){this._buffer[this._index]=e,this._index=(this._index+1)%this._buffer.length}copy(){const e=new Xe([...this._buffer]);return e._index=this._index,e}}class Lt{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new X({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new X({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...e)=>e.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new X({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new X({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Xe(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new b,atomDisposal:new b,selectorCreation:new b,selectorDisposal:new b,timelineCreation:new b,transactionCreation:new b,transactionApplying:new Qe(null),operationClose:new b,moleculeCreationStart:new b,moleculeCreationDone:new b,moleculeDisposal:new b};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Ye("warn",(e,t,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...e)=>{for(let t of this.loggers)t.error(...e)},info:(...e)=>{for(let t of this.loggers)t.info(...e)},warn:(...e)=>{for(let t of this.loggers)t.warn(...e)}};constructor(e,t=null){if(this.config={...t?.config,...e},t!==null){if(this.valueMap=new Map(t?.valueMap),this.operation={...t?.operation},P(t))this.transactionMeta={epoch:new Map(t?.transactionMeta.epoch),actionContinuities:new X(t?.transactionMeta.actionContinuities.toJSON())};for(let[,n]of t.families){if(n.internalRoles?.includes("mutable")||n.internalRoles?.includes("join"))continue;n.install(this)}const o=new Set;for(let[,n]of t.atoms){if(o.has(n.key))continue;if(n.install(this),n.type==="mutable_atom"){const i=V(t,n),r=se(n);o.add(i.key),o.add(r.key)}}for(let[,n]of t.readonlySelectors)n.install(this);for(let[,n]of t.selectors){if(o.has(n.key))continue;n.install(this)}for(let[,n]of t.transactions)n.install(this);for(let[,n]of t.timelines)n.install(this)}}}var K={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new Lt({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(e,t){let o,n=t;while(n!==null){switch(e.type){case"atom":case"mutable_atom":o=n.atoms.get(e.key);break;case"selector":o=n.selectors.get(e.key);break;case"readonly_selector":o=n.readonlySelectors.get(e.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=n.families.get(e.key);break;case"timeline":o=n.timelines.get(e.key);break;case"transaction":o=n.transactions.get(e.key);break;case"molecule":o=n.molecules.get(S(e.key));break;case"molecule_family":o=n.moleculeFamilies.get(e.key);break}if(o)return o;n=n.child}throw new N(e,t)}var qt=(e,t)=>{const o=y(t);if(o.operation.open)return o.operation.prev.get(e.key);return o.valueMap.get(e.key)};var ct=(e,t)=>{const o=y(t);return _t(e,t).map((i)=>{const r=o.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${e.key}", not found in store "${t.config.name}".`);return r.subject.subscribe(`${e.type}:${e.key}`,(a)=>{t.logger.info("\uD83D\uDCE2",e.type,e.key,"root",i,"went",a.oldValue,"->",a.newValue);const s=qt(e,o),l=ie(e,o);t.logger.info("\u2728",e.type,e.key,"went",s,"->",l),e.subject.next({newValue:l,oldValue:s})})})};function H(e,t,o,n){function i(u){if(n.operation.open){const F=n.on.operationClose.subscribe(`state subscription ${o}`,()=>{F(),t(u)})}else t(u)}const r=d(e,n);n.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${o}"`);const a=r.type==="selector"||r.type==="readonly_selector";let s=null,l=i;if(a)s=ct(r,n),l=(u)=>{if(s)s.length=0,s.push(...ct(r,n));i(u)};const c=r.subject.subscribe(o,l);return()=>{if(n.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${o}"`),c(),s)for(let u of s)u()}}var st=(e,t,o,n)=>{const i=d(e,n);n.logger.info("\uD83D\uDC40","timeline",e.key,`Adding subscription "${o}"`);const r=i.subject.subscribe(o,t);return()=>{n.logger.info("\uD83D\uDE48","timeline",e.key,`Removing subscription "${o}" from timeline`),r()}};class ce{Update;initializeState(e,t){const o=`*${e.key}`;t.atoms.delete(o),t.valueMap.delete(o);const n=e.family?{key:`*${e.family.key}`,subKey:e.family.subKey}:void 0,i=ae(t,{key:o,default:null},n);if(t.parent?.valueMap.has(o)){const r=t.parent.valueMap.get(o);t.valueMap.set(o,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`,i=_(o,e);this.unsubscribeFromInnerValue=i.subscribe(n,(r)=>{j(o,t,r)}),this.unsubscribeFromState=H(e,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(n,(a)=>{j(o,t,a)})},n,o)}updateCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`;H(t,({newValue:i,oldValue:r})=>{const a=o.timelineTopics.getRelatedKey(t.key);if(a){if(o.timelines.get(a)?.timeTraveling){const c=st({key:a,type:"timeline"},(m)=>{c(),j(o,e,(u)=>{if(m==="redo"&&i)u.do(i);else if(m==="undo"&&r)u.undo(r);return u})},n,o);return}}const s=o.on.operationClose.subscribe(n,()=>{s();const l=_(o,e),c=i===null?-1:l.getUpdateNumber(i),m=c-l.cacheUpdateNumber;if(i&&m===1)j(o,e,(u)=>(u.do(i),u));else o.logger.info("\u274C","mutable_atom",e.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${c}`)})},n,o)}mutableState;latestUpdateState;dispose;constructor(e,t){this.mutableState=e;const o=y(t);this.latestUpdateState=this.initializeState(e,o),this.observeCore(e,this.latestUpdateState,o),this.updateCore(e,this.latestUpdateState,o),o.trackers.set(e.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(e.key)}}}function Je(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="mutable_atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"mutable_atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),Je(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),De(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}if(new ce(l,e),!o)Qt(l,t,e);return l}class mt{Update;latestUpdateAtoms;mutableAtoms;constructor(e,t){const o=re(t,{key:`*${e.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(o,t),this.mutableAtoms=e,this.mutableAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey);$(t,this.latestUpdateAtoms,i),new ce(n.token,t)}}),this.latestUpdateAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey),r=$(t,this.mutableAtoms,i);if(r)new ce(r,t)}})}}function Fe(e,t,o){const n={key:t.key,type:"mutable_atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","mutable_atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C={key:u,default:()=>t.default(l),toJson:t.toJson,fromJson:t.fromJson,mutable:!0};if(t.effects)C.effects=t.effects(l);const v=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Zt(s,t,e),new mt(s,e),n}var tt=(e,t)=>{const o=y(t),n=`${e.key}:JSON`;return o.families.get(n)};var V=(e,t)=>{if(t.family){const n=y(e),r={key:`${t.family.key}:JSON`,type:"selector_family"},a=d(r,n),s=JSON.parse(t.family.subKey);return h(e,a,s)}return{type:"selector",key:`${t.key}:JSON`}};var se=(e)=>{const o={type:"atom",key:`*${e.key}`};if(e.family)o.family={key:`*${e.family.key}`,subKey:e.family.subKey};return o};function $t(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(e,t,o){const n=t.valueMap.get(e.key),i=o.valueMap.get(e.key);if(n===i){if(n===void 0)return typeof e.default==="function"?e.default():e.default;t.logger.info("\uD83D\uDCC3","atom",e.key,"copying");const r=e.toJson(n),a=e.fromJson(r);return o.valueMap.set(e.key,a),new ce(e,t),a}return i}function Y(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof be)i.use(t);if(t instanceof Promise){const r=new be(t);return n.valueMap.set(e,r),r.then((a)=>{Y(e,a,o,n),o.next({newValue:a,oldValue:r})}).catch((a)=>{n.logger.error("\uD83D\uDCA5","state",e,"rejected:",a)}),r}return n.valueMap.set(e,t),t}var Mt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},wt=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){const n=o,i=t.selectors.get(e)??t.readonlySelectors.get(e);if(i)n.use(i.get());return}if(t.operation.open)t.operation.prev.set(e,o);t.valueMap.delete(e),t.logger.info("\uD83D\uDDD1","state",e,"evicted")};var vt=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},De=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},It=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(y(t).atomsThatAreDefault),o.atomsThatAreDefault.delete(e)};function ae(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),ae(c,t,o)},subject:r};if(o)a.family=o;let s=t.default;if(t.default instanceof Function)s=t.default();n.atoms.set(a.key,a),De(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}return l}function At(e,t){if("mutable"in t){const i=Je(e,t,void 0);return e.on.atomCreation.next(i),i}const n=ae(e,t,void 0);return e.on.atomCreation.next(n),n}function nt(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{i.cleanup?.();const r=t.valueMap.get(i.key);d({key:i.family.key,type:"atom_family"},t).subject.next({type:"state_disposal",token:e,value:r});const s=o.molecules.get(i.family.subKey);if(s)s.tokens.delete(n);if(o.atoms.delete(n),o.valueMap.delete(n),o.selectorAtoms.delete(n),o.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),e.type==="mutable_atom"){const l=se(e);nt(l,t),t.trackers.delete(n)}if(t.logger.info("\uD83D\uDD25","atom",n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.atomDisposal.next(e)}}var Qt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Zt(e,t,o=K.STORE){const n=Ce(o,{key:`${e.key}:JSON`,get:(r)=>({seek:a,get:s})=>{const l=a(e,r);if(l)return t.toJson(s(l));const c=S(r),m=o.molecules.get(c);if(m){const F=Z(m,e,o);return t.toJson(s(F))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${c}"`);const u=te(o,e,r);return t.toJson(s(u))},set:(r)=>({seek:a,set:s},l)=>{const c=a(e,r);if(c)s(c,t.fromJson(l));else{const m=S(r),u=o.molecules.get(m);if(u){const F=Z(u,e,o);s(F,t.fromJson(l))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${m}"`);s(te(o,e,r),t.fromJson(l))}}}},["mutable","json"]);return d(e,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(r)=>{if(r.token.family)$(o,n,E(r.token.family.subKey))}),n}var E=(e)=>JSON.parse(e),S=(e)=>JSON.stringify(e),Nm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{e;listeners;globalListeners;handleEvent(e,...t){for(let n of this.globalListeners)n(e,...t);const o=this.listeners.get(e);if(o)for(let n of o)n(...t)}id="no_id_retrieved";constructor(e){this.emit=e;this.listeners=new Map,this.globalListeners=new Set}on(e,t){const o=this.listeners.get(e);if(o)o.add(t);else this.listeners.set(e,new Set([t]));return this}onAny(e){return this.globalListeners.add(e),this}off(e,t){const o=this.listeners.get(e);if(o)if(t)o.delete(t);else this.listeners.delete(e);return this}offAny(e){return this.globalListeners.delete(e),this}}class yt extends de{e;t;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(e){if(Array.isArray(e)){const[t,...o]=e;switch(t){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(e,t,o=console){super((n,...i)=>{const r=JSON.stringify([n,...i])+"\x03",a=(s)=>{if(s.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",a)};return this.process.stdin.once("error",a),this.process.stdin.write(r),this});this.process=e;this.key=t;this.logger=o;if(this.process=e,this.process.stdout.on("data",(n)=>{const i=n.toString();if(i==="\u2728")return;this.unprocessedEvents.push(...i.split("\x03"));const r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let a=E(this.incompleteData);this.handleEvent(...a);while(this.unprocessedEvents.length>0){const s=this.unprocessedEvents.shift();if(s){if(this.unprocessedEvents.length===0)this.incompleteData=s;a=E(s),this.handleEvent(...a)}}this.incompleteData=""}catch(a){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(a)}}),this.process.stderr.on("data",(n)=>{const i=n.toString();this.unprocessedLogs.push(...i.split("\x03"));const r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let a=E(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=E(this.incompleteLog),this.handleLog(a)}catch(a){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(a),console.error("\u274C\u274C\u274C\uFE0F")}}),e.pid)this.id=e.pid.toString()}}class Gt extends de{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(e){super((...t)=>{return this.out.next(t),this});this.id=e,this.in=new b,this.out=new b,this.in.subscribe("socket",(t)=>{this.handleEvent(...t)})}dispose(){for(let e of this.disposalFunctions)e()}}class ft extends de{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...e){this.process.stderr.write(S(e.map((t)=>t instanceof z?`{ ${t.toJSON().members.join(" | ")} }`:t))+"\x03")}logger={info:(...e)=>{this.log("i",...e)},warn:(...e)=>{this.log("w",...e)},error:(...e)=>{this.log("e",...e)}};constructor(){super((e,...t)=>{const o=JSON.stringify([e,...t]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(e)=>{const t=e.toString();this.unprocessedEvents.push(...t.split("\x03"));const o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{const n=E(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){const i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;const r=E(i);this.handleEvent(...r)}}this.incompleteData=""}catch(n){if(n instanceof Error)this.logger.error("\u2757",n.message,n.cause,n.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(e)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${e}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(e)=>{this.logger.info("\uD83D\uDC64","user",e,"joined");const t=new Gt(`user:${e}`);this.relays.set(e,t),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){const n=o(t);if(n)t.disposalFunctions.push(n)}this.on(`user:${e}`,(...o)=>{t.in.next(o)}),t.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(e)=>{const t=this.relays.get(e);if(this.off(`relay:${e}`),t)t.dispose(),this.relays.delete(e)}),process.stdout.write("\u2728")}relay(e){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(e)}}class eo extends Map{set(e,t){if(this.has(e))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:e,value:t}),this;return super.set(e,t)}clear(){throw new Error("Cannot clear an InvariantMap")}}class pt{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new eo;static create(e,t){const o=new pt(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return pt.existing.set(e,s),s}add(...e){switch(e[0].type){case"atom":case"mutable_atom":this.globals.push(...e);break;case"transaction":this.actions.push(...e);break;case"atom_family":{const[o,n]=e;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:n})}break}return this}}var Sy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ut=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),po={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},po),ky=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Vt(we);return[t(o,e)]}});import{spawn as uo}from"child_process";var Tt=me({key:"roomArguments",default:["echo",["Hello World!"]]}),to=he({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(Tt,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=uo(r,a,{env:process.env}),m=(u)=>{if(u.toString()==="\u2728")c.stdout.off("data",m),l(c)};c.stdout.on("data",m)});return new yt(s,e)}});var Oy=xe({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(Tt,n);t(s,a),t(ut,(m)=>m.add(n));const l=o(to,n);return e(l)}}),vy=xe({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Iy=xe({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Wy=xe({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(ut,(o)=>(o.delete(t),o))}});var By=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),To=me({key:"unacknowledgedUpdates",default:()=>[]});var So=me({key:"sockets",default:null}),Ny=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),Xy=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ko=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:oo,serve:xo}=globalThis.Bun;var{MODE:Cf,FRONTEND_PORT:dt,BACKEND_PORT:Kf}=process.env;var He=new ft;He.logger.info(" ready");var St=no(import.meta.dir,"..","app");xo({port:dt??3333,async fetch(e,t){const o=new URL(e.url),n=t.requestIP(e)?.address??"??";if(He.logger.info(`[${n}]`,e.method,o.pathname),o.pathname==="/")return new Response(Bun.file(no(St,"index.html")));if(o.pathname==="/index.html")return Response.redirect("/");const i=bo(St,o.pathname),r=go(i);if(!r.startsWith(St))return new Response("403: Forbidden",{status:403});return await oo(r).exists()?new Response(oo(r)):new Response("404: Not Found",{status:404})}});process.on("exit",()=>{He.logger.info("\uD83D\uDEEC frontend server exiting")});He.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${dt??3333}/`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tempest.games",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },