tempest.games 0.1.24 → 0.1.25
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 +6 -0
- package/bin/backend.bun.js +1 -1
- package/bin/backend.worker.game.bun.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
package/bin/backend.bun.js
CHANGED
|
@@ -77,4 +77,4 @@ ${m.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"
|
|
|
77
77
|
hash text NOT NULL,
|
|
78
78
|
created_at bigint
|
|
79
79
|
)
|
|
80
|
-
`;await i.execute(A`CREATE SCHEMA IF NOT EXISTS ${A.identifier(p)}`),await i.execute(x);let a=(await i.all(A`select id, hash, created_at from ${A.identifier(p)}.${A.identifier(c)} order by created_at desc limit 1`))[0];await i.transaction(async(f)=>{for await(let l of n)if(!a||Number(a.created_at)<l.folderMillis){for(let $ of l.sql)await f.execute(A.raw($));await f.execute(A`insert into ${A.identifier(p)}.${A.identifier(c)} ("hash", "created_at") values(${l.hash}, ${l.folderMillis})`)}})}escapeName(n){return`"${n}"`}escapeParam(n){return`$${n+1}`}escapeString(n){return`'${n.replace(/'/g,"''")}'`}buildWithCTE(n){if(!n?.length)return;let i=[A`with `];for(let[o,c]of n.entries())if(i.push(A`${A.identifier(c._.alias)} as (${c._.sql})`),o<n.length-1)i.push(A`, `);return i.push(A` `),A.join(i)}buildDeleteQuery({table:n,where:i,returning:o,withList:c}){let p=this.buildWithCTE(c),x=o?A` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,m=i?A` where ${i}`:void 0;return A`${p}delete from ${n}${m}${x}`}buildUpdateSet(n,i){let o=n[L.Symbol.Columns],c=Object.keys(o).filter((x)=>i[x]!==void 0||o[x]?.onUpdateFn!==void 0),p=c.length;return A.join(c.flatMap((x,m)=>{let a=o[x],f=i[x]??A.param(a.onUpdateFn(),a),l=A`${A.identifier(this.casing.getColumnCasing(a))} = ${f}`;if(m<p-1)return[l,A.raw(", ")];return[l]}))}buildUpdateQuery({table:n,set:i,where:o,returning:c,withList:p,from:x,joins:m}){let a=this.buildWithCTE(p),f=n[vi.Symbol.Name],l=n[vi.Symbol.Schema],$=n[vi.Symbol.OriginalName],v=f===$?void 0:f,T=A`${l?A`${A.identifier(l)}.`:void 0}${A.identifier($)}${v&&A` ${A.identifier(v)}`}`,F=this.buildUpdateSet(n,i),R=x&&A.join([A.raw(" from "),this.buildFromTable(x)]),S=this.buildJoins(m),M=c?A` returning ${this.buildSelection(c,{isSingleTable:!x})}`:void 0,G=o?A` where ${o}`:void 0;return A`${a}update ${T} set ${F}${R}${S}${G}${M}`}buildSelection(n,{isSingleTable:i=!1}={}){let o=n.length,c=n.flatMap(({field:p},x)=>{let m=[];if(z(p,N.Aliased)&&p.isSelectionField)m.push(A.identifier(p.fieldAlias));else if(z(p,N.Aliased)||z(p,N)){let a=z(p,N.Aliased)?p.sql:p;if(i)m.push(new N(a.queryChunks.map((f)=>{if(z(f,_))return A.identifier(this.casing.getColumnCasing(f));return f})));else m.push(a);if(z(p,N.Aliased))m.push(A` as ${A.identifier(p.fieldAlias)}`)}else if(z(p,On))if(i)m.push(A.identifier(this.casing.getColumnCasing(p)));else m.push(p);if(x<o-1)m.push(A`, `);return m});return A.join(c)}buildJoins(n){if(!n||n.length===0)return;let i=[];for(let[o,c]of n.entries()){if(o===0)i.push(A` `);let p=c.table,x=c.lateral?A` lateral`:void 0;if(z(p,vi)){let m=p[vi.Symbol.Name],a=p[vi.Symbol.Schema],f=p[vi.Symbol.OriginalName],l=m===f?void 0:c.alias;i.push(A`${A.raw(c.joinType)} join${x} ${a?A`${A.identifier(a)}.`:void 0}${A.identifier(f)}${l&&A` ${A.identifier(l)}`} on ${c.on}`)}else if(z(p,ui)){let m=p[Bn].name,a=p[Bn].schema,f=p[Bn].originalName,l=m===f?void 0:c.alias;i.push(A`${A.raw(c.joinType)} join${x} ${a?A`${A.identifier(a)}.`:void 0}${A.identifier(f)}${l&&A` ${A.identifier(l)}`} on ${c.on}`)}else i.push(A`${A.raw(c.joinType)} join${x} ${p} on ${c.on}`);if(o<n.length-1)i.push(A` `)}return A.join(i)}buildFromTable(n){if(z(n,L)&&n[L.Symbol.OriginalName]!==n[L.Symbol.Name]){let i=A`${A.identifier(n[L.Symbol.OriginalName])}`;if(n[L.Symbol.Schema])i=A`${A.identifier(n[L.Symbol.Schema])}.${i}`;return A`${i} ${A.identifier(n[L.Symbol.Name])}`}return n}buildSelectQuery({withList:n,fields:i,fieldsFlat:o,where:c,having:p,table:x,joins:m,orderBy:a,groupBy:f,limit:l,offset:$,lockingClause:v,distinct:T,setOperators:F}){let R=o??ei(i);for(let q of R)if(z(q.field,On)&&di(q.field.table)!==(z(x,ci)?x._.alias:z(x,cm)?x[Bn].name:z(x,N)?void 0:di(x))&&!((Xn)=>m?.some(({alias:Un})=>Un===(Xn[L.Symbol.IsAlias]?di(Xn):Xn[L.Symbol.BaseName])))(q.field.table)){let Xn=di(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${Xn}"."${q.field.name}", but the table "${Xn}" is not part of the query! Did you forget to join it?`)}let S=!m||m.length===0,M=this.buildWithCTE(n),G;if(T)G=T===!0?A` distinct`:A` distinct on (${A.join(T.on,A`, `)})`;let H=this.buildSelection(R,{isSingleTable:S}),y=this.buildFromTable(x),k=this.buildJoins(m),Y=c?A` where ${c}`:void 0,K=p?A` having ${p}`:void 0,Q;if(a&&a.length>0)Q=A` order by ${A.join(a,A`, `)}`;let u;if(f&&f.length>0)u=A` group by ${A.join(f,A`, `)}`;let V=typeof l==="object"||typeof l==="number"&&l>=0?A` limit ${l}`:void 0,X=$?A` offset ${$}`:void 0,s=A.empty();if(v){let q=A` for ${A.raw(v.strength)}`;if(v.config.of)q.append(A` of ${A.join(Array.isArray(v.config.of)?v.config.of:[v.config.of],A`, `)}`);if(v.config.noWait)q.append(A` no wait`);else if(v.config.skipLocked)q.append(A` skip locked`);s.append(q)}let C=A`${M}select${G} ${H} from ${y}${k}${Y}${u}${K}${Q}${V}${X}${s}`;if(F.length>0)return this.buildSetOperations(C,F);return C}buildSetOperations(n,i){let[o,...c]=i;if(!o)throw new Error("Cannot pass undefined values to any set operator");if(c.length===0)return this.buildSetOperationQuery({leftSelect:n,setOperator:o});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:n,setOperator:o}),c)}buildSetOperationQuery({leftSelect:n,setOperator:{type:i,isAll:o,rightSelect:c,limit:p,orderBy:x,offset:m}}){let a=A`(${n.getSQL()}) `,f=A`(${c.getSQL()})`,l;if(x&&x.length>0){let F=[];for(let R of x)if(z(R,_))F.push(A.identifier(R.name));else if(z(R,N)){for(let S=0;S<R.queryChunks.length;S++){let M=R.queryChunks[S];if(z(M,_))R.queryChunks[S]=A.identifier(M.name)}F.push(A`${R}`)}else F.push(A`${R}`);l=A` order by ${A.join(F,A`, `)} `}let $=typeof p==="object"||typeof p==="number"&&p>=0?A` limit ${p}`:void 0,v=A.raw(`${i} ${o?"all ":""}`),T=m?A` offset ${m}`:void 0;return A`${a}${v}${f}${l}${$}${T}`}buildInsertQuery({table:n,values:i,onConflict:o,returning:c,withList:p,select:x,overridingSystemValue_:m}){let a=[],f=n[L.Symbol.Columns],l=Object.entries(f).filter(([M,G])=>!G.shouldDisableInsert()),$=l.map(([,M])=>A.identifier(this.casing.getColumnCasing(M)));if(x){let M=i;if(z(M,N))a.push(M);else a.push(M.getSQL())}else{let M=i;a.push(A.raw("values "));for(let[G,H]of M.entries()){let y=[];for(let[k,Y]of l){let K=H[k];if(K===void 0||z(K,Li)&&K.value===void 0)if(Y.defaultFn!==void 0){let Q=Y.defaultFn(),u=z(Q,N)?Q:A.param(Q,Y);y.push(u)}else if(!Y.default&&Y.onUpdateFn!==void 0){let Q=Y.onUpdateFn(),u=z(Q,N)?Q:A.param(Q,Y);y.push(u)}else y.push(A`default`);else y.push(K)}if(a.push(y),G<M.length-1)a.push(A`, `)}}let v=this.buildWithCTE(p),T=A.join(a),F=c?A` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,R=o?A` on conflict ${o}`:void 0,S=m===!0?A`overriding system value `:void 0;return A`${v}insert into ${n} ${$} ${S}${T}${R}${F}`}buildRefreshMaterializedViewQuery({view:n,concurrently:i,withNoData:o}){let c=i?A` concurrently`:void 0,p=o?A` with no data`:void 0;return A`refresh materialized view${c} ${n}${p}`}prepareTyping(n){if(z(n,aa)||z(n,ma))return"json";else if(z(n,fa))return"decimal";else if(z(n,la))return"time";else if(z(n,$a)||z(n,va))return"timestamp";else if(z(n,ca)||z(n,pa))return"date";else if(z(n,Ta))return"uuid";else return"none"}sqlToQuery(n,i){return n.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:i})}buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:c,tableConfig:p,queryConfig:x,tableAlias:m,nestedQueryRelation:a,joinOn:f}){let l=[],$,v,T=[],F,R=[];if(x===!0)l=Object.entries(p.columns).map(([G,H])=>({dbKey:H.name,tsKey:G,field:Ho(H,m),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(p.columns).map(([K,Q])=>[K,Ho(Q,m)]));if(x.where){let K=typeof x.where==="function"?x.where(M,pA()):x.where;F=K&&Ux(K,m)}let G=[],H=[];if(x.columns){let K=!1;for(let[Q,u]of Object.entries(x.columns)){if(u===void 0)continue;if(Q in p.columns){if(!K&&u===!0)K=!0;H.push(Q)}}if(H.length>0)H=K?H.filter((Q)=>x.columns?.[Q]===!0):Object.keys(p.columns).filter((Q)=>!H.includes(Q))}else H=Object.keys(p.columns);for(let K of H){let Q=p.columns[K];G.push({tsKey:K,value:Q})}let y=[];if(x.with)y=Object.entries(x.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:p.relations[K]}));let k;if(x.extras){k=typeof x.extras==="function"?x.extras(M,{sql:A}):x.extras;for(let[K,Q]of Object.entries(k))G.push({tsKey:K,value:El(Q,m)})}for(let{tsKey:K,value:Q}of G)l.push({dbKey:z(Q,N.Aliased)?Q.fieldAlias:p.columns[K].name,tsKey:K,field:z(Q,On)?Ho(Q,m):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof x.orderBy==="function"?x.orderBy(M,xA()):x.orderBy??[];if(!Array.isArray(Y))Y=[Y];T=Y.map((K)=>{if(z(K,On))return Ho(K,m);return Ux(K,m)}),$=x.limit,v=x.offset;for(let{tsKey:K,queryConfig:Q,relation:u}of y){let V=aA(i,o,u),X=Uc(u.referencedTable),s=o[X],C=`${m}_${K}`,q=Vc(...V.fields.map((Vi,_o)=>Qo(Ho(V.references[_o],C),Ho(Vi,m)))),Xn=this.buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:n[s],tableConfig:i[s],queryConfig:z(u,lc)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:C,joinOn:q,nestedQueryRelation:u}),Un=A`${A.identifier(C)}.${A.identifier("data")}`.as(K);R.push({on:A`true`,table:new ci(Xn.sql,{},C),alias:C,joinType:"left",lateral:!0}),l.push({dbKey:K,tsKey:K,field:Un,relationTableTsKey:s,isJson:!0,selection:Xn.selection})}}if(l.length===0)throw new na({message:`No fields selected for table "${p.tsName}" ("${m}")`});let S;if(F=Vc(f,F),a){let M=A`json_build_array(${A.join(l.map(({field:y,tsKey:k,isJson:Y})=>Y?A`${A.identifier(`${m}_${k}`)}.${A.identifier("data")}`:z(y,N.Aliased)?y.sql:y),A`, `)})`;if(z(a,bx))M=A`coalesce(json_agg(${M}${T.length>0?A` order by ${A.join(T,A`, `)}`:void 0}), '[]'::json)`;let G=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:p.tsName,selection:l}];if($!==void 0||v!==void 0||T.length>0)S=this.buildSelectQuery({table:em(c,m),fields:{},fieldsFlat:[{path:[],field:A.raw("*")}],where:F,limit:$,offset:v,orderBy:T,setOperators:[]}),F=void 0,$=void 0,v=void 0,T=[];else S=em(c,m);S=this.buildSelectQuery({table:z(S,vi)?S:new ci(S,{},m),fields:{},fieldsFlat:G.map(({field:y})=>({path:[],field:z(y,On)?Ho(y,m):y})),joins:R,where:F,limit:$,offset:v,orderBy:T,setOperators:[]})}else S=this.buildSelectQuery({table:em(c,m),fields:{},fieldsFlat:l.map(({field:M})=>({path:[],field:z(M,On)?Ho(M,m):M})),joins:R,where:F,limit:$,offset:v,orderBy:T,setOperators:[]});return{tableTsKey:p.tsName,sql:S,selection:l}}}class Ti{static[w]="SelectionProxyHandler";config;constructor(n){this.config={...n}}get(n,i){if(i==="_")return{...n._,selectedFields:new Proxy(n._.selectedFields,this)};if(i===Bn)return{...n[Bn],selectedFields:new Proxy(n[Bn].selectedFields,this)};if(typeof i==="symbol")return n[i];let c=(z(n,ci)?n._.selectedFields:z(n,ui)?n[Bn].selectedFields:n)[i];if(z(c,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!c.isSelectionField)return c.sql;let p=c.clone();return p.isSelectionField=!0,p}if(z(c,N)){if(this.config.sqlBehavior==="sql")return c;throw new Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(z(c,On)){if(this.config.alias)return new Proxy(c,new Rp(new Proxy(c.table,new Ex(this.config.alias,this.config.replaceOriginalName??!1))));return c}if(typeof c!=="object"||c===null)return c;return new Proxy(c,new Ti(this.config))}}class c0{static[w]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Ui{static[w]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(n){if(this.fields=n.fields,this.session=n.session,this.dialect=n.dialect,n.withList)this.withList=n.withList;this.distinct=n.distinct}authToken;setToken(n){return this.authToken=n,this}from(n){let i=!!this.fields,o;if(this.fields)o=this.fields;else if(z(n,ci))o=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(z(n,cm))o=n[Bn].selectedFields;else if(z(n,N))o={};else o=fJ(n);return new p0({table:n,fields:o,isPartialSelect:i,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class bR extends c0{static[w]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:n,fields:i,isPartialSelect:o,session:c,dialect:p,withList:x,distinct:m}){super();this.config={withList:x,table:n,fields:{...i},distinct:m,setOperators:[]},this.isPartialSelect=o,this.session=c,this.dialect=p,this._={selectedFields:i},this.tableName=yo(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(n){return(i,o)=>{let c=this.tableName,p=yo(i);if(typeof p==="string"&&this.config.joins?.some((x)=>x.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof c==="string")this.config.fields={[c]:this.config.fields};if(typeof p==="string"&&!z(i,N)){let x=z(i,ci)?i._.selectedFields:z(i,ui)?i[Bn].selectedFields:i[L.Symbol.Columns];this.config.fields[p]=x}}if(typeof o==="function")o=o(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:o,table:i,joinType:n,alias:p}),typeof p==="string")switch(n){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(n,i){return(o)=>{let c=typeof o==="function"?o(OG()):o;if(!Vx(this.getSelectedFields(),c.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:n,isAll:i,rightSelect:c}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(n){return this.config.setOperators.push(...n),this}where(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=n,this}having(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=n,this}groupBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=n;return this}orderBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),o=Array.isArray(i)?i:[i];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}else{let i=n;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=i;else this.config.orderBy=i}return this}limit(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=n;else this.config.limit=n;return this}offset(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=n;else this.config.offset=n;return this}for(n,i={}){return this.config.lockingClause={strength:n,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(n){return new Proxy(new ci(this.getSQL(),this.config.fields,n),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Ti({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class p0 extends bR{static[w]="PgSelect";_prepare(n){let{session:i,config:o,dialect:c,joinsNotNullableMap:p,authToken:x}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return En.startActiveSpan("drizzle.prepareQuery",()=>{let m=ei(o.fields),a=i.prepareQuery(c.sqlToQuery(this.getSQL()),m,n,!0);return a.joinsNotNullableMap=p,a.setToken(x)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})}}aJ(p0,[Qi]);function ep(n,i){return(o,c,...p)=>{let x=[c,...p].map((m)=>({type:n,isAll:i,rightSelect:m}));for(let m of x)if(!Vx(o.getSelectedFields(),m.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return o.addSetOperators(x)}}var OG=()=>({union:EG,unionAll:UG,intersect:VG,intersectAll:_G,except:uG,exceptAll:bG}),EG=ep("union",!1),UG=ep("union",!0),VG=ep("intersect",!1),_G=ep("intersect",!0),uG=ep("except",!1),bG=ep("except",!0);class pm{static[w]="PgQueryBuilder";dialect;dialectConfig;constructor(n){this.dialect=z(n,tc)?n:void 0,this.dialectConfig=z(n,tc)?void 0:n}$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(i);return new Proxy(new Ox(o.getSQL(),o.getSelectedFields(),n,!0),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...n){let i=this;function o(x){return new Ui({fields:x??void 0,session:void 0,dialect:i.getDialect(),withList:n})}function c(x){return new Ui({fields:x??void 0,session:void 0,dialect:i.getDialect(),distinct:!0})}function p(x,m){return new Ui({fields:m??void 0,session:void 0,dialect:i.getDialect(),distinct:{on:x}})}return{select:o,selectDistinct:c,selectDistinctOn:p}}select(n){return new Ui({fields:n??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(n){return new Ui({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(n,i){return new Ui({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:n}})}getDialect(){if(!this.dialect)this.dialect=new tc(this.dialectConfig);return this.dialect}}class xf{constructor(n,i,o,c,p){this.table=n,this.session=i,this.dialect=o,this.withList=c,this.overridingSystemValue_=p}static[w]="PgInsertBuilder";authToken;setToken(n){return this.authToken=n,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(n){if(n=Array.isArray(n)?n:[n],n.length===0)throw new Error("values() must be called with at least one value");let i=n.map((o)=>{let c={},p=this.table[L.Symbol.Columns];for(let x of Object.keys(o)){let m=o[x];c[x]=z(m,N)?m:new Li(m,p[x])}return c});return new x0(this.table,i,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(n){let i=typeof n==="function"?n(new pm):n;if(!z(i,N)&&!Vx(this.table[rm],i._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new x0(this.table,i,this.session,this.dialect,this.withList,!0)}}class x0 extends Qi{constructor(n,i,o,c,p,x,m){super();this.session=o,this.dialect=c,this.config={table:n,values:i,withList:p,select:x,overridingSystemValue_:m}}static[w]="PgInsert";config;returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}onConflictDoNothing(n={}){if(n.target===void 0)this.config.onConflict=A`do nothing`;else{let i="";i=Array.isArray(n.target)?n.target.map((c)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(c))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target));let o=n.where?A` where ${n.where}`:void 0;this.config.onConflict=A`(${A.raw(i)})${o} do nothing`}return this}onConflictDoUpdate(n){if(n.where&&(n.targetWhere||n.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let i=n.where?A` where ${n.where}`:void 0,o=n.targetWhere?A` where ${n.targetWhere}`:void 0,c=n.setWhere?A` where ${n.setWhere}`:void 0,p=this.dialect.buildUpdateSet(this.config.table,oa(this.config.table,n.set)),x="";return x=Array.isArray(n.target)?n.target.map((m)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(m))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target)),this.config.onConflict=A`(${A.raw(x)})${o} do update set ${p}${i}${c}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})};$dynamic(){return this}}class m0 extends Qi{constructor(n,i,o){super();this.session=i,this.dialect=o,this.config={view:n}}static[w]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,n,!0)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})}}class mf{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[w]="PgUpdateBuilder";authToken;setToken(n){return this.authToken=n,this}set(n){return new jR(this.table,oa(this.table,n),this.session,this.dialect,this.withList).setToken(this.authToken)}}class jR extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={set:i,table:n,withList:p,joins:[]},this.tableName=yo(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[w]="PgUpdate";config;tableName;joinsNotNullableMap;from(n){let i=yo(n);if(typeof i==="string")this.joinsNotNullableMap[i]=!0;return this.config.from=n,this}getTableLikeFields(n){if(z(n,vi))return n[L.Symbol.Columns];else if(z(n,ci))return n._.selectedFields;return n[Bn].selectedFields}createJoin(n){return(i,o)=>{let c=yo(i);if(typeof c==="string"&&this.config.joins.some((p)=>p.alias===c))throw new Error(`Alias "${c}" is already used in this query`);if(typeof o==="function"){let p=this.config.from&&!z(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;o=o(new Proxy(this.config.table[L.Symbol.Columns],new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),p&&new Proxy(p,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:o,table:i,joinType:n,alias:c}),typeof c==="string")switch(n){case"left":{this.joinsNotNullableMap[c]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([p])=>[p,!1])),this.joinsNotNullableMap[c]=!0;break}case"inner":{this.joinsNotNullableMap[c]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([p])=>[p,!1])),this.joinsNotNullableMap[c]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(n){return this.config.where=n,this}returning(n){if(!n){if(n=Object.assign({},this.config.table[L.Symbol.Columns]),this.config.from){let i=yo(this.config.from);if(typeof i==="string"&&this.config.from&&!z(this.config.from,N)){let o=this.getTableLikeFields(this.config.from);n[i]=o}for(let o of this.config.joins){let c=yo(o.table);if(typeof c==="string"&&!z(o.table,N)){let p=this.getTableLikeFields(o.table);n[c]=p}}}}return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){let i=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return this._prepare().execute(n,this.authToken)};$dynamic(){return this}}class xm extends N{constructor(n){super(xm.buildEmbeddedCount(n.source,n.filters).queryChunks);this.params=n,this.mapWith(Number),this.session=n.session,this.sql=xm.buildCount(n.source,n.filters)}sql;token;static[w]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(n,i){return A`(select count(*) from ${n}${A.raw(" where ").if(i)}${i})`}static buildCount(n,i){return A`select count(*) as count from ${n}${A.raw(" where ").if(i)}${i};`}setToken(n){return this.token=n,this}then(n,i){return Promise.resolve(this.session.count(this.sql,this.token)).then(n,i)}catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}}class f0{constructor(n,i,o,c,p,x,m){this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=x,this.session=m}static[w]="PgRelationalQueryBuilder";findMany(n){return new a0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?n:{},"many")}findFirst(n){return new a0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?{...n,limit:1}:{limit:1},"first")}}class a0 extends Qi{constructor(n,i,o,c,p,x,m,a,f){super();this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=x,this.session=m,this.config=a,this.mode=f}static[w]="PgRelationalQuery";_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{let{query:i,builtQuery:o}=this._toSQL();return this.session.prepareQuery(o,void 0,n,!0,(c,p)=>{let x=c.map((m)=>Ja(this.schema,this.tableConfig,m,i.selection,p));if(this.mode==="first")return x[0];return x})})}prepare(n){return this._prepare(n)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let n=this._getQuery(),i=this.dialect.sqlToQuery(n.sql);return{query:n,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(n){return this.authToken=n,this}execute(){return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class l0 extends Qi{constructor(n,i,o,c){super();this.execute=n,this.sql=i,this.query=o,this.mapBatchResult=c}static[w]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(n,i){return i?this.mapBatchResult(n):n}_prepare(){return this}isResponseInArrayMode(){return!1}}class mm{constructor(n,i,o){if(this.dialect=n,this.session=i,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,session:i}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:i},this.query={},this._.schema)for(let[c,p]of Object.entries(this._.schema))this.query[c]=new f0(o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[c],p,n,i)}static[w]="PgDatabase";query;$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(new pm(i.dialect));return new Proxy(new Ox(o.getSQL(),o.getSelectedFields(),n,!0),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(n,i){return new xm({source:n,filters:i,session:this.session})}with(...n){let i=this;function o(f){return new Ui({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n})}function c(f){return new Ui({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:!0})}function p(f,l){return new Ui({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:{on:f}})}function x(f){return new mf(f,i.session,i.dialect,n)}function m(f){return new xf(f,i.session,i.dialect,n)}function a(f){return new pf(f,i.session,i.dialect,n)}return{select:o,selectDistinct:c,selectDistinctOn:p,update:x,insert:m,delete:a}}select(n){return new Ui({fields:n??void 0,session:this.session,dialect:this.dialect})}selectDistinct(n){return new Ui({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(n,i){return new Ui({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:{on:n}})}update(n){return new mf(n,this.session,this.dialect)}insert(n){return new xf(n,this.session,this.dialect)}delete(n){return new pf(n,this.session,this.dialect)}refreshMaterializedView(n){return new m0(n,this.session,this.dialect)}authToken;execute(n){let i=typeof n==="string"?A.raw(n):n.getSQL(),o=this.dialect.sqlToQuery(i),c=this.session.prepareQuery(o,void 0,void 0,!1);return new l0(()=>c.execute(void 0,this.authToken),i,o,(p)=>c.mapResult(p,!0))}transaction(n,i){return this.session.transaction(n,i)}}class BR{constructor(n,i){this.unique=n,this.name=i}static[w]="PgIndexBuilderOn";on(...n){return new af(n.map((i)=>{if(z(i,N))return i;i=i;let o=new Qx(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),o}),this.unique,!1,this.name)}onOnly(...n){return new af(n.map((i)=>{if(z(i,N))return i;i=i;let o=new Qx(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=i.defaultConfig,o}),this.unique,!0,this.name)}using(n,...i){return new af(i.map((o)=>{if(z(o,N))return o;o=o;let c=new Qx(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),c}),this.unique,!0,this.name,n)}}class af{static[w]="PgIndexBuilder";config;constructor(n,i,o,c,p="btree"){this.config={name:c,columns:n,unique:i,only:o,method:p}}concurrently(){return this.config.concurrently=!0,this}with(n){return this.config.with=n,this}where(n){return this.config.where=n,this}build(n){return new yR(this.config,n)}}class yR{static[w]="PgIndex";config;constructor(n,i){this.config={...n,table:i}}}function $0(n){return new BR(!0,n)}class v0{constructor(n){this.query=n}authToken;getQuery(){return this.query}mapResult(n,i){return n}setToken(n){return this.authToken=n,this}static[w]="PgPreparedQuery";joinsNotNullableMap}class T0{constructor(n){this.dialect=n}static[w]="PgSession";execute(n,i){return En.startActiveSpan("drizzle.operation",()=>{return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1)}).setToken(i).execute(void 0,i)})}all(n){return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1).all()}async count(n,i){let o=await this.execute(n,i);return Number(o[0].count)}}class J0 extends mm{constructor(n,i,o,c=0){super(n,i,o);this.schema=o,this.nestedIndex=c}static[w]="PgTransaction";rollback(){throw new Ul}getTransactionConfigSQL(n){let i=[];if(n.isolationLevel)i.push(`isolation level ${n.isolationLevel}`);if(n.accessMode)i.push(n.accessMode);if(typeof n.deferrable==="boolean")i.push(n.deferrable?"deferrable":"not deferrable");return A.raw(i.join(" "))}setTransaction(n){return this.session.execute(A`set transaction ${this.getTransactionConfigSQL(n)}`)}}class LR extends v0{constructor(n,i,o,c,p,x,m){super({sql:i,params:o});this.client=n,this.queryString=i,this.params=o,this.logger=c,this.fields=p,this._isResponseInArrayMode=x,this.customResultMapper=m}static[w]="PostgresJsPreparedQuery";async execute(n={}){return En.startActiveSpan("drizzle.execute",async(i)=>{let o=Ol(this.params,n);i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o);let{fields:c,queryString:p,client:x,joinsNotNullableMap:m,customResultMapper:a}=this;if(!c&&!a)return En.startActiveSpan("drizzle.driver.execute",()=>{return x.unsafe(p,o)});let f=await En.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":p,"drizzle.query.params":JSON.stringify(o)}),x.unsafe(p,o).values()});return En.startActiveSpan("drizzle.mapResponse",()=>{return a?a(f):f.map((l)=>mJ(c,l,m))})})}all(n={}){return En.startActiveSpan("drizzle.execute",async(i)=>{let o=Ol(this.params,n);return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o),En.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.client.unsafe(this.queryString,o)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class am extends T0{constructor(n,i,o,c={}){super(i);this.client=n,this.schema=o,this.options=c,this.logger=c.logger??new _l}static[w]="PostgresJsSession";logger;prepareQuery(n,i,o,c,p){return new LR(this.client,n.sql,n.params,this.logger,i,c,p)}query(n,i){return this.logger.logQuery(n,i),this.client.unsafe(n,i).values()}queryObjects(n,i){return this.client.unsafe(n,i)}transaction(n,i){return this.client.begin(async(o)=>{let c=new am(o,this.dialect,this.schema,this.options),p=new w0(this.dialect,c,this.schema);if(i)await p.setTransaction(i);return n(p)})}}class w0 extends J0{constructor(n,i,o,c=0){super(n,i,o,c);this.session=i}static[w]="PostgresJsTransaction";transaction(n){return this.session.client.savepoint((i)=>{let o=new am(i,this.dialect,this.schema,this.session.options),c=new w0(this.dialect,o,this.schema);return n(c)})}}class NR extends mm{static[w]="PostgresJsDatabase"}function nx(n,i={}){let o=(f)=>f;for(let f of["1184","1082","1083","1114"])n.options.parsers[f]=o,n.options.serializers[f]=o;n.options.serializers["114"]=o,n.options.serializers["3802"]=o;let c=new tc({casing:i.casing}),p;if(i.logger===!0)p=new Vl;else if(i.logger!==!1)p=i.logger;let x;if(i.schema){let f=mA(i.schema,fA);x={fullSchema:i.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}let m=new am(n,c,x,{logger:p}),a=new NR(c,m,x);return a.$client=n,a}function ff(...n){if(typeof n[0]==="string"){let i=dp(n[0]);return nx(i,n[1])}if(lJ(n[0])){let{connection:i,client:o,...c}=n[0];if(o)return nx(o,c);if(typeof i==="object"&&i.url!==void 0){let{url:x,...m}=i,a=dp(x,m);return nx(a,c)}let p=dp(i);return nx(p,c)}return nx(n[0],n[1])}((n)=>{function i(o){return nx({options:{parsers:{},serializers:{}}},o)}n.mock=i})(ff||(ff={}));var S0={};i8(S0,{users:()=>Ko,userChanges:()=>BG,untrackedUserColumnNames:()=>jG,twoFactorMethod:()=>kR,trackedUserColumnName:()=>IR,trackableUserColumnNames:()=>hR,role:()=>CR,players:()=>A0,passwordResetAttempts:()=>yG,loginHistory:()=>ix,games:()=>lf,banishedIps:()=>$f});function DR(n){return A`lower(${n})`}var CR=Pm("role",["admin","user"]),Ko=fc("users",{id:Ni().primaryKey().defaultRandom(),username:$i({length:16}).notNull(),email:$i({length:254}).notNull(),hash:$i({length:64}).notNull(),salt:$i({length:36}).notNull(),createdAt:Jo({withTimezone:!0}).notNull().defaultNow(),createdIp:$i({length:45}).notNull(),isActive:_x().notNull().default(!1),verifiedAt:Jo({withTimezone:!0}),userRole:CR().default("user")},(n)=>[$0("usernameUniqueIndex").on(DR(n.username)),$0("emailUniqueIndex").on(DR(n.email))]),jG=["id","createdAt","createdIp","isActive","salt","verifiedAt"],hR=["username","email","hash","userRole"],IR=Pm("trackedUserColumnName",hR),BG=fc("userChanges",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Ko.id),changedAt:Jo({withTimezone:!0}).notNull().defaultNow(),changedIp:$i({length:45}).notNull(),changedColumn:IR().notNull(),oldValue:$i({length:255}),newValue:$i({length:255})}),lf=fc("games",{id:Ni().primaryKey().defaultRandom()}),A0=fc("players",{userId:Ni().notNull().references(()=>Ko.id),gameId:Ni().notNull().references(()=>lf.id),score:xa().notNull()},(n)=>[iA({name:"players_userId_gameId_pk",columns:[n.userId,n.gameId]})]),ix=fc("loginHistory",{id:Ni().primaryKey().defaultRandom(),userId:Ni().references(()=>Ko.id),loginTime:Jo({withTimezone:!0}).notNull().defaultNow(),ipAddress:$i({length:45}).notNull(),userAgent:$i({length:1024}),successful:_x().notNull().default(!1)}),kR=Pm("twoFactorMethod",["email","phone"]),yG=fc("passwordResetAttempts",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Ko.id),requestedIp:$i({length:45}).notNull(),requestedAt:Jo({withTimezone:!0}).notNull().defaultNow(),succeededIp:$i({length:45}),succeededAt:Jo({withTimezone:!0}),verificationMethod:kR().notNull()}),$f=fc("banishedIps",{ip:$i({length:45}).primaryKey(),reason:$i({length:2048}).notNull(),banishedAt:Jo({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Jo({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class F0{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(LG.resolve(__dirname,"notify_update.sql"));let n=[di(Ko),di(lf),di(A0)];await this.sql`SELECT create_notify_triggers(${this.sql.array(n)})`,await this.sql.listen("table_update",(i)=>{let o=i.split(","),c=o[0],p=o[1],x=`${c}("${p}")`;if(this.observers.has(x))this.observers.get(x).next(x)})}constructor(n=!1,i={host:tn.POSTGRES_HOST,port:tn.POSTGRES_PORT,user:tn.POSTGRES_USER,password:tn.POSTGRES_PASSWORD,database:tn.POSTGRES_DATABASE}){this.options=i,this.sql=dp(i),this.drizzle=ff(this.sql,{schema:S0,logger:n})}observe(n,i){if(!this.observers.has(n))this.observers.set(n,new mn);this.observers.get(n).subscribe("SINGLETON",i)}}import{createHash as NG}from"crypto";function M0(n){let i=NG("sha256").update(n).digest("hex");return`${i.substring(0,8)}-${i.substring(8,12)}-${i.substring(12,16)}-${i.substring(16,20)}-${i.substring(20,32)}`}var sR=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var DG=3,CG=15,hG=/^[a-zA-Z0-9_-]+$/,PR=Kn.string().min(DG).max(CG).regex(hG),ZR=20,qR={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function IG(n){let i="";for(let o of n)if(o in qR)i+=qR[o];else i+=o;return i}function kG(n){let i=n.toLocaleLowerCase(),o=IG(i);for(let c of sR){if(o.includes(c))return!0;if(i.includes(c))return!0}return!1}function sG(n){let i=new Set(n).size;return n.length*Math.log2(i)}function ZG(n){let i=0,o=100;if(kG(n))i-=o;return i+=sG(n)*0.5,Math.max(i,0)}var tR=Kn.string().refine((n)=>{return ZG(n)>=ZR},{message:`Password does not meet the minimum complexity of ${ZR}.`}).brand("password"),rR=Kn.object({username:PR,password:tR}).strict(),qG=Kn.string().email().brand("email"),gR=Kn.object({username:PR,password:tR,email:qG}).strict();var vf={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},R0=V0(vf).map(([n])=>Kn.literal(Number(n))),PG=Kn.union([R0[0],R0[1],...R0]),dR=Kn.tuple([PG,Kn.string()]);var eR=nc({key:"count",default:0}),tG=Gc({key:"incrementTX",do:({set:n})=>{n(eR,(i)=>i+1)}}),n4=Jv({key:"countContinuity",config:(n)=>n.add(eR).add(tG)});var o4=y$(Mc,"backend.worker.game.bun",$n),rc=new F0({logQuery(n,i){$n.info("\uD83D\uDCDD query",n,i)}});on.STORE.loggers[0]=new Kc("info",void 0,$n);var QI=(()=>{let{__tribunalDaily:n}=globalThis;if(!n)n=new c4.CronJob("00 15 * * * *",()=>{y$(Mc,"backend.worker.tribunal.bun",$n)}),n.start(),process.on("exit",()=>{n.stop(),$n.info("\u231B tribunal daily cronjob stopped")}),$n.info("\u23F3 tribunal daily cronjob started");return n})();function dG(n){if(B$)return gG(B$,n);return rG({},n)}var p4=dG((n,i)=>{let o;n.on("data",(c)=>(o??=[]).push(c)).on("end",async()=>{let c=n.headers.authorization;try{if(typeof n.url==="undefined")throw[400,"No URL"];let p=n.socket.remoteAddress;if(!p)throw[400,"No IP address"];let x=new Date,m=new URL(n.url,tn.VITE_BACKEND_ORIGIN);$n.info(x,p,n.method,m.pathname);let a=await rc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:Qo($f.ip,p)}),f=a?.banishedUntil===null,l=a?.banishedUntil&&a.banishedUntil>x;if(f||l){$n.info(`\uD83D\uDE45 request from banned ip ${p}`);return}switch(n.method){case"POST":if(!o)throw[400,"No data received"];switch(m.pathname){case`/sign-up-${M0("sign-up")}`:{let $=Buffer.concat(o).toString(),v=JSON.parse($),T=gR.safeParse(v);if(!T.success){$n.warn("signup parsed",T.error.issues);return}let{username:F,password:R,email:S}=T.data;if($n.info(`\uD83D\uDD11 attempting to sign up: ${F}`),await rc.drizzle.query.users.findFirst({columns:{id:!0},where:Qo(Ko.email,S)}))throw[400,"User already exists"];let G=crypto.randomUUID(),H=i4("sha256").update(R+G).digest("hex");await rc.drizzle.insert(Ko).values({username:F,email:S,hash:H,salt:G,createdIp:p}),$n.info(`\uD83D\uDD11 user created: ${F}`),i.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(vf[201])}break;case`/login-${M0("login")}`:{let $=!1,v=null;try{let T=new Date(+x-600000);$n.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:T,now:x});let F=await rc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:Vc(Qo(ix.ipAddress,p),Qo(ix.successful,!1),ia(ix.loginTime,T)),limit:10});$n.info(`\uD83D\uDD11 ${F.length}/10 recent failed logins from ${p}`);let R=10-F.length;if(R<1)throw $n.info(`\uD83D\uDD11 too many recent failed logins from ${p}`),await rc.drizzle.insert($f).values({ip:p,reason:"Too many recent login attempts.",banishedAt:x,banishedUntil:new Date(+x+86400000)}),[429,"Too many recent login attempts."];let S=Buffer.concat(o).toString(),M=JSON.parse(S),G=rR.safeParse(M);if(!G.success)throw $n.warn("login parsed",G.error.issues),[400,`${R} attempts remaining.`];let{username:H,password:y}=G.data,k=await rc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:Qo(Ko.username,H)});if($n.info("\uD83D\uDD11 login attempt as user",H),!k)throw $n.info(`\uD83D\uDD11 user ${H} does not exist`),[400,`${R} attempts remaining.`];let{hash:Y,salt:K}=k;if(v=k.id,i4("sha256").update(y+K).digest("hex")===Y){let u=crypto.randomUUID(),V=sa.get(H);if(!V)V=new Map,sa.set(H,V);V.set(u,Number(x)),$=!0,$n.info("\uD83D\uDD11 login successful as",H),i.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(`${H} ${u}`)}}finally{await rc.drizzle.insert(ix).values({userId:v,successful:$,ipAddress:p,userAgent:n.headers["user-agent"]??"Withheld"}),$n.info(`\uD83D\uDD11 recorded login attempt from ${p}`)}}}}}catch(p){let x=dR.safeParse(p);if(x.success){let[m,a]=x.data,l=`${vf[m]}. ${a}`;$n.info(`\u274C ${m}: ${l}`),i.writeHead(m,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(l)}else $n.error(p),i.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end("Internal Server Error")}})}),W0=p4.listen(tn.BACKEND_PORT).address(),eG=typeof W0==="string"?null:W0===null?null:W0.port;if(eG===null)throw new Error("Could not determine port for test server");new gM(p4,{cors:{origin:tn.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((n,i)=>{let{username:o,sessionKey:c}=n.handshake.auth;if(!(o&&c)){i(new Error("No auth header provided"));return}let p=`user::${o}`,x=`socket::${n.id}`;if(sa.get(o)?.has(c)){let a=Tn(on.STORE,zm,x);Yn(on.STORE,a,n),Wc(Yc,(f)=>{f.set(p,x)},on.STORE),Yn(on.STORE,hf,(f)=>f.add(p)),Yn(on.STORE,Cf,(f)=>f.add(x)),$n.info(`${o} connected on ${n.id}`),i()}else $n.info(`${o} couldn't authenticate`),i(new Error("Authentication error"))}).on("connection",(n)=>{let o=Kv({socket:n,store:on.STORE})(n4);n.on("disconnect",()=>{let c=`socket::${n.id}`,p=op(Yc,c,on.STORE).userKeyOfSocket,x=An(on.STORE,p);if(Wc(Yc,(m)=>{m.delete(c)},on.STORE),x)Yn(on.STORE,hf,(m)=>(m.delete(x),m));Yn(on.STORE,Cf,(m)=>(m.delete(c),m)),$n.info(`${n.id} disconnected`),o()})});async function Tf(){$n.info("\uD83E\uDDF9 closing workers");let n=new Promise((i)=>o4.process.once("close",i));o4.process.emit("timeToStop"),await n,$n.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{$n.info("\u2757 received SIGINT; exiting gracefully"),await Tf()});process.on("SIGTERM",async()=>{$n.info("\u2757 received SIGTERM; exiting gracefully"),await Tf()});process.on("exit",async()=>{$n.info("\u2757 received exit; exiting gracefully"),await Tf()});Mc.on("updatesReady",()=>{$n.info('\u2757 backend server received signal "updatesReady"'),Mc.emit("readyToUpdate"),$n.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),Mc.on("timeToStop",async()=>{$n.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await Tf()})});$n.info(`\uD83D\uDEEB backend server ready on port ${tn.BACKEND_PORT}`);Mc.emit("alive");export{QI as tribunalDaily};
|
|
80
|
+
`;await i.execute(A`CREATE SCHEMA IF NOT EXISTS ${A.identifier(p)}`),await i.execute(x);let a=(await i.all(A`select id, hash, created_at from ${A.identifier(p)}.${A.identifier(c)} order by created_at desc limit 1`))[0];await i.transaction(async(f)=>{for await(let l of n)if(!a||Number(a.created_at)<l.folderMillis){for(let $ of l.sql)await f.execute(A.raw($));await f.execute(A`insert into ${A.identifier(p)}.${A.identifier(c)} ("hash", "created_at") values(${l.hash}, ${l.folderMillis})`)}})}escapeName(n){return`"${n}"`}escapeParam(n){return`$${n+1}`}escapeString(n){return`'${n.replace(/'/g,"''")}'`}buildWithCTE(n){if(!n?.length)return;let i=[A`with `];for(let[o,c]of n.entries())if(i.push(A`${A.identifier(c._.alias)} as (${c._.sql})`),o<n.length-1)i.push(A`, `);return i.push(A` `),A.join(i)}buildDeleteQuery({table:n,where:i,returning:o,withList:c}){let p=this.buildWithCTE(c),x=o?A` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,m=i?A` where ${i}`:void 0;return A`${p}delete from ${n}${m}${x}`}buildUpdateSet(n,i){let o=n[L.Symbol.Columns],c=Object.keys(o).filter((x)=>i[x]!==void 0||o[x]?.onUpdateFn!==void 0),p=c.length;return A.join(c.flatMap((x,m)=>{let a=o[x],f=i[x]??A.param(a.onUpdateFn(),a),l=A`${A.identifier(this.casing.getColumnCasing(a))} = ${f}`;if(m<p-1)return[l,A.raw(", ")];return[l]}))}buildUpdateQuery({table:n,set:i,where:o,returning:c,withList:p,from:x,joins:m}){let a=this.buildWithCTE(p),f=n[vi.Symbol.Name],l=n[vi.Symbol.Schema],$=n[vi.Symbol.OriginalName],v=f===$?void 0:f,T=A`${l?A`${A.identifier(l)}.`:void 0}${A.identifier($)}${v&&A` ${A.identifier(v)}`}`,F=this.buildUpdateSet(n,i),R=x&&A.join([A.raw(" from "),this.buildFromTable(x)]),S=this.buildJoins(m),M=c?A` returning ${this.buildSelection(c,{isSingleTable:!x})}`:void 0,G=o?A` where ${o}`:void 0;return A`${a}update ${T} set ${F}${R}${S}${G}${M}`}buildSelection(n,{isSingleTable:i=!1}={}){let o=n.length,c=n.flatMap(({field:p},x)=>{let m=[];if(z(p,N.Aliased)&&p.isSelectionField)m.push(A.identifier(p.fieldAlias));else if(z(p,N.Aliased)||z(p,N)){let a=z(p,N.Aliased)?p.sql:p;if(i)m.push(new N(a.queryChunks.map((f)=>{if(z(f,_))return A.identifier(this.casing.getColumnCasing(f));return f})));else m.push(a);if(z(p,N.Aliased))m.push(A` as ${A.identifier(p.fieldAlias)}`)}else if(z(p,On))if(i)m.push(A.identifier(this.casing.getColumnCasing(p)));else m.push(p);if(x<o-1)m.push(A`, `);return m});return A.join(c)}buildJoins(n){if(!n||n.length===0)return;let i=[];for(let[o,c]of n.entries()){if(o===0)i.push(A` `);let p=c.table,x=c.lateral?A` lateral`:void 0;if(z(p,vi)){let m=p[vi.Symbol.Name],a=p[vi.Symbol.Schema],f=p[vi.Symbol.OriginalName],l=m===f?void 0:c.alias;i.push(A`${A.raw(c.joinType)} join${x} ${a?A`${A.identifier(a)}.`:void 0}${A.identifier(f)}${l&&A` ${A.identifier(l)}`} on ${c.on}`)}else if(z(p,ui)){let m=p[Bn].name,a=p[Bn].schema,f=p[Bn].originalName,l=m===f?void 0:c.alias;i.push(A`${A.raw(c.joinType)} join${x} ${a?A`${A.identifier(a)}.`:void 0}${A.identifier(f)}${l&&A` ${A.identifier(l)}`} on ${c.on}`)}else i.push(A`${A.raw(c.joinType)} join${x} ${p} on ${c.on}`);if(o<n.length-1)i.push(A` `)}return A.join(i)}buildFromTable(n){if(z(n,L)&&n[L.Symbol.OriginalName]!==n[L.Symbol.Name]){let i=A`${A.identifier(n[L.Symbol.OriginalName])}`;if(n[L.Symbol.Schema])i=A`${A.identifier(n[L.Symbol.Schema])}.${i}`;return A`${i} ${A.identifier(n[L.Symbol.Name])}`}return n}buildSelectQuery({withList:n,fields:i,fieldsFlat:o,where:c,having:p,table:x,joins:m,orderBy:a,groupBy:f,limit:l,offset:$,lockingClause:v,distinct:T,setOperators:F}){let R=o??ei(i);for(let q of R)if(z(q.field,On)&&di(q.field.table)!==(z(x,ci)?x._.alias:z(x,cm)?x[Bn].name:z(x,N)?void 0:di(x))&&!((Xn)=>m?.some(({alias:Un})=>Un===(Xn[L.Symbol.IsAlias]?di(Xn):Xn[L.Symbol.BaseName])))(q.field.table)){let Xn=di(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${Xn}"."${q.field.name}", but the table "${Xn}" is not part of the query! Did you forget to join it?`)}let S=!m||m.length===0,M=this.buildWithCTE(n),G;if(T)G=T===!0?A` distinct`:A` distinct on (${A.join(T.on,A`, `)})`;let H=this.buildSelection(R,{isSingleTable:S}),y=this.buildFromTable(x),k=this.buildJoins(m),Y=c?A` where ${c}`:void 0,K=p?A` having ${p}`:void 0,Q;if(a&&a.length>0)Q=A` order by ${A.join(a,A`, `)}`;let u;if(f&&f.length>0)u=A` group by ${A.join(f,A`, `)}`;let V=typeof l==="object"||typeof l==="number"&&l>=0?A` limit ${l}`:void 0,X=$?A` offset ${$}`:void 0,s=A.empty();if(v){let q=A` for ${A.raw(v.strength)}`;if(v.config.of)q.append(A` of ${A.join(Array.isArray(v.config.of)?v.config.of:[v.config.of],A`, `)}`);if(v.config.noWait)q.append(A` no wait`);else if(v.config.skipLocked)q.append(A` skip locked`);s.append(q)}let C=A`${M}select${G} ${H} from ${y}${k}${Y}${u}${K}${Q}${V}${X}${s}`;if(F.length>0)return this.buildSetOperations(C,F);return C}buildSetOperations(n,i){let[o,...c]=i;if(!o)throw new Error("Cannot pass undefined values to any set operator");if(c.length===0)return this.buildSetOperationQuery({leftSelect:n,setOperator:o});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:n,setOperator:o}),c)}buildSetOperationQuery({leftSelect:n,setOperator:{type:i,isAll:o,rightSelect:c,limit:p,orderBy:x,offset:m}}){let a=A`(${n.getSQL()}) `,f=A`(${c.getSQL()})`,l;if(x&&x.length>0){let F=[];for(let R of x)if(z(R,_))F.push(A.identifier(R.name));else if(z(R,N)){for(let S=0;S<R.queryChunks.length;S++){let M=R.queryChunks[S];if(z(M,_))R.queryChunks[S]=A.identifier(M.name)}F.push(A`${R}`)}else F.push(A`${R}`);l=A` order by ${A.join(F,A`, `)} `}let $=typeof p==="object"||typeof p==="number"&&p>=0?A` limit ${p}`:void 0,v=A.raw(`${i} ${o?"all ":""}`),T=m?A` offset ${m}`:void 0;return A`${a}${v}${f}${l}${$}${T}`}buildInsertQuery({table:n,values:i,onConflict:o,returning:c,withList:p,select:x,overridingSystemValue_:m}){let a=[],f=n[L.Symbol.Columns],l=Object.entries(f).filter(([M,G])=>!G.shouldDisableInsert()),$=l.map(([,M])=>A.identifier(this.casing.getColumnCasing(M)));if(x){let M=i;if(z(M,N))a.push(M);else a.push(M.getSQL())}else{let M=i;a.push(A.raw("values "));for(let[G,H]of M.entries()){let y=[];for(let[k,Y]of l){let K=H[k];if(K===void 0||z(K,Li)&&K.value===void 0)if(Y.defaultFn!==void 0){let Q=Y.defaultFn(),u=z(Q,N)?Q:A.param(Q,Y);y.push(u)}else if(!Y.default&&Y.onUpdateFn!==void 0){let Q=Y.onUpdateFn(),u=z(Q,N)?Q:A.param(Q,Y);y.push(u)}else y.push(A`default`);else y.push(K)}if(a.push(y),G<M.length-1)a.push(A`, `)}}let v=this.buildWithCTE(p),T=A.join(a),F=c?A` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,R=o?A` on conflict ${o}`:void 0,S=m===!0?A`overriding system value `:void 0;return A`${v}insert into ${n} ${$} ${S}${T}${R}${F}`}buildRefreshMaterializedViewQuery({view:n,concurrently:i,withNoData:o}){let c=i?A` concurrently`:void 0,p=o?A` with no data`:void 0;return A`refresh materialized view${c} ${n}${p}`}prepareTyping(n){if(z(n,aa)||z(n,ma))return"json";else if(z(n,fa))return"decimal";else if(z(n,la))return"time";else if(z(n,$a)||z(n,va))return"timestamp";else if(z(n,ca)||z(n,pa))return"date";else if(z(n,Ta))return"uuid";else return"none"}sqlToQuery(n,i){return n.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:i})}buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:c,tableConfig:p,queryConfig:x,tableAlias:m,nestedQueryRelation:a,joinOn:f}){let l=[],$,v,T=[],F,R=[];if(x===!0)l=Object.entries(p.columns).map(([G,H])=>({dbKey:H.name,tsKey:G,field:Ho(H,m),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(p.columns).map(([K,Q])=>[K,Ho(Q,m)]));if(x.where){let K=typeof x.where==="function"?x.where(M,pA()):x.where;F=K&&Ux(K,m)}let G=[],H=[];if(x.columns){let K=!1;for(let[Q,u]of Object.entries(x.columns)){if(u===void 0)continue;if(Q in p.columns){if(!K&&u===!0)K=!0;H.push(Q)}}if(H.length>0)H=K?H.filter((Q)=>x.columns?.[Q]===!0):Object.keys(p.columns).filter((Q)=>!H.includes(Q))}else H=Object.keys(p.columns);for(let K of H){let Q=p.columns[K];G.push({tsKey:K,value:Q})}let y=[];if(x.with)y=Object.entries(x.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:p.relations[K]}));let k;if(x.extras){k=typeof x.extras==="function"?x.extras(M,{sql:A}):x.extras;for(let[K,Q]of Object.entries(k))G.push({tsKey:K,value:El(Q,m)})}for(let{tsKey:K,value:Q}of G)l.push({dbKey:z(Q,N.Aliased)?Q.fieldAlias:p.columns[K].name,tsKey:K,field:z(Q,On)?Ho(Q,m):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof x.orderBy==="function"?x.orderBy(M,xA()):x.orderBy??[];if(!Array.isArray(Y))Y=[Y];T=Y.map((K)=>{if(z(K,On))return Ho(K,m);return Ux(K,m)}),$=x.limit,v=x.offset;for(let{tsKey:K,queryConfig:Q,relation:u}of y){let V=aA(i,o,u),X=Uc(u.referencedTable),s=o[X],C=`${m}_${K}`,q=Vc(...V.fields.map((Vi,_o)=>Qo(Ho(V.references[_o],C),Ho(Vi,m)))),Xn=this.buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:n[s],tableConfig:i[s],queryConfig:z(u,lc)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:C,joinOn:q,nestedQueryRelation:u}),Un=A`${A.identifier(C)}.${A.identifier("data")}`.as(K);R.push({on:A`true`,table:new ci(Xn.sql,{},C),alias:C,joinType:"left",lateral:!0}),l.push({dbKey:K,tsKey:K,field:Un,relationTableTsKey:s,isJson:!0,selection:Xn.selection})}}if(l.length===0)throw new na({message:`No fields selected for table "${p.tsName}" ("${m}")`});let S;if(F=Vc(f,F),a){let M=A`json_build_array(${A.join(l.map(({field:y,tsKey:k,isJson:Y})=>Y?A`${A.identifier(`${m}_${k}`)}.${A.identifier("data")}`:z(y,N.Aliased)?y.sql:y),A`, `)})`;if(z(a,bx))M=A`coalesce(json_agg(${M}${T.length>0?A` order by ${A.join(T,A`, `)}`:void 0}), '[]'::json)`;let G=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:p.tsName,selection:l}];if($!==void 0||v!==void 0||T.length>0)S=this.buildSelectQuery({table:em(c,m),fields:{},fieldsFlat:[{path:[],field:A.raw("*")}],where:F,limit:$,offset:v,orderBy:T,setOperators:[]}),F=void 0,$=void 0,v=void 0,T=[];else S=em(c,m);S=this.buildSelectQuery({table:z(S,vi)?S:new ci(S,{},m),fields:{},fieldsFlat:G.map(({field:y})=>({path:[],field:z(y,On)?Ho(y,m):y})),joins:R,where:F,limit:$,offset:v,orderBy:T,setOperators:[]})}else S=this.buildSelectQuery({table:em(c,m),fields:{},fieldsFlat:l.map(({field:M})=>({path:[],field:z(M,On)?Ho(M,m):M})),joins:R,where:F,limit:$,offset:v,orderBy:T,setOperators:[]});return{tableTsKey:p.tsName,sql:S,selection:l}}}class Ti{static[w]="SelectionProxyHandler";config;constructor(n){this.config={...n}}get(n,i){if(i==="_")return{...n._,selectedFields:new Proxy(n._.selectedFields,this)};if(i===Bn)return{...n[Bn],selectedFields:new Proxy(n[Bn].selectedFields,this)};if(typeof i==="symbol")return n[i];let c=(z(n,ci)?n._.selectedFields:z(n,ui)?n[Bn].selectedFields:n)[i];if(z(c,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!c.isSelectionField)return c.sql;let p=c.clone();return p.isSelectionField=!0,p}if(z(c,N)){if(this.config.sqlBehavior==="sql")return c;throw new Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(z(c,On)){if(this.config.alias)return new Proxy(c,new Rp(new Proxy(c.table,new Ex(this.config.alias,this.config.replaceOriginalName??!1))));return c}if(typeof c!=="object"||c===null)return c;return new Proxy(c,new Ti(this.config))}}class c0{static[w]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Ui{static[w]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(n){if(this.fields=n.fields,this.session=n.session,this.dialect=n.dialect,n.withList)this.withList=n.withList;this.distinct=n.distinct}authToken;setToken(n){return this.authToken=n,this}from(n){let i=!!this.fields,o;if(this.fields)o=this.fields;else if(z(n,ci))o=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(z(n,cm))o=n[Bn].selectedFields;else if(z(n,N))o={};else o=fJ(n);return new p0({table:n,fields:o,isPartialSelect:i,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class bR extends c0{static[w]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:n,fields:i,isPartialSelect:o,session:c,dialect:p,withList:x,distinct:m}){super();this.config={withList:x,table:n,fields:{...i},distinct:m,setOperators:[]},this.isPartialSelect=o,this.session=c,this.dialect=p,this._={selectedFields:i},this.tableName=yo(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(n){return(i,o)=>{let c=this.tableName,p=yo(i);if(typeof p==="string"&&this.config.joins?.some((x)=>x.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof c==="string")this.config.fields={[c]:this.config.fields};if(typeof p==="string"&&!z(i,N)){let x=z(i,ci)?i._.selectedFields:z(i,ui)?i[Bn].selectedFields:i[L.Symbol.Columns];this.config.fields[p]=x}}if(typeof o==="function")o=o(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:o,table:i,joinType:n,alias:p}),typeof p==="string")switch(n){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(n,i){return(o)=>{let c=typeof o==="function"?o(OG()):o;if(!Vx(this.getSelectedFields(),c.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:n,isAll:i,rightSelect:c}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(n){return this.config.setOperators.push(...n),this}where(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=n,this}having(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=n,this}groupBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=n;return this}orderBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new Ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),o=Array.isArray(i)?i:[i];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}else{let i=n;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=i;else this.config.orderBy=i}return this}limit(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=n;else this.config.limit=n;return this}offset(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=n;else this.config.offset=n;return this}for(n,i={}){return this.config.lockingClause={strength:n,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(n){return new Proxy(new ci(this.getSQL(),this.config.fields,n),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Ti({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class p0 extends bR{static[w]="PgSelect";_prepare(n){let{session:i,config:o,dialect:c,joinsNotNullableMap:p,authToken:x}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return En.startActiveSpan("drizzle.prepareQuery",()=>{let m=ei(o.fields),a=i.prepareQuery(c.sqlToQuery(this.getSQL()),m,n,!0);return a.joinsNotNullableMap=p,a.setToken(x)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})}}aJ(p0,[Qi]);function ep(n,i){return(o,c,...p)=>{let x=[c,...p].map((m)=>({type:n,isAll:i,rightSelect:m}));for(let m of x)if(!Vx(o.getSelectedFields(),m.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return o.addSetOperators(x)}}var OG=()=>({union:EG,unionAll:UG,intersect:VG,intersectAll:_G,except:uG,exceptAll:bG}),EG=ep("union",!1),UG=ep("union",!0),VG=ep("intersect",!1),_G=ep("intersect",!0),uG=ep("except",!1),bG=ep("except",!0);class pm{static[w]="PgQueryBuilder";dialect;dialectConfig;constructor(n){this.dialect=z(n,tc)?n:void 0,this.dialectConfig=z(n,tc)?void 0:n}$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(i);return new Proxy(new Ox(o.getSQL(),o.getSelectedFields(),n,!0),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...n){let i=this;function o(x){return new Ui({fields:x??void 0,session:void 0,dialect:i.getDialect(),withList:n})}function c(x){return new Ui({fields:x??void 0,session:void 0,dialect:i.getDialect(),distinct:!0})}function p(x,m){return new Ui({fields:m??void 0,session:void 0,dialect:i.getDialect(),distinct:{on:x}})}return{select:o,selectDistinct:c,selectDistinctOn:p}}select(n){return new Ui({fields:n??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(n){return new Ui({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(n,i){return new Ui({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:n}})}getDialect(){if(!this.dialect)this.dialect=new tc(this.dialectConfig);return this.dialect}}class xf{constructor(n,i,o,c,p){this.table=n,this.session=i,this.dialect=o,this.withList=c,this.overridingSystemValue_=p}static[w]="PgInsertBuilder";authToken;setToken(n){return this.authToken=n,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(n){if(n=Array.isArray(n)?n:[n],n.length===0)throw new Error("values() must be called with at least one value");let i=n.map((o)=>{let c={},p=this.table[L.Symbol.Columns];for(let x of Object.keys(o)){let m=o[x];c[x]=z(m,N)?m:new Li(m,p[x])}return c});return new x0(this.table,i,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(n){let i=typeof n==="function"?n(new pm):n;if(!z(i,N)&&!Vx(this.table[rm],i._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new x0(this.table,i,this.session,this.dialect,this.withList,!0)}}class x0 extends Qi{constructor(n,i,o,c,p,x,m){super();this.session=o,this.dialect=c,this.config={table:n,values:i,withList:p,select:x,overridingSystemValue_:m}}static[w]="PgInsert";config;returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}onConflictDoNothing(n={}){if(n.target===void 0)this.config.onConflict=A`do nothing`;else{let i="";i=Array.isArray(n.target)?n.target.map((c)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(c))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target));let o=n.where?A` where ${n.where}`:void 0;this.config.onConflict=A`(${A.raw(i)})${o} do nothing`}return this}onConflictDoUpdate(n){if(n.where&&(n.targetWhere||n.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let i=n.where?A` where ${n.where}`:void 0,o=n.targetWhere?A` where ${n.targetWhere}`:void 0,c=n.setWhere?A` where ${n.setWhere}`:void 0,p=this.dialect.buildUpdateSet(this.config.table,oa(this.config.table,n.set)),x="";return x=Array.isArray(n.target)?n.target.map((m)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(m))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target)),this.config.onConflict=A`(${A.raw(x)})${o} do update set ${p}${i}${c}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})};$dynamic(){return this}}class m0 extends Qi{constructor(n,i,o){super();this.session=i,this.dialect=o,this.config={view:n}}static[w]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,n,!0)})}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n,this.authToken)})}}class mf{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[w]="PgUpdateBuilder";authToken;setToken(n){return this.authToken=n,this}set(n){return new jR(this.table,oa(this.table,n),this.session,this.dialect,this.withList).setToken(this.authToken)}}class jR extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={set:i,table:n,withList:p,joins:[]},this.tableName=yo(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[w]="PgUpdate";config;tableName;joinsNotNullableMap;from(n){let i=yo(n);if(typeof i==="string")this.joinsNotNullableMap[i]=!0;return this.config.from=n,this}getTableLikeFields(n){if(z(n,vi))return n[L.Symbol.Columns];else if(z(n,ci))return n._.selectedFields;return n[Bn].selectedFields}createJoin(n){return(i,o)=>{let c=yo(i);if(typeof c==="string"&&this.config.joins.some((p)=>p.alias===c))throw new Error(`Alias "${c}" is already used in this query`);if(typeof o==="function"){let p=this.config.from&&!z(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;o=o(new Proxy(this.config.table[L.Symbol.Columns],new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),p&&new Proxy(p,new Ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:o,table:i,joinType:n,alias:c}),typeof c==="string")switch(n){case"left":{this.joinsNotNullableMap[c]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([p])=>[p,!1])),this.joinsNotNullableMap[c]=!0;break}case"inner":{this.joinsNotNullableMap[c]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([p])=>[p,!1])),this.joinsNotNullableMap[c]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(n){return this.config.where=n,this}returning(n){if(!n){if(n=Object.assign({},this.config.table[L.Symbol.Columns]),this.config.from){let i=yo(this.config.from);if(typeof i==="string"&&this.config.from&&!z(this.config.from,N)){let o=this.getTableLikeFields(this.config.from);n[i]=o}for(let o of this.config.joins){let c=yo(o.table);if(typeof c==="string"&&!z(o.table,N)){let p=this.getTableLikeFields(o.table);n[c]=p}}}}return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){let i=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}prepare(n){return this._prepare(n)}authToken;setToken(n){return this.authToken=n,this}execute=(n)=>{return this._prepare().execute(n,this.authToken)};$dynamic(){return this}}class xm extends N{constructor(n){super(xm.buildEmbeddedCount(n.source,n.filters).queryChunks);this.params=n,this.mapWith(Number),this.session=n.session,this.sql=xm.buildCount(n.source,n.filters)}sql;token;static[w]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(n,i){return A`(select count(*) from ${n}${A.raw(" where ").if(i)}${i})`}static buildCount(n,i){return A`select count(*) as count from ${n}${A.raw(" where ").if(i)}${i};`}setToken(n){return this.token=n,this}then(n,i){return Promise.resolve(this.session.count(this.sql,this.token)).then(n,i)}catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}}class f0{constructor(n,i,o,c,p,x,m){this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=x,this.session=m}static[w]="PgRelationalQueryBuilder";findMany(n){return new a0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?n:{},"many")}findFirst(n){return new a0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?{...n,limit:1}:{limit:1},"first")}}class a0 extends Qi{constructor(n,i,o,c,p,x,m,a,f){super();this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=x,this.session=m,this.config=a,this.mode=f}static[w]="PgRelationalQuery";_prepare(n){return En.startActiveSpan("drizzle.prepareQuery",()=>{let{query:i,builtQuery:o}=this._toSQL();return this.session.prepareQuery(o,void 0,n,!0,(c,p)=>{let x=c.map((m)=>Ja(this.schema,this.tableConfig,m,i.selection,p));if(this.mode==="first")return x[0];return x})})}prepare(n){return this._prepare(n)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let n=this._getQuery(),i=this.dialect.sqlToQuery(n.sql);return{query:n,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(n){return this.authToken=n,this}execute(){return En.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class l0 extends Qi{constructor(n,i,o,c){super();this.execute=n,this.sql=i,this.query=o,this.mapBatchResult=c}static[w]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(n,i){return i?this.mapBatchResult(n):n}_prepare(){return this}isResponseInArrayMode(){return!1}}class mm{constructor(n,i,o){if(this.dialect=n,this.session=i,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,session:i}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:i},this.query={},this._.schema)for(let[c,p]of Object.entries(this._.schema))this.query[c]=new f0(o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[c],p,n,i)}static[w]="PgDatabase";query;$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(new pm(i.dialect));return new Proxy(new Ox(o.getSQL(),o.getSelectedFields(),n,!0),new Ti({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(n,i){return new xm({source:n,filters:i,session:this.session})}with(...n){let i=this;function o(f){return new Ui({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n})}function c(f){return new Ui({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:!0})}function p(f,l){return new Ui({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:{on:f}})}function x(f){return new mf(f,i.session,i.dialect,n)}function m(f){return new xf(f,i.session,i.dialect,n)}function a(f){return new pf(f,i.session,i.dialect,n)}return{select:o,selectDistinct:c,selectDistinctOn:p,update:x,insert:m,delete:a}}select(n){return new Ui({fields:n??void 0,session:this.session,dialect:this.dialect})}selectDistinct(n){return new Ui({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(n,i){return new Ui({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:{on:n}})}update(n){return new mf(n,this.session,this.dialect)}insert(n){return new xf(n,this.session,this.dialect)}delete(n){return new pf(n,this.session,this.dialect)}refreshMaterializedView(n){return new m0(n,this.session,this.dialect)}authToken;execute(n){let i=typeof n==="string"?A.raw(n):n.getSQL(),o=this.dialect.sqlToQuery(i),c=this.session.prepareQuery(o,void 0,void 0,!1);return new l0(()=>c.execute(void 0,this.authToken),i,o,(p)=>c.mapResult(p,!0))}transaction(n,i){return this.session.transaction(n,i)}}class BR{constructor(n,i){this.unique=n,this.name=i}static[w]="PgIndexBuilderOn";on(...n){return new af(n.map((i)=>{if(z(i,N))return i;i=i;let o=new Qx(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),o}),this.unique,!1,this.name)}onOnly(...n){return new af(n.map((i)=>{if(z(i,N))return i;i=i;let o=new Qx(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=i.defaultConfig,o}),this.unique,!0,this.name)}using(n,...i){return new af(i.map((o)=>{if(z(o,N))return o;o=o;let c=new Qx(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),c}),this.unique,!0,this.name,n)}}class af{static[w]="PgIndexBuilder";config;constructor(n,i,o,c,p="btree"){this.config={name:c,columns:n,unique:i,only:o,method:p}}concurrently(){return this.config.concurrently=!0,this}with(n){return this.config.with=n,this}where(n){return this.config.where=n,this}build(n){return new yR(this.config,n)}}class yR{static[w]="PgIndex";config;constructor(n,i){this.config={...n,table:i}}}function $0(n){return new BR(!0,n)}class v0{constructor(n){this.query=n}authToken;getQuery(){return this.query}mapResult(n,i){return n}setToken(n){return this.authToken=n,this}static[w]="PgPreparedQuery";joinsNotNullableMap}class T0{constructor(n){this.dialect=n}static[w]="PgSession";execute(n,i){return En.startActiveSpan("drizzle.operation",()=>{return En.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1)}).setToken(i).execute(void 0,i)})}all(n){return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1).all()}async count(n,i){let o=await this.execute(n,i);return Number(o[0].count)}}class J0 extends mm{constructor(n,i,o,c=0){super(n,i,o);this.schema=o,this.nestedIndex=c}static[w]="PgTransaction";rollback(){throw new Ul}getTransactionConfigSQL(n){let i=[];if(n.isolationLevel)i.push(`isolation level ${n.isolationLevel}`);if(n.accessMode)i.push(n.accessMode);if(typeof n.deferrable==="boolean")i.push(n.deferrable?"deferrable":"not deferrable");return A.raw(i.join(" "))}setTransaction(n){return this.session.execute(A`set transaction ${this.getTransactionConfigSQL(n)}`)}}class LR extends v0{constructor(n,i,o,c,p,x,m){super({sql:i,params:o});this.client=n,this.queryString=i,this.params=o,this.logger=c,this.fields=p,this._isResponseInArrayMode=x,this.customResultMapper=m}static[w]="PostgresJsPreparedQuery";async execute(n={}){return En.startActiveSpan("drizzle.execute",async(i)=>{let o=Ol(this.params,n);i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o);let{fields:c,queryString:p,client:x,joinsNotNullableMap:m,customResultMapper:a}=this;if(!c&&!a)return En.startActiveSpan("drizzle.driver.execute",()=>{return x.unsafe(p,o)});let f=await En.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":p,"drizzle.query.params":JSON.stringify(o)}),x.unsafe(p,o).values()});return En.startActiveSpan("drizzle.mapResponse",()=>{return a?a(f):f.map((l)=>mJ(c,l,m))})})}all(n={}){return En.startActiveSpan("drizzle.execute",async(i)=>{let o=Ol(this.params,n);return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o),En.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.client.unsafe(this.queryString,o)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class am extends T0{constructor(n,i,o,c={}){super(i);this.client=n,this.schema=o,this.options=c,this.logger=c.logger??new _l}static[w]="PostgresJsSession";logger;prepareQuery(n,i,o,c,p){return new LR(this.client,n.sql,n.params,this.logger,i,c,p)}query(n,i){return this.logger.logQuery(n,i),this.client.unsafe(n,i).values()}queryObjects(n,i){return this.client.unsafe(n,i)}transaction(n,i){return this.client.begin(async(o)=>{let c=new am(o,this.dialect,this.schema,this.options),p=new w0(this.dialect,c,this.schema);if(i)await p.setTransaction(i);return n(p)})}}class w0 extends J0{constructor(n,i,o,c=0){super(n,i,o,c);this.session=i}static[w]="PostgresJsTransaction";transaction(n){return this.session.client.savepoint((i)=>{let o=new am(i,this.dialect,this.schema,this.session.options),c=new w0(this.dialect,o,this.schema);return n(c)})}}class NR extends mm{static[w]="PostgresJsDatabase"}function nx(n,i={}){let o=(f)=>f;for(let f of["1184","1082","1083","1114"])n.options.parsers[f]=o,n.options.serializers[f]=o;n.options.serializers["114"]=o,n.options.serializers["3802"]=o;let c=new tc({casing:i.casing}),p;if(i.logger===!0)p=new Vl;else if(i.logger!==!1)p=i.logger;let x;if(i.schema){let f=mA(i.schema,fA);x={fullSchema:i.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}let m=new am(n,c,x,{logger:p}),a=new NR(c,m,x);return a.$client=n,a}function ff(...n){if(typeof n[0]==="string"){let i=dp(n[0]);return nx(i,n[1])}if(lJ(n[0])){let{connection:i,client:o,...c}=n[0];if(o)return nx(o,c);if(typeof i==="object"&&i.url!==void 0){let{url:x,...m}=i,a=dp(x,m);return nx(a,c)}let p=dp(i);return nx(p,c)}return nx(n[0],n[1])}((n)=>{function i(o){return nx({options:{parsers:{},serializers:{}}},o)}n.mock=i})(ff||(ff={}));var S0={};i8(S0,{users:()=>Ko,userChanges:()=>BG,untrackedUserColumnNames:()=>jG,twoFactorMethod:()=>kR,trackedUserColumnName:()=>IR,trackableUserColumnNames:()=>hR,role:()=>CR,players:()=>A0,passwordResetAttempts:()=>yG,loginHistory:()=>ix,games:()=>lf,banishedIps:()=>$f});function DR(n){return A`lower(${n})`}var CR=Pm("role",["admin","user"]),Ko=fc("users",{id:Ni().primaryKey().defaultRandom(),username:$i({length:16}).notNull(),email:$i({length:254}).notNull(),hash:$i({length:64}).notNull(),salt:$i({length:36}).notNull(),createdAt:Jo({withTimezone:!0}).notNull().defaultNow(),createdIp:$i({length:45}).notNull(),isActive:_x().notNull().default(!1),verifiedAt:Jo({withTimezone:!0}),userRole:CR().default("user")},(n)=>[$0("usernameUniqueIndex").on(DR(n.username)),$0("emailUniqueIndex").on(DR(n.email))]),jG=["id","createdAt","createdIp","isActive","salt","verifiedAt"],hR=["username","email","hash","userRole"],IR=Pm("trackedUserColumnName",hR),BG=fc("userChanges",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Ko.id),changedAt:Jo({withTimezone:!0}).notNull().defaultNow(),changedIp:$i({length:45}).notNull(),changedColumn:IR().notNull(),oldValue:$i({length:255}),newValue:$i({length:255})}),lf=fc("games",{id:Ni().primaryKey().defaultRandom()}),A0=fc("players",{userId:Ni().notNull().references(()=>Ko.id),gameId:Ni().notNull().references(()=>lf.id),score:xa().notNull()},(n)=>[iA({name:"players_userId_gameId_pk",columns:[n.userId,n.gameId]})]),ix=fc("loginHistory",{id:Ni().primaryKey().defaultRandom(),userId:Ni().references(()=>Ko.id),loginTime:Jo({withTimezone:!0}).notNull().defaultNow(),ipAddress:$i({length:45}).notNull(),userAgent:$i({length:1024}),successful:_x().notNull().default(!1)}),kR=Pm("twoFactorMethod",["email","phone"]),yG=fc("passwordResetAttempts",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Ko.id),requestedIp:$i({length:45}).notNull(),requestedAt:Jo({withTimezone:!0}).notNull().defaultNow(),succeededIp:$i({length:45}),succeededAt:Jo({withTimezone:!0}),verificationMethod:kR().notNull()}),$f=fc("banishedIps",{ip:$i({length:45}).primaryKey(),reason:$i({length:2048}).notNull(),banishedAt:Jo({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Jo({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class F0{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(LG.resolve(__dirname,"notify_update.sql"));let n=[di(Ko),di(lf),di(A0)];await this.sql`SELECT create_notify_triggers(${this.sql.array(n)})`,await this.sql.listen("table_update",(i)=>{let o=i.split(","),c=o[0],p=o[1],x=`${c}("${p}")`;if(this.observers.has(x))this.observers.get(x).next(x)})}constructor(n=!1,i={host:tn.POSTGRES_HOST,port:tn.POSTGRES_PORT,user:tn.POSTGRES_USER,password:tn.POSTGRES_PASSWORD,database:tn.POSTGRES_DATABASE}){this.options=i,this.sql=dp(i),this.drizzle=ff(this.sql,{schema:S0,logger:n})}observe(n,i){if(!this.observers.has(n))this.observers.set(n,new mn);this.observers.get(n).subscribe("SINGLETON",i)}}import{createHash as NG}from"crypto";function M0(n){let i=NG("sha256").update(n).digest("hex");return`${i.substring(0,8)}-${i.substring(8,12)}-${i.substring(12,16)}-${i.substring(16,20)}-${i.substring(20,32)}`}var sR=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var DG=3,CG=15,hG=/^[a-zA-Z0-9_-]+$/,PR=Kn.string().min(DG).max(CG).regex(hG),ZR=20,qR={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function IG(n){let i="";for(let o of n)if(o in qR)i+=qR[o];else i+=o;return i}function kG(n){let i=n.toLocaleLowerCase(),o=IG(i);for(let c of sR){if(o.includes(c))return!0;if(i.includes(c))return!0}return!1}function sG(n){let i=new Set(n).size;return n.length*Math.log2(i)}function ZG(n){let i=0,o=100;if(kG(n))i-=o;return i+=sG(n)*0.5,Math.max(i,0)}var tR=Kn.string().refine((n)=>{return ZG(n)>=ZR},{message:`Password does not meet the minimum complexity of ${ZR}.`}).brand("password"),rR=Kn.object({username:PR,password:tR}).strict(),qG=Kn.string().email().brand("email"),gR=Kn.object({username:PR,password:tR,email:qG}).strict();var vf={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},R0=V0(vf).map(([n])=>Kn.literal(Number(n))),PG=Kn.union([R0[0],R0[1],...R0]),dR=Kn.tuple([PG,Kn.string()]);var eR=nc({key:"count",default:0}),tG=Gc({key:"incrementTX",do:({set:n})=>{n(eR,(i)=>i+1)}}),n4=Jv({key:"countContinuity",config:(n)=>n.add(eR).add(tG)});var o4=y$(Mc,"backend.worker.game.bun",$n),rc=new F0({logQuery(n,i){$n.info("\uD83D\uDCDD query",n,i)}});on.STORE.loggers[0]=new Kc("info",void 0,$n);var QI=(()=>{let{__tribunalDaily:n}=globalThis;if(!n)n=new c4.CronJob("00 15 * * * *",()=>{y$(Mc,"backend.worker.tribunal.bun",$n)}),n.start(),process.on("exit",()=>{n.stop(),$n.info("\u231B tribunal daily cronjob stopped")}),$n.info("\u23F3 tribunal daily cronjob started");return n})();function dG(n){if(B$)return gG(B$,n);return rG({},n)}var p4=dG((n,i)=>{let o;n.on("data",(c)=>(o??=[]).push(c)).on("end",async()=>{let c=n.headers.authorization;try{if(typeof n.url==="undefined")throw[400,"No URL"];let p=n.socket.remoteAddress;if(!p)throw[400,"No IP address"];let x=new Date,m=new URL(n.url,tn.VITE_BACKEND_ORIGIN);$n.info(x,p,n.method,m.pathname);let a=await rc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:Qo($f.ip,p)}),f=a?.banishedUntil===null,l=a?.banishedUntil&&a.banishedUntil>x;if(f||l){$n.info(`\uD83D\uDE45 request from banned ip ${p}`);return}switch(n.method){case"POST":if(!o)throw[400,"No data received"];switch(m.pathname){case`/sign-up-${M0("sign-up")}`:{let $=Buffer.concat(o).toString(),v=JSON.parse($),T=gR.safeParse(v);if(!T.success){$n.warn("signup parsed",T.error.issues);return}let{username:F,password:R,email:S}=T.data;if($n.info(`\uD83D\uDD11 attempting to sign up: ${F}`),await rc.drizzle.query.users.findFirst({columns:{id:!0},where:Qo(Ko.email,S)}))throw[400,"User already exists"];let G=crypto.randomUUID(),H=i4("sha256").update(R+G).digest("hex");await rc.drizzle.insert(Ko).values({username:F,email:S,hash:H,salt:G,createdIp:p}),$n.info(`\uD83D\uDD11 user created: ${F}`),i.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(vf[201])}break;case`/login-${M0("login")}`:{let $=!1,v=null;try{let T=new Date(+x-600000);$n.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:T,now:x});let F=await rc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:Vc(Qo(ix.ipAddress,p),Qo(ix.successful,!1),ia(ix.loginTime,T)),limit:10});$n.info(`\uD83D\uDD11 ${F.length}/10 recent failed logins from ${p}`);let R=10-F.length;if(R<1)throw $n.info(`\uD83D\uDD11 too many recent failed logins from ${p}`),await rc.drizzle.insert($f).values({ip:p,reason:"Too many recent login attempts.",banishedAt:x,banishedUntil:new Date(+x+86400000)}),[429,"Too many recent login attempts."];let S=Buffer.concat(o).toString(),M=JSON.parse(S),G=rR.safeParse(M);if(!G.success)throw $n.warn("login parsed",G.error.issues),[400,`${R} attempts remaining.`];let{username:H,password:y}=G.data,k=await rc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:Qo(Ko.username,H)});if($n.info("\uD83D\uDD11 login attempt as user",H),!k)throw $n.info(`\uD83D\uDD11 user ${H} does not exist`),[400,`${R} attempts remaining.`];let{hash:Y,salt:K}=k;if(v=k.id,i4("sha256").update(y+K).digest("hex")===Y){let u=crypto.randomUUID(),V=sa.get(H);if(!V)V=new Map,sa.set(H,V);V.set(u,Number(x)),$=!0,$n.info("\uD83D\uDD11 login successful as",H),i.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(`${H} ${u}`)}}finally{await rc.drizzle.insert(ix).values({userId:v,successful:$,ipAddress:p,userAgent:n.headers["user-agent"]??"Withheld"}),$n.info(`\uD83D\uDD11 recorded login attempt from ${p}`)}}}}}catch(p){let x=dR.safeParse(p);if(x.success){let[m,a]=x.data,l=`${vf[m]}. ${a}`;$n.info(`\u274C ${m}: ${l}`),i.writeHead(m,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end(l)}else $n.error(p),i.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${tn.FRONTEND_ORIGINS[0]}`}),i.end("Internal Server Error")}})}),W0=p4.listen(tn.BACKEND_PORT).address(),eG=typeof W0==="string"?null:W0===null?null:W0.port;if(eG===null)throw new Error("Could not determine port for test server");new gM(p4,{cors:{origin:tn.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((n,i)=>{let{username:o,sessionKey:c}=n.handshake.auth;if(!(o&&c)){i(new Error("No auth header provided"));return}let p=`user::${o}`,x=`socket::${n.id}`;if(sa.get(o)?.has(c)){let a=Tn(on.STORE,zm,x);Yn(on.STORE,a,n),Wc(Yc,(f)=>{f.set(p,x)},on.STORE),Yn(on.STORE,hf,(f)=>f.add(p)),Yn(on.STORE,Cf,(f)=>f.add(x)),$n.info(`${o} connected on ${n.id}`),i()}else $n.info(`${o} couldn't authenticate`),i(new Error("Authentication error"))}).on("connection",(n)=>{let o=Kv({socket:n,store:on.STORE})(n4);n.on("disconnect",()=>{let c=`socket::${n.id}`,p=op(Yc,c,on.STORE).userKeyOfSocket,x=An(on.STORE,p);if(Wc(Yc,(m)=>{m.delete(c)},on.STORE),x)Yn(on.STORE,hf,(m)=>(m.delete(x),m));Yn(on.STORE,Cf,(m)=>(m.delete(c),m)),$n.info(`${n.id} disconnected`),o()})});async function Tf(){$n.info("\uD83E\uDDF9 closing workers");let n=new Promise((i)=>o4.process.once("close",i));o4.emit("timeToStop"),await n,$n.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{$n.info("\u2757 received SIGINT; exiting gracefully"),await Tf()});process.on("SIGTERM",async()=>{$n.info("\u2757 received SIGTERM; exiting gracefully"),await Tf()});process.on("exit",async()=>{$n.info("\u2757 received exit; exiting gracefully"),await Tf()});Mc.on("updatesReady",()=>{$n.info('\u2757 backend server received signal "updatesReady"'),Mc.emit("readyToUpdate"),$n.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),Mc.on("timeToStop",async()=>{$n.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await Tf()})});$n.info(`\uD83D\uDEEB backend server ready on port ${tn.BACKEND_PORT}`);Mc.emit("alive");export{QI as tribunalDaily};
|
|
@@ -6,4 +6,4 @@ ${a.trace}`:"No previous disposal trace was found."),n.type){case"atom_family":c
|
|
|
6
6
|
This state was most recently disposed
|
|
7
7
|
${a.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":co(t,e);break;case"selector":case"readonly_selector":et(t,e);break;case"molecule":Ne(t,e);break}let{stack:i}=new Error;if(i){let r=i?.split(`
|
|
8
8
|
`)?.slice(3)?.join(`
|
|
9
|
-
`);e.disposalTraces.add({key:t.key,trace:r})}}var Xe=(e,o)=>y(o).atoms.has(e),Ct=(e,o)=>y(o).selectors.has(e),Kt=(e,o)=>y(o).readonlySelectors.has(e),ot=(e,o)=>Xe(e,o)||Ct(e,o)||Kt(e,o);var He=(e,o)=>{return y(o).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>ot(n,o))};var mo=(e,o,t)=>{let n=[],i=He(e,t);while(i.length>0){let r=i.shift();if(o.has(r))continue;if(o.add(r),!Xe(r,t))i.push(...He(r,t));else if(!n.includes(r))n.push(r)}return n},tt=(e,o)=>{let t=e.key,n=He(t,o),i=new Set;return n.flatMap((r)=>Xe(r,o)?r:mo(r,i,o))};var nt=(e,o,t,n)=>{let i=y(n);if(o.type==="atom"||o.type==="mutable_atom")i.selectorAtoms.set({selectorKey:e,atomKey:o.key}),n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atom "${o.key}"`);else{let r=mo(o.key,t,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})}t.add(o.key)};var Ve=(e,o,t)=>({get:(...n)=>{let i=y(t),r;if(n.length===2){let[l,s]=n;switch(l.type){case"molecule_family":return O(t,l,s);default:if(t.config.lifespan==="ephemeral")r=K(t,l,s);else{let m=W(t,l,s);if(m)r=m;else throw new D(l,s,t)}}}else[r]=n;if(r.type==="molecule")return O(t,r);let a=g(r,t),c=ce(a,t);return t.logger.info("\uD83D\uDD0C","selector",e,`registers dependency ( "${r.key}" =`,c,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:e},{source:r.key}),nt(e,r,o,t),c},set:(...n)=>{let i,r;if(n.length===2)i=n[0],r=n[1];else{let l=n[0],s=n[1];r=n[2];let m=t.config.lifespan==="ephemeral"?K(t,l,s):W(t,l,s);if(!m)throw new D(l,s,t);i=m}let a=y(t),c=g(i,a);je(c,r,a)},find:(n,i)=>K(t,n,i),seek:(n,i)=>W(t,n,i),json:(n)=>z(t,n)});var Fe=(e,o,t)=>{let n=y(e),i=new A,r=new Set,{get:a,find:c,seek:l,json:s}=Ve(o.key,r,n),m=()=>{let R=o.get({get:a,find:c,seek:l,json:s});return Z(o.key,R,i,y(e)),r.clear(),R},p={...o,subject:i,install:(R)=>Fe(R,o,t),get:m,type:"readonly_selector",...t&&{family:t}};n.readonlySelectors.set(o.key,p);let u=m();e.logger.info("\u2728",p.type,p.key,"=",u);let x={key:o.key,type:"readonly_selector"};if(t)x.family=t;return x};var $e=(e,o,t)=>{let n=y(e),i=new A,r=new Set,a=Ve(o.key,r,n),{find:c,get:l,seek:s,json:m}=a,p={find:c,get:l,seek:s,json:m},u=(J=o.get,w=y(e))=>{let B=J(p);return Z(o.key,B,i,w),r.clear(),B},R={...o,subject:i,install:(J)=>$e(J,o,t),get:u,set:(J)=>{let w=y(e),B=u(o.get,w),U=_e(J)(B);if(e.logger.info("\uD83D\uDCDD","selector",o.key,"set (",B,"->",U,")"),Z(o.key,U,i,w),de(w,o.key),P(w))i.next({newValue:U,oldValue:B});o.set(a,U)},type:"selector",...t&&{family:t}};n.selectors.set(o.key,R);let v=u();e.logger.info("\u2728",R.type,R.key,"=",v);let f={key:o.key,type:"selector"};if(t)f.family=t;return f};function Ae(e,o){if("set"in o){let i=$e(e,o,void 0);return e.on.selectorCreation.next(i),i}let n=Fe(e,o,void 0);return e.on.selectorCreation.next(n),n}function et(e,o){let t=y(o),{key:n}=e,i=g(e,t);if(!i.family)o.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{let r=t.molecules.get(i.family.subKey);if(r)r.tokens.delete(n);switch(e.type){case"selector":t.selectors.delete(n),g({key:i.family.key,type:"selector_family"},o).subject.next({type:"state_disposal",token:e});break;case"readonly_selector":t.readonlySelectors.delete(n),g({key:i.family.key,type:"readonly_selector_family"},o).subject.next({type:"state_disposal",token:e});break}if(t.valueMap.delete(n),t.selectorAtoms.delete(n),t.selectorGraph.delete(n),o.logger.info("\uD83D\uDD25",e.type,n,"deleted"),C(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:e});else o.on.selectorDisposal.next(e)}}function Re(e,o,t){let n={key:o.key,type:"selector_family"},i=e.families.get(o.key);if(i)e.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${ee(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let r=new A,c=Object.assign((l)=>{let s=S(l),m={key:o.key,subKey:s},p=`${o.key}(${s})`,u=y(e),x=$e(u,{key:p,get:o.get(l),set:o.set(l)},m);return r.next({type:"state_creation",token:x}),x},n,{internalRoles:t,subject:r,install:(l)=>Re(l,o),default:(l)=>{return o.get(l)({get:(...m)=>O(e,...m),find:(m,p)=>K(e,m,p),seek:(m,p)=>W(e,m,p),json:(m)=>z(e,m)})}});return e.families.set(o.key,c),n}function it(e,o,t=$.STORE){let n=Re(t,{key:`${e.key}:JSON`,get:(r)=>({seek:a,get:c})=>{let l=a(e,r);if(l)return o.toJson(c(l));let s=S(r),m=t.molecules.get(s);if(m){let u=oe(m,e,t);return o.toJson(c(u))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${s}"`);let p=te(t,e,r);return o.toJson(c(p))},set:(r)=>({seek:a,set:c},l)=>{let s=a(e,r);if(s)c(s,o.fromJson(l));else{let m=S(r),p=t.molecules.get(m);if(p){let u=oe(p,e,t);c(u,o.fromJson(l))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${m}"`);c(te(t,e,r),o.fromJson(l))}}}},["mutable","json"]);return g(e,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(r)=>{if(r.token.family)W(t,n,N(r.token.family.subKey))}),n}var N=(e)=>JSON.parse(e),S=(e)=>JSON.stringify(e),ps=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var rt=(e,o)=>{let t=y(o);if(t.operation.open)return t.operation.prev.get(e.key);return t.valueMap.get(e.key)};var To=(e,o)=>{let t=y(o);return tt(e,o).map((i)=>{let r=t.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${e.key}", not found in store "${o.config.name}".`);return r.subject.subscribe(`${e.type}:${e.key}`,(a)=>{o.logger.info("\uD83D\uDCE2",e.type,e.key,"root",i,"went",a.oldValue,"->",a.newValue);let c=rt(e,t),l=ce(e,t);o.logger.info("\u2728",e.type,e.key,"went",c,"->",l),e.subject.next({newValue:l,oldValue:c})})})};function H(e,o,t,n){function i(p){if(n.operation.open){let u=n.on.operationClose.subscribe(`state subscription ${t}`,()=>{u(),o(p)})}else o(p)}let r=g(e,n);n.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${t}"`);let a=r.type==="selector"||r.type==="readonly_selector",c=null,l=i;if(a)c=To(r,n),l=(p)=>{if(c)c.length=0,c.push(...To(r,n));i(p)};let s=r.subject.subscribe(t,l);return()=>{if(n.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${t}"`),s(),c)for(let p of c)p()}}var yo=(e,o,t,n)=>{let i=g(e,n);n.logger.info("\uD83D\uDC40","timeline",e.key,`Adding subscription "${t}"`);let r=i.subject.subscribe(t,o);return()=>{n.logger.info("\uD83D\uDE48","timeline",e.key,`Removing subscription "${t}" from timeline`),r()}};var po=(e,o,t,n)=>{let i=g(e,n);n.logger.info("\uD83D\uDC40","transaction",e.key,`Adding subscription "${t}"`);let r=i.subject.subscribe(t,o);return()=>{n.logger.info("\uD83D\uDE48","transaction",e.key,`Removing subscription "${t}"`),r()}};class me{Update;initializeState(e,o){let t=`*${e.key}`;o.atoms.delete(t),o.valueMap.delete(t);let n=e.family?{key:`*${e.family.key}`,subKey:e.family.subKey}:void 0,i=ae(o,{key:t,default:null},n);if(o.parent?.valueMap.has(t)){let r=o.parent.valueMap.get(t);o.valueMap.set(t,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(e,o,t){let n=`tracker:${t.config.name}:${C(t)?t.transactionMeta.update.key:"main"}:${e.key}`,i=O(t,e);this.unsubscribeFromInnerValue=i.subscribe(n,(r)=>{I(t,o,r)}),this.unsubscribeFromState=H(e,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(n,(a)=>{I(t,o,a)})},n,t)}updateCore(e,o,t){let n=`tracker:${t.config.name}:${C(t)?t.transactionMeta.update.key:"main"}:${e.key}`;H(o,({newValue:i,oldValue:r})=>{let a=t.timelineTopics.getRelatedKey(o.key);if(a){if(t.timelines.get(a)?.timeTraveling){let s=yo({key:a,type:"timeline"},(m)=>{s(),I(t,e,(p)=>{if(m==="redo"&&i)p.do(i);else if(m==="undo"&&r)p.undo(r);return p})},n,t);return}}let c=t.on.operationClose.subscribe(n,()=>{c();let l=O(t,e),s=i===null?-1:l.getUpdateNumber(i),m=s-l.cacheUpdateNumber;if(i&&m===1)I(t,e,(p)=>(p.do(i),p));else t.logger.info("\u274C","mutable_atom",e.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${s}`)})},n,t)}mutableState;latestUpdateState;dispose;constructor(e,o){this.mutableState=e;let t=y(o);this.latestUpdateState=this.initializeState(e,t),this.observeCore(e,this.latestUpdateState,t),this.updateCore(e,this.latestUpdateState,t),t.trackers.set(e.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(e.key)}}}function Oe(e,o,t){e.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${e.config.name}"`);let n=y(e),i=n.atoms.get(o.key);if(i&&i.type==="mutable_atom")return e.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Q(i);let r=new A,a={...o,type:"mutable_atom",install:(s)=>{return s.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${s.config.name}"`),Oe(s,o,t)},subject:r};if(t)a.family=t;let c=o.default();n.atoms.set(a.key,a),De(o.key,e),Z(o.key,c,r,n);let l=Q(a);if(o.effects){let s=0,m=[];for(let p of o.effects){let u=p({setSelf:(x)=>{I(e,l,x)},onSet:(x)=>H(l,x,`effect[${s}]`,e)});if(u)m.push(u);++s}a.cleanup=()=>{for(let p of m)p()}}if(new me(l,e),!t)Ko(l,o,e);return l}class fo{Update;latestUpdateAtoms;mutableAtoms;constructor(e,o){let t=re(o,{key:`*${e.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=g(t,o),this.mutableAtoms=e,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){let i=N(n.token.family.subKey);W(o,this.latestUpdateAtoms,i),new me(n.token,o)}}),this.latestUpdateAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){let i=N(n.token.family.subKey),r=W(o,this.mutableAtoms,i);if(r)new me(r,o)}})}}function Me(e,o,t){let n={key:o.key,type:"mutable_atom_family"},i=e.families.get(o.key);if(i)e.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${ee(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let r=new A,c=Object.assign((l)=>{let s=S(l),m={key:o.key,subKey:s},p=`${o.key}(${s})`,u=y(e),x={key:p,default:()=>o.default(l),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)x.effects=o.effects(l);let R=Oe(u,x,m);return r.next({type:"state_creation",token:R}),R},n,{subject:r,install:(l)=>Me(l,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:t});return e.families.set(o.key,c),it(c,o,e),new fo(c,e),n}var uo=(e,o)=>{let t=y(o),n=`${e.key}:JSON`;return t.families.get(n)};var z=(e,o)=>{if(o.family){let n=y(e),r={key:`${o.family.key}:JSON`,type:"selector_family"},a=g(r,n),c=JSON.parse(o.family.subKey);return K(e,a,c)}return{type:"selector",key:`${o.key}:JSON`}};var ie=(e)=>{let t={type:"atom",key:`*${e.key}`};if(e.family)t.family={key:`*${e.family.key}`,subKey:e.family.subKey};return t};function Eo(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Je(e,o,t){let n=o.valueMap.get(e.key),i=t.valueMap.get(e.key);if(n===i){if(n===void 0)return typeof e.default==="function"?e.default():e.default;o.logger.info("\uD83D\uDCC3","atom",e.key,"copying");let r=e.toJson(n),a=e.fromJson(r);return t.valueMap.set(e.key,a),new me(e,o),a}return i}function Z(e,o,t,n){let i=n.valueMap.get(e);if(i instanceof xe)i.use(o);if(o instanceof Promise){let r=new xe(o);return n.valueMap.set(e,r),r.then((a)=>{Z(e,a,t,n),t.next({newValue:a,oldValue:r})}).catch((a)=>{n.logger.error("\uD83D\uDCA5","state",e,"rejected:",a)}),r}return n.valueMap.set(e,o),o}var wo=(e,o)=>{let t=o.valueMap.get(e.key);if(e.type==="mutable_atom"&&C(o)){let{parent:n}=o;t=Je(e,n,o)}return t},Io=(e,o)=>{let t=o.valueMap.get(e);if(t instanceof xe){let n=t,i=o.selectors.get(e)??o.readonlySelectors.get(e);if(i)n.use(i.get());return}if(o.operation.open)o.operation.prev.set(e,t);o.valueMap.delete(e),o.logger.info("\uD83D\uDDD1","state",e,"evicted")};var Po=(e,o)=>{return y(o).atomsThatAreDefault.has(e)},De=(e,o)=>{let t=y(o);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(e)},No=(e,o)=>{let t=y(o);t.atomsThatAreDefault=new Set(y(o).atomsThatAreDefault),t.atomsThatAreDefault.delete(e)};function ae(e,o,t){e.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${e.config.name}"`);let n=y(e),i=n.atoms.get(o.key);if(i&&i.type==="atom")return e.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Q(i);let r=new A,a={...o,type:"atom",install:(s)=>{return s.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${s.config.name}"`),ae(s,o,t)},subject:r};if(t)a.family=t;let c=o.default;if(o.default instanceof Function)c=o.default();n.atoms.set(a.key,a),De(o.key,e),Z(o.key,c,r,n);let l=Q(a);if(o.effects){let s=0,m=[];for(let p of o.effects){let u=p({setSelf:(x)=>{I(e,l,x)},onSet:(x)=>H(l,x,`effect[${s}]`,e)});if(u)m.push(u);++s}a.cleanup=()=>{for(let p of m)p()}}return l}function $o(e,o){if("mutable"in o){let i=Oe(e,o,void 0);return e.on.atomCreation.next(i),i}let n=ae(e,o,void 0);return e.on.atomCreation.next(n),n}function co(e,o){let t=y(o),{key:n}=e,i=g(e,t);if(!i.family)o.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{i.cleanup?.();let r=o.valueMap.get(i.key);g({key:i.family.key,type:"atom_family"},o).subject.next({type:"state_disposal",token:e,value:r});let c=t.molecules.get(i.family.subKey);if(c)c.tokens.delete(n);if(t.atoms.delete(n),t.valueMap.delete(n),t.selectorAtoms.delete(n),t.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),e.type==="mutable_atom"){let l=ie(e);co(l,o),o.trackers.delete(n)}if(o.logger.info("\uD83D\uDD25","atom",n,"deleted"),C(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:e});else o.on.atomDisposal.next(e)}}class X extends Set{mode="record";subject=new A;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(e,o=0){super(e);if(e instanceof X)this.parent=e,this.cacheUpdateNumber=e.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(t)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=t})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(e){let o=new X(e.members,e.cacheLimit);return o.cache=e.cache,o.cacheIdx=e.cacheIdx,o.cacheUpdateNumber=e.cacheUpdateNumber,o}add(e){let o=super.add(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S(e)}`);return o}clear(){let e=this.mode==="record"?[...this]:null;if(super.clear(),e)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(e)}`)}delete(e){let o=super.delete(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S(e)}`);return o}parent;child=null;transactionUpdates=null;transaction(e){this.mode="transaction",this.transactionUpdates=[],this.child=new X(this);let o=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(e(this.child)){for(let n of this.transactionUpdates)this.doStep(n);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",t),t}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(e,o){return this.subject.subscribe(e,o)}subscribe(e,o){return this.subject.subscribe(e,(t)=>{o(`${this.cacheUpdateNumber}=${t}`)})}emit(e){this.subject.next(e)}doStep(e){let o=e.indexOf(":"),t=e.substring(0,o),n=e.substring(o+1);switch(t){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){let o=e.indexOf("=");return Number(e.substring(0,o))}do(e){let o=e.indexOf("="),t=Number(e.substring(0,o)),n=t-this.cacheUpdateNumber;if(n>0){if(n===1){this.mode="playback";let r=e.substring(o+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(n)<this.cacheLimit){let r=this.cacheIdx+n;if(this.cache[r]===e)return null;this.mode="playback";let c=!1;while(!c){this.cacheIdx%=this.cacheLimit;let s=this.cache[this.cacheIdx];if(this.cacheIdx--,!s)return"OUT_OF_RANGE";this.undo(s),c=this.cacheIdx===r-1}let l=e.substring(o+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(e){let o=e.indexOf(":"),t=e.substring(0,o),n=e.substring(o+1);switch(t){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{let i=JSON.parse(n);for(let r of i)this.add(r);break}case"tx":{let i=n.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(e){let o=e.indexOf("=");if(Number(e.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let n=e.substring(o+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function _(e){return e[0].toUpperCase()+e.slice(1)}class ko{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(e,o){let t=this.toolkit;this.toolkit=e,o(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(e){let o=e.config.name,t=this.alternates.get(o);if(t)return t;let n=new ko(this.options,this.defaultContent,e);return this.alternates.set(o,n),n.alternates=this.alternates,n}constructor(e,o,t=$.STORE){this.store=t,this.options=e,this.defaultContent=o,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${e.key}`,this),this.retrieve=(T,d)=>{let M=this.toolkit.seek(T,d);if(M)return M;let F=this.store.molecules.get(S(d));if(F){let k=g(T,t);return oe(F,k,t)}if(t.config.lifespan==="immortal")throw new D(T,d,t);return te(t,T,d)},this.toolkit={get:(...T)=>O(t,...T),set:(...T)=>{I(t,...T)},find:this.retrieve,seek:(...T)=>W(t,...T),json:(T)=>z(t,T),dispose:(...T)=>{V(t,...T)}};let n=e.between[0],i=e.between[1],r=Me(t,{key:`${e.key}/relatedKeys`,default:()=>new X,mutable:!0,fromJson:(T)=>X.fromJSON(T),toJson:(T)=>T.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};let a=({get:T},d)=>T(this.retrieve(r,d)),c=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d),b=this.retrieve(r,M);F(k,(h)=>h.add(M)),F(b,(h)=>h.add(d))},l=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d),b=this.retrieve(r,M),h,j;F(k,(E)=>{if(E.delete(M),E.size===0)h=`"${d}"`;return E}),F(b,(E)=>{if(E.delete(d),E.size===0)j=`"${M}"`;return E})},s=(T,d,M)=>{let{get:F,set:k}=T,b=this.retrieve(r,d),h=F(b);for(let j of h){if(M.includes(j))continue;let Y=this.retrieve(r,j);k(Y,(L)=>{return L.delete(d),L})}k(b,(j)=>{return j.transaction((E)=>{E.clear();for(let Y of M){let L=a(T,Y),Ro=L.has(d);if(this.relations.cardinality==="1:n"){let Co=[];for(let be of L){if(be===d)continue;let ge=a(T,be);if(ge.delete(Y),ge.size===0)Co.push(be)}if(!Ro&&L.size>0)L.clear();for(let be of Co){let ge=[Y,be].sort(),dt=`"${ge[0]}:${ge[1]}"`;this.molecules.delete(dt)}}if(!Ro)L.add(d);E.add(Y)}return!0}),j})},m=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d);F(k,(b)=>{return b.transaction((h)=>{for(let j of M)h.add(j);return!0}),b});for(let b of M){let h=this.retrieve(r,b);F(h,(j)=>{return j.add(d),j})}return!0},p=(T,d,M)=>{let F=a(T,d);return M?F.has(M):F.size>0},u={getRelatedKeys:(T)=>a(this.toolkit,T),addRelation:(T,d)=>{c(this.toolkit,T,d)},deleteRelation:(T,d)=>{l(this.toolkit,T,d)},replaceRelationsSafely:(T,d)=>{s(this.toolkit,T,d)},replaceRelationsUnsafely:(T,d)=>{m(this.toolkit,T,d)},has:(T,d)=>p(this.toolkit,T,d)},x,R,v;if(o){R=re(t,{key:`${e.key}/content`,default:o},["join","content"]),v=Xo(t,{key:`${e.key}/content-molecules`,new:class k{key;constructor(b,h){this.key=h}}});let T=({get:k},b)=>k(this.retrieve(R,b)),d=({set:k},b,h)=>{k(this.retrieve(R,b),h)},M=(k,b)=>{let h=t.molecules.get(`"${b}"`);if(h)this.toolkit.dispose(h),this.molecules.delete(`"${b}"`)};x=Object.assign(u,{getContent:(k)=>{return T(this.toolkit,k)},setContent:(k,b)=>{d(this.toolkit,k,b)},deleteContent:(k)=>{M(this.toolkit,k)}})}else x=u;let f=new q(e,{externalStore:x,isAType:e.isAType,isBType:e.isBType,makeContentKey:(...T)=>{let d=T.sort(),M=`${d[0]}:${d[1]}`,[F,k]=d.map((b)=>this.molecules.get(S(b)));if(t.config.lifespan==="immortal"&&F&&k){let b=y(t),h=ne(b,[F,k],v,M);this.molecules.set(`"${M}"`,g(h,b))}return M}}),J=()=>le(t,{key:`${e.key}/singleRelatedKey`,get:(T)=>({get:d})=>{let M=this.retrieve(r,T),F=d(M);for(let k of F)return k;return null}},["join","keys"]),w=()=>{return le(t,{key:`${e.key}/multipleRelatedKeys`,get:(T)=>({get:d})=>{let M=uo(r,t),F=this.retrieve(M,T);return d(F).members}},["join","keys"])},B=()=>le(t,{key:`${e.key}/singleRelatedEntry`,get:(T)=>({get:d})=>{let M=this.retrieve(r,T),F=d(M);for(let k of F){let b=f.isAType?.(T)?T:void 0,h=b===void 0?T:void 0;b??=k,h??=k;let j=f.makeContentKey(b,h),E=this.retrieve(R,j),Y=d(E);return[k,Y]}return null}},["join","entries"]),U=()=>le(t,{key:`${e.key}/multipleRelatedEntries`,get:(T)=>({get:d})=>{let M=uo(r,t),F=this.retrieve(M,T);return d(F).members.map((b)=>{let h=f.isAType?.(T)?T:void 0,j=h===void 0?T:void 0;h??=b,j??=b;let E=f.makeContentKey(h,j),Y=this.retrieve(R,E),L=d(Y);return[b,L]})}},["join","entries"]);switch(e.cardinality){case"1:1":{let T=J(),d=`${n}KeyOf${_(i)}`,M=`${i}KeyOf${_(n)}`,F={[d]:T,[M]:T},k;if(o){let b=B(),h=`${n}EntryOf${_(i)}`,j=`${i}EntryOf${_(n)}`,E={[h]:b,[j]:b};k=Object.assign(F,E)}else k=F;this.relations=f,this.states=k;break}case"1:n":{let T=J(),d=w(),M=`${n}KeyOf${_(i)}`,F=`${i}KeysOf${_(n)}`,k={[M]:T,[F]:d},b;if(o){let h=B(),j=U(),E=`${n}EntryOf${_(i)}`,Y=`${i}EntriesOf${_(n)}`,L={[E]:h,[Y]:j};b=Object.assign(k,L)}else b=k;this.relations=f,this.states=b;break}default:{let T=w(),d=`${n}KeysOf${_(i)}`,M=`${i}KeysOf${_(n)}`,F={[d]:T,[M]:T},k;if(o){let b=U(),h=`${n}EntriesOf${_(i)}`,j=`${i}EntriesOf${_(n)}`,E={[h]:b,[j]:b};k=Object.assign(F,E)}else k=F;this.relations=f,this.states=k}}}}function Ue(e,o,t=$.STORE){return So(t).set(e.key,new ko(e,o,t)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function So(e){if("joins"in e&&e.joins instanceof Map)return e.joins;let o=new Map;return e.joins=o,o}function he(e,o){let t=So(o),n=t.get(e.key);if(n===void 0){if(n=So($.STORE).get(e.key)?.in(o),n===void 0)throw new Error(`Join "${e.key}" not found in store "${o.config.name}"`);t.set(e.key,n)}return n}function qe(e,o,t){let n=he(e,t),i;switch(e.cardinality){case"1:1":{let r=`${e.a}KeyOf${_(e.b)}`,a=`${e.b}KeyOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntryOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntryOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}break}case"1:n":{let r=`${e.a}KeyOf${_(e.b)}`,a=`${e.b}KeysOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntryOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntriesOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}break}case"n:n":{let r=`${e.a}KeysOf${_(e.b)}`,a=`${e.b}KeysOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntriesOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntriesOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}}}return i}function Vo(e,o){return qe(e,o,$.STORE)}function Ye(e,o,t){let n=he(e,t),i=y(t);if(C(i)){let{toolkit:r}=i.transactionMeta;n.transact(r,({relations:a})=>{o(a)})}else o(n.relations)}function Jt(e,o){return he(e,o).core.findRelatedKeysState}function at(e){return Jt(e,$.STORE)}class lt extends Map{set(e,o){if(this.has(e))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:e,value:o}),this;return super.set(e,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Le{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new lt;static create(e,o){let t=new Le(e),{type:n,globals:i,actions:r,perspectives:a}=o(t),c={type:n,key:e,globals:i,actions:r,perspectives:a};return Le.existing.set(e,c),c}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":{let[t,n]=e;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:n})}break}return this}}function my(e){let{key:o,config:t}=e,n=Le.create(o,t),{actions:i}=n;for(let r of i)Lo(o,r.key,$.STORE);return Uo(o,-1,$.STORE),n}var uy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),bo=ue({key:"roomIndex",default:()=>new X,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),ht={enteredAtEpoch:0},we=Ue({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(e)=>typeof e==="string",isBType:(e)=>typeof e==="string"},ht),dy=We({key:"usersInMyRoomView",get:(e)=>({find:o})=>{let t=at(we);return[o(t,e)]}});import{spawn as $t}from"child_process";class Se{emit;listeners;globalListeners;handleEvent(e,...o){for(let n of this.globalListeners)n(e,...o);let t=this.listeners.get(e);if(t)for(let n of t)n(...o)}id="no_id_retrieved";constructor(e){this.emit=e;this.listeners=new Map,this.globalListeners=new Set}on(e,o){let t=this.listeners.get(e);if(t)t.add(o);else this.listeners.set(e,new Set([o]));return this}onAny(e){return this.globalListeners.add(e),this}off(e,o){let t=this.listeners.get(e);if(t)if(o)t.delete(o);else this.listeners.delete(e);return this}offAny(e){return this.globalListeners.delete(e),this}}class go extends Se{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(e){if(Array.isArray(e)){let[o,...t]=e;switch(o){case"i":this.logger.info(...t);break;case"w":this.logger.warn(...t);break;case"e":this.logger.error(...t);break}}}constructor(e,o,t){super((n,...i)=>{let r=JSON.stringify([n,...i])+"\x03",a=(c)=>{if(c.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});if(this.process=e,this.key=o,this.logger=t??{info:(...n)=>{console.info(this.id,this.key,...n)},warn:(...n)=>{console.warn(this.id,this.key,...n)},error:(...n)=>{console.error(this.id,this.key,...n)}},this.process.stdout.on("data",(n)=>{let i=n.toString();if(i==="ALIVE")return;this.unprocessedEvents.push(...i.split("\x03"));let r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let a=N(this.incompleteData);this.handleEvent(...a);while(this.unprocessedEvents.length>0){let c=this.unprocessedEvents.shift();if(c){if(this.unprocessedEvents.length===0)this.incompleteData=c;a=N(c),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)=>{let i=n.toString();this.unprocessedLogs.push(...i.split("\x03"));let r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let a=N(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=N(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 st extends Se{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(e){super((...o)=>{return this.out.next(o),this});this.id=e,this.in=new A,this.out=new A,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let e of this.disposalFunctions)e()}}class xo extends Se{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...e){this.process.stderr.write(S(e.map((o)=>o instanceof X?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...e)=>{this.log("i",...e)},warn:(...e)=>{this.log("w",...e)},error:(...e)=>{this.log("e",...e)}};constructor(){super((e,...o)=>{let t=JSON.stringify([e,...o]);return this.process.stdout.write(t+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(e)=>{let o=e.toString();this.unprocessedEvents.push(...o.split("\x03"));let t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{let n=N(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){let i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;let r=N(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");let o=new st(`user:${e}`);this.relays.set(e,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){let n=t(o);if(n)o.disposalFunctions.push(n)}this.on(`user:${e}`,(...t)=>{o.in.next(t)}),o.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(e)=>{let o=this.relays.get(e);if(this.off(`relay:${e}`),o)o.dispose(),this.relays.delete(e)}),process.stdout.write("ALIVE")}relay(e){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(e)}}var Ao=ye({key:"roomArguments",default:["echo",["Hello World!"]]}),ct=We({key:"room",get:(e)=>async({get:o,find:t})=>{let n=t(Ao,e),i=o(n),[r,a]=i,c=await new Promise((l)=>{let s=$t(r,a,{env:process.env}),m=(p)=>{if(p.toString()==="ALIVE")s.stdout.off("data",m),l(s)};s.stdout.on("data",m)});return new go(c,e)}});var Hy=Ke({key:"createRoom",do:({get:e,set:o,find:t},n,i,r)=>{let a=r?[i,r]:[i],c=t(Ao,n);o(c,a),o(bo,(m)=>m.add(n));let l=t(ct,n);return e(l)}}),Vy=Ke({key:"joinRoom",do:(e,o,t,n)=>{let i={enteredAtEpoch:n};return Ye(we,(r)=>{r.set({room:o,user:t},i)},e.env().store),i}}),Dy=Ke({key:"leaveRoom",do:(e,o,t)=>{Ye(we,(n)=>{n.delete({room:o,user:t})},e.env().store)}}),Uy=Ke({key:"destroyRoom",do:(e,o)=>{Ye(we,(t)=>{t.delete({room:o})},e.env().store),e.set(bo,(t)=>(t.delete(o),t))}});function Mo(e,o){return o.map((t)=>{switch(t.type){case"transaction_update":{let n=Mo(e,t.updates);return{...t,updates:n}}default:return t}}).filter((t)=>{switch(t.type){case"atom_update":case"selector_update":return e.includes(t.key);case"state_creation":return e.includes(t.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var Ly=ye({key:"redactor",default:{occlude:(e)=>e}}),ke=ye({key:"unacknowledgedUpdates",default:()=>[]});var mt=ye({key:"sockets",default:null}),op=ue({key:"socketsIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),tp=ue({key:"usersIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),Fo=Ue({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(e)=>e.startsWith("user::"),isBType:(e)=>e.startsWith("socket::")});function yt(e,o,t,n){let i=o.key;return function r(){let a=[];for(let l of o.globals){let s=l.type==="mutable_atom"?z(e,l):l,m=O(e,s);a.push(s,m)}for(let l of o.perspectives){let{viewAtoms:s,resourceAtoms:m}=l,p=K(e,s,t),u=O(e,p);e.logger.info("\uD83D\uDC41","atom",m.key,`${t} can see`,{viewAtoms:s,resourceAtoms:m,userView:u});for(let x of u){let R=x.type==="mutable_atom"?z(e,x):x,v=O(e,R);a.push(R,v)}}let c=P(e)?e.transactionMeta.epoch.get(i)??null:null;n?.emit(`continuity-init:${i}`,c,a)}}function pt(e,o,t){let n=o.key;return function i(r){e.logger.info("\uD83D\uDECE\uFE0F","continuity",n,"received",r);let{key:a,id:c}=r,l=`tx-run:${a}:${c}`,s=`${l}:start`,m=`${l}:end`;performance.mark(s);try{se({type:"transaction",key:a},c,e)(...r.params)}catch(u){if(u instanceof Error)e.logger.error("\u274C","continuity",n,`failed to run transaction ${a} from ${t} with update ${c}`,u.message)}performance.mark(m);let p=performance.measure(l,s,m);e?.logger.info("\uD83D\uDE80","transaction",a,c,t,p.duration)}}function Tt(e,o,t,n){let i=o.key;return function r(a){if(e.logger.info("\uD83D\uDC4D","continuity",i,`${t} acknowledged epoch ${a}`),n[0]?.epoch===a)I(e,ke,t,(l)=>{return l.shift(),e.logger.info("\uD83D\uDC4D","continuity",i,`${t} unacknowledged update queue now has`,l.length,"items"),l})}}function ft(e,o,t,n){let i=o.key,r=[];for(let a of o.actions){let c=po(a,(l)=>{try{let s=o.globals.map((u)=>{if(u.type==="atom")return u.key;return ie(u).key}).concat(o.perspectives.flatMap((u)=>{let{viewAtoms:x}=u,R=K(e,x,t);return O(e,R).map((f)=>{return f.type==="mutable_atom"?"*"+f.key:f.key})})),m=Mo(s,l.updates),p={...l,updates:m};I(e,ke,t,(u)=>{if(p)u.push(p),u.sort((x,R)=>x.epoch-R.epoch),e.logger.info("\uD83D\uDC4D","continuity",i,`${t} unacknowledged update queue now has`,u.length,"items");return u}),n?.emit(`tx-new:${i}`,p)}catch(s){if(s instanceof Error)e.logger.error("\u274C","continuity",i,`${t} failed to send update from transaction ${a.key} to ${t}`,s.message)}},`sync-continuity:${i}:${t}`,e);r.push(c)}return r}function ut(e,o,t,n){let i=o.key,r=[];for(let a of o.perspectives){let{viewAtoms:c}=a,l=K(e,c,t),s=H(l,({oldValue:m,newValue:p})=>{let u=m.map((f)=>f.key),x=p.map((f)=>f.key),R=m.filter((f)=>!x.includes(f.key)),v=p.filter((f)=>!u.includes(f.key)).flatMap((f)=>{let J=f.type==="mutable_atom"?z(e,f):f,w=O(e,J);return[J,w]});if(e.logger.info("\uD83D\uDC41","atom",a.resourceAtoms.key,`${t} has a new perspective`,{oldKeys:u,newKeys:x,revealed:v,concealed:R}),v.length>0)n?.emit(`reveal:${i}`,v);if(R.length>0)n?.emit(`conceal:${i}`,R)},`sync-continuity:${i}:${t}:perspective:${a.resourceAtoms.key}`,e);r.push(s)}return r}function wp({socket:e,store:o=$.STORE}){return function t(n){let i=e,r=n.key,a=qe(Fo,`socket::${i.id}`,o).userKeyOfSocket,c=O(o,a);if(!c)return o.logger.error("\u274C","continuity",r,`Tried to create a synchronizer for a socket (${i.id}) that is not connected to a user.`),()=>{};let l=qe(Fo,c,o).socketKeyOfUser,s=H(l,({newValue:J})=>{if(o.logger.info("\uD83D\uDC4B","continuity",r,`seeing ${c} on new socket ${J}`),J===null){o.logger.warn("\u274C","continuity",r,`User (${c}) is not connected to a socket, waiting for them to reappear.`);return}let w=K(o,mt,J);i=O(o,w);for(let U of m)i?.emit(`tx-new:${r}`,U)},`sync-continuity:${r}:${c}`,o),m=O(o,ke,c),p=[],u=ut(o,n,c,i),x=ft(o,n,c,i);p.push(...u,...x);let R=yt(o,n,c,e);i.off(`get:${r}`,R),i.on(`get:${r}`,R);let v=pt(o,n,c);i.off(`tx-run:${r}`,v),i.on(`tx-run:${r}`,v);let f=Tt(o,n,c,m);return i?.on(`ack:${r}`,f),()=>{for(let J of p)J();i?.off(`ack:${r}`,f),i?.off(`get:${r}`,R),i?.off(`tx-run:${r}`,v)}}}var Be=new xo;Object.assign(console,Be.logger,{log:Be.logger.info});Be.on("timeToStop",function e(){Be.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)});Be.logger.info("\uD83D\uDEEB game worker ready");
|
|
9
|
+
`);e.disposalTraces.add({key:t.key,trace:r})}}var Xe=(e,o)=>y(o).atoms.has(e),Ct=(e,o)=>y(o).selectors.has(e),Kt=(e,o)=>y(o).readonlySelectors.has(e),ot=(e,o)=>Xe(e,o)||Ct(e,o)||Kt(e,o);var He=(e,o)=>{return y(o).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>ot(n,o))};var mo=(e,o,t)=>{let n=[],i=He(e,t);while(i.length>0){let r=i.shift();if(o.has(r))continue;if(o.add(r),!Xe(r,t))i.push(...He(r,t));else if(!n.includes(r))n.push(r)}return n},tt=(e,o)=>{let t=e.key,n=He(t,o),i=new Set;return n.flatMap((r)=>Xe(r,o)?r:mo(r,i,o))};var nt=(e,o,t,n)=>{let i=y(n);if(o.type==="atom"||o.type==="mutable_atom")i.selectorAtoms.set({selectorKey:e,atomKey:o.key}),n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atom "${o.key}"`);else{let r=mo(o.key,t,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})}t.add(o.key)};var Ve=(e,o,t)=>({get:(...n)=>{let i=y(t),r;if(n.length===2){let[l,s]=n;switch(l.type){case"molecule_family":return O(t,l,s);default:if(t.config.lifespan==="ephemeral")r=K(t,l,s);else{let m=W(t,l,s);if(m)r=m;else throw new D(l,s,t)}}}else[r]=n;if(r.type==="molecule")return O(t,r);let a=g(r,t),c=ce(a,t);return t.logger.info("\uD83D\uDD0C","selector",e,`registers dependency ( "${r.key}" =`,c,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:e},{source:r.key}),nt(e,r,o,t),c},set:(...n)=>{let i,r;if(n.length===2)i=n[0],r=n[1];else{let l=n[0],s=n[1];r=n[2];let m=t.config.lifespan==="ephemeral"?K(t,l,s):W(t,l,s);if(!m)throw new D(l,s,t);i=m}let a=y(t),c=g(i,a);je(c,r,a)},find:(n,i)=>K(t,n,i),seek:(n,i)=>W(t,n,i),json:(n)=>z(t,n)});var Fe=(e,o,t)=>{let n=y(e),i=new A,r=new Set,{get:a,find:c,seek:l,json:s}=Ve(o.key,r,n),m=()=>{let R=o.get({get:a,find:c,seek:l,json:s});return Z(o.key,R,i,y(e)),r.clear(),R},p={...o,subject:i,install:(R)=>Fe(R,o,t),get:m,type:"readonly_selector",...t&&{family:t}};n.readonlySelectors.set(o.key,p);let u=m();e.logger.info("\u2728",p.type,p.key,"=",u);let x={key:o.key,type:"readonly_selector"};if(t)x.family=t;return x};var $e=(e,o,t)=>{let n=y(e),i=new A,r=new Set,a=Ve(o.key,r,n),{find:c,get:l,seek:s,json:m}=a,p={find:c,get:l,seek:s,json:m},u=(J=o.get,w=y(e))=>{let B=J(p);return Z(o.key,B,i,w),r.clear(),B},R={...o,subject:i,install:(J)=>$e(J,o,t),get:u,set:(J)=>{let w=y(e),B=u(o.get,w),U=_e(J)(B);if(e.logger.info("\uD83D\uDCDD","selector",o.key,"set (",B,"->",U,")"),Z(o.key,U,i,w),de(w,o.key),P(w))i.next({newValue:U,oldValue:B});o.set(a,U)},type:"selector",...t&&{family:t}};n.selectors.set(o.key,R);let v=u();e.logger.info("\u2728",R.type,R.key,"=",v);let f={key:o.key,type:"selector"};if(t)f.family=t;return f};function Ae(e,o){if("set"in o){let i=$e(e,o,void 0);return e.on.selectorCreation.next(i),i}let n=Fe(e,o,void 0);return e.on.selectorCreation.next(n),n}function et(e,o){let t=y(o),{key:n}=e,i=g(e,t);if(!i.family)o.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{let r=t.molecules.get(i.family.subKey);if(r)r.tokens.delete(n);switch(e.type){case"selector":t.selectors.delete(n),g({key:i.family.key,type:"selector_family"},o).subject.next({type:"state_disposal",token:e});break;case"readonly_selector":t.readonlySelectors.delete(n),g({key:i.family.key,type:"readonly_selector_family"},o).subject.next({type:"state_disposal",token:e});break}if(t.valueMap.delete(n),t.selectorAtoms.delete(n),t.selectorGraph.delete(n),o.logger.info("\uD83D\uDD25",e.type,n,"deleted"),C(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:e});else o.on.selectorDisposal.next(e)}}function Re(e,o,t){let n={key:o.key,type:"selector_family"},i=e.families.get(o.key);if(i)e.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${ee(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let r=new A,c=Object.assign((l)=>{let s=S(l),m={key:o.key,subKey:s},p=`${o.key}(${s})`,u=y(e),x=$e(u,{key:p,get:o.get(l),set:o.set(l)},m);return r.next({type:"state_creation",token:x}),x},n,{internalRoles:t,subject:r,install:(l)=>Re(l,o),default:(l)=>{return o.get(l)({get:(...m)=>O(e,...m),find:(m,p)=>K(e,m,p),seek:(m,p)=>W(e,m,p),json:(m)=>z(e,m)})}});return e.families.set(o.key,c),n}function it(e,o,t=$.STORE){let n=Re(t,{key:`${e.key}:JSON`,get:(r)=>({seek:a,get:c})=>{let l=a(e,r);if(l)return o.toJson(c(l));let s=S(r),m=t.molecules.get(s);if(m){let u=oe(m,e,t);return o.toJson(c(u))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${s}"`);let p=te(t,e,r);return o.toJson(c(p))},set:(r)=>({seek:a,set:c},l)=>{let s=a(e,r);if(s)c(s,o.fromJson(l));else{let m=S(r),p=t.molecules.get(m);if(p){let u=oe(p,e,t);c(u,o.fromJson(l))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${m}"`);c(te(t,e,r),o.fromJson(l))}}}},["mutable","json"]);return g(e,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(r)=>{if(r.token.family)W(t,n,N(r.token.family.subKey))}),n}var N=(e)=>JSON.parse(e),S=(e)=>JSON.stringify(e),ps=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var rt=(e,o)=>{let t=y(o);if(t.operation.open)return t.operation.prev.get(e.key);return t.valueMap.get(e.key)};var To=(e,o)=>{let t=y(o);return tt(e,o).map((i)=>{let r=t.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${e.key}", not found in store "${o.config.name}".`);return r.subject.subscribe(`${e.type}:${e.key}`,(a)=>{o.logger.info("\uD83D\uDCE2",e.type,e.key,"root",i,"went",a.oldValue,"->",a.newValue);let c=rt(e,t),l=ce(e,t);o.logger.info("\u2728",e.type,e.key,"went",c,"->",l),e.subject.next({newValue:l,oldValue:c})})})};function H(e,o,t,n){function i(p){if(n.operation.open){let u=n.on.operationClose.subscribe(`state subscription ${t}`,()=>{u(),o(p)})}else o(p)}let r=g(e,n);n.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${t}"`);let a=r.type==="selector"||r.type==="readonly_selector",c=null,l=i;if(a)c=To(r,n),l=(p)=>{if(c)c.length=0,c.push(...To(r,n));i(p)};let s=r.subject.subscribe(t,l);return()=>{if(n.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${t}"`),s(),c)for(let p of c)p()}}var yo=(e,o,t,n)=>{let i=g(e,n);n.logger.info("\uD83D\uDC40","timeline",e.key,`Adding subscription "${t}"`);let r=i.subject.subscribe(t,o);return()=>{n.logger.info("\uD83D\uDE48","timeline",e.key,`Removing subscription "${t}" from timeline`),r()}};var po=(e,o,t,n)=>{let i=g(e,n);n.logger.info("\uD83D\uDC40","transaction",e.key,`Adding subscription "${t}"`);let r=i.subject.subscribe(t,o);return()=>{n.logger.info("\uD83D\uDE48","transaction",e.key,`Removing subscription "${t}"`),r()}};class me{Update;initializeState(e,o){let t=`*${e.key}`;o.atoms.delete(t),o.valueMap.delete(t);let n=e.family?{key:`*${e.family.key}`,subKey:e.family.subKey}:void 0,i=ae(o,{key:t,default:null},n);if(o.parent?.valueMap.has(t)){let r=o.parent.valueMap.get(t);o.valueMap.set(t,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(e,o,t){let n=`tracker:${t.config.name}:${C(t)?t.transactionMeta.update.key:"main"}:${e.key}`,i=O(t,e);this.unsubscribeFromInnerValue=i.subscribe(n,(r)=>{I(t,o,r)}),this.unsubscribeFromState=H(e,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(n,(a)=>{I(t,o,a)})},n,t)}updateCore(e,o,t){let n=`tracker:${t.config.name}:${C(t)?t.transactionMeta.update.key:"main"}:${e.key}`;H(o,({newValue:i,oldValue:r})=>{let a=t.timelineTopics.getRelatedKey(o.key);if(a){if(t.timelines.get(a)?.timeTraveling){let s=yo({key:a,type:"timeline"},(m)=>{s(),I(t,e,(p)=>{if(m==="redo"&&i)p.do(i);else if(m==="undo"&&r)p.undo(r);return p})},n,t);return}}let c=t.on.operationClose.subscribe(n,()=>{c();let l=O(t,e),s=i===null?-1:l.getUpdateNumber(i),m=s-l.cacheUpdateNumber;if(i&&m===1)I(t,e,(p)=>(p.do(i),p));else t.logger.info("\u274C","mutable_atom",e.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${s}`)})},n,t)}mutableState;latestUpdateState;dispose;constructor(e,o){this.mutableState=e;let t=y(o);this.latestUpdateState=this.initializeState(e,t),this.observeCore(e,this.latestUpdateState,t),this.updateCore(e,this.latestUpdateState,t),t.trackers.set(e.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(e.key)}}}function Oe(e,o,t){e.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${e.config.name}"`);let n=y(e),i=n.atoms.get(o.key);if(i&&i.type==="mutable_atom")return e.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Q(i);let r=new A,a={...o,type:"mutable_atom",install:(s)=>{return s.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${s.config.name}"`),Oe(s,o,t)},subject:r};if(t)a.family=t;let c=o.default();n.atoms.set(a.key,a),De(o.key,e),Z(o.key,c,r,n);let l=Q(a);if(o.effects){let s=0,m=[];for(let p of o.effects){let u=p({setSelf:(x)=>{I(e,l,x)},onSet:(x)=>H(l,x,`effect[${s}]`,e)});if(u)m.push(u);++s}a.cleanup=()=>{for(let p of m)p()}}if(new me(l,e),!t)Ko(l,o,e);return l}class fo{Update;latestUpdateAtoms;mutableAtoms;constructor(e,o){let t=re(o,{key:`*${e.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=g(t,o),this.mutableAtoms=e,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){let i=N(n.token.family.subKey);W(o,this.latestUpdateAtoms,i),new me(n.token,o)}}),this.latestUpdateAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){let i=N(n.token.family.subKey),r=W(o,this.mutableAtoms,i);if(r)new me(r,o)}})}}function Me(e,o,t){let n={key:o.key,type:"mutable_atom_family"},i=e.families.get(o.key);if(i)e.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${ee(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let r=new A,c=Object.assign((l)=>{let s=S(l),m={key:o.key,subKey:s},p=`${o.key}(${s})`,u=y(e),x={key:p,default:()=>o.default(l),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)x.effects=o.effects(l);let R=Oe(u,x,m);return r.next({type:"state_creation",token:R}),R},n,{subject:r,install:(l)=>Me(l,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:t});return e.families.set(o.key,c),it(c,o,e),new fo(c,e),n}var uo=(e,o)=>{let t=y(o),n=`${e.key}:JSON`;return t.families.get(n)};var z=(e,o)=>{if(o.family){let n=y(e),r={key:`${o.family.key}:JSON`,type:"selector_family"},a=g(r,n),c=JSON.parse(o.family.subKey);return K(e,a,c)}return{type:"selector",key:`${o.key}:JSON`}};var ie=(e)=>{let t={type:"atom",key:`*${e.key}`};if(e.family)t.family={key:`*${e.family.key}`,subKey:e.family.subKey};return t};function Eo(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Je(e,o,t){let n=o.valueMap.get(e.key),i=t.valueMap.get(e.key);if(n===i){if(n===void 0)return typeof e.default==="function"?e.default():e.default;o.logger.info("\uD83D\uDCC3","atom",e.key,"copying");let r=e.toJson(n),a=e.fromJson(r);return t.valueMap.set(e.key,a),new me(e,o),a}return i}function Z(e,o,t,n){let i=n.valueMap.get(e);if(i instanceof xe)i.use(o);if(o instanceof Promise){let r=new xe(o);return n.valueMap.set(e,r),r.then((a)=>{Z(e,a,t,n),t.next({newValue:a,oldValue:r})}).catch((a)=>{n.logger.error("\uD83D\uDCA5","state",e,"rejected:",a)}),r}return n.valueMap.set(e,o),o}var wo=(e,o)=>{let t=o.valueMap.get(e.key);if(e.type==="mutable_atom"&&C(o)){let{parent:n}=o;t=Je(e,n,o)}return t},Io=(e,o)=>{let t=o.valueMap.get(e);if(t instanceof xe){let n=t,i=o.selectors.get(e)??o.readonlySelectors.get(e);if(i)n.use(i.get());return}if(o.operation.open)o.operation.prev.set(e,t);o.valueMap.delete(e),o.logger.info("\uD83D\uDDD1","state",e,"evicted")};var Po=(e,o)=>{return y(o).atomsThatAreDefault.has(e)},De=(e,o)=>{let t=y(o);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(e)},No=(e,o)=>{let t=y(o);t.atomsThatAreDefault=new Set(y(o).atomsThatAreDefault),t.atomsThatAreDefault.delete(e)};function ae(e,o,t){e.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${e.config.name}"`);let n=y(e),i=n.atoms.get(o.key);if(i&&i.type==="atom")return e.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Q(i);let r=new A,a={...o,type:"atom",install:(s)=>{return s.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${s.config.name}"`),ae(s,o,t)},subject:r};if(t)a.family=t;let c=o.default;if(o.default instanceof Function)c=o.default();n.atoms.set(a.key,a),De(o.key,e),Z(o.key,c,r,n);let l=Q(a);if(o.effects){let s=0,m=[];for(let p of o.effects){let u=p({setSelf:(x)=>{I(e,l,x)},onSet:(x)=>H(l,x,`effect[${s}]`,e)});if(u)m.push(u);++s}a.cleanup=()=>{for(let p of m)p()}}return l}function $o(e,o){if("mutable"in o){let i=Oe(e,o,void 0);return e.on.atomCreation.next(i),i}let n=ae(e,o,void 0);return e.on.atomCreation.next(n),n}function co(e,o){let t=y(o),{key:n}=e,i=g(e,t);if(!i.family)o.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{i.cleanup?.();let r=o.valueMap.get(i.key);g({key:i.family.key,type:"atom_family"},o).subject.next({type:"state_disposal",token:e,value:r});let c=t.molecules.get(i.family.subKey);if(c)c.tokens.delete(n);if(t.atoms.delete(n),t.valueMap.delete(n),t.selectorAtoms.delete(n),t.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),e.type==="mutable_atom"){let l=ie(e);co(l,o),o.trackers.delete(n)}if(o.logger.info("\uD83D\uDD25","atom",n,"deleted"),C(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:e});else o.on.atomDisposal.next(e)}}class X extends Set{mode="record";subject=new A;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(e,o=0){super(e);if(e instanceof X)this.parent=e,this.cacheUpdateNumber=e.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(t)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=t})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(e){let o=new X(e.members,e.cacheLimit);return o.cache=e.cache,o.cacheIdx=e.cacheIdx,o.cacheUpdateNumber=e.cacheUpdateNumber,o}add(e){let o=super.add(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S(e)}`);return o}clear(){let e=this.mode==="record"?[...this]:null;if(super.clear(),e)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(e)}`)}delete(e){let o=super.delete(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S(e)}`);return o}parent;child=null;transactionUpdates=null;transaction(e){this.mode="transaction",this.transactionUpdates=[],this.child=new X(this);let o=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(e(this.child)){for(let n of this.transactionUpdates)this.doStep(n);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",t),t}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(e,o){return this.subject.subscribe(e,o)}subscribe(e,o){return this.subject.subscribe(e,(t)=>{o(`${this.cacheUpdateNumber}=${t}`)})}emit(e){this.subject.next(e)}doStep(e){let o=e.indexOf(":"),t=e.substring(0,o),n=e.substring(o+1);switch(t){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){let o=e.indexOf("=");return Number(e.substring(0,o))}do(e){let o=e.indexOf("="),t=Number(e.substring(0,o)),n=t-this.cacheUpdateNumber;if(n>0){if(n===1){this.mode="playback";let r=e.substring(o+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(n)<this.cacheLimit){let r=this.cacheIdx+n;if(this.cache[r]===e)return null;this.mode="playback";let c=!1;while(!c){this.cacheIdx%=this.cacheLimit;let s=this.cache[this.cacheIdx];if(this.cacheIdx--,!s)return"OUT_OF_RANGE";this.undo(s),c=this.cacheIdx===r-1}let l=e.substring(o+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(e){let o=e.indexOf(":"),t=e.substring(0,o),n=e.substring(o+1);switch(t){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{let i=JSON.parse(n);for(let r of i)this.add(r);break}case"tx":{let i=n.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(e){let o=e.indexOf("=");if(Number(e.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let n=e.substring(o+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function _(e){return e[0].toUpperCase()+e.slice(1)}class ko{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(e,o){let t=this.toolkit;this.toolkit=e,o(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(e){let o=e.config.name,t=this.alternates.get(o);if(t)return t;let n=new ko(this.options,this.defaultContent,e);return this.alternates.set(o,n),n.alternates=this.alternates,n}constructor(e,o,t=$.STORE){this.store=t,this.options=e,this.defaultContent=o,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${e.key}`,this),this.retrieve=(T,d)=>{let M=this.toolkit.seek(T,d);if(M)return M;let F=this.store.molecules.get(S(d));if(F){let k=g(T,t);return oe(F,k,t)}if(t.config.lifespan==="immortal")throw new D(T,d,t);return te(t,T,d)},this.toolkit={get:(...T)=>O(t,...T),set:(...T)=>{I(t,...T)},find:this.retrieve,seek:(...T)=>W(t,...T),json:(T)=>z(t,T),dispose:(...T)=>{V(t,...T)}};let n=e.between[0],i=e.between[1],r=Me(t,{key:`${e.key}/relatedKeys`,default:()=>new X,mutable:!0,fromJson:(T)=>X.fromJSON(T),toJson:(T)=>T.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};let a=({get:T},d)=>T(this.retrieve(r,d)),c=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d),b=this.retrieve(r,M);F(k,(h)=>h.add(M)),F(b,(h)=>h.add(d))},l=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d),b=this.retrieve(r,M),h,j;F(k,(E)=>{if(E.delete(M),E.size===0)h=`"${d}"`;return E}),F(b,(E)=>{if(E.delete(d),E.size===0)j=`"${M}"`;return E})},s=(T,d,M)=>{let{get:F,set:k}=T,b=this.retrieve(r,d),h=F(b);for(let j of h){if(M.includes(j))continue;let Y=this.retrieve(r,j);k(Y,(L)=>{return L.delete(d),L})}k(b,(j)=>{return j.transaction((E)=>{E.clear();for(let Y of M){let L=a(T,Y),Ro=L.has(d);if(this.relations.cardinality==="1:n"){let Co=[];for(let be of L){if(be===d)continue;let ge=a(T,be);if(ge.delete(Y),ge.size===0)Co.push(be)}if(!Ro&&L.size>0)L.clear();for(let be of Co){let ge=[Y,be].sort(),dt=`"${ge[0]}:${ge[1]}"`;this.molecules.delete(dt)}}if(!Ro)L.add(d);E.add(Y)}return!0}),j})},m=(T,d,M)=>{let{set:F}=T,k=this.retrieve(r,d);F(k,(b)=>{return b.transaction((h)=>{for(let j of M)h.add(j);return!0}),b});for(let b of M){let h=this.retrieve(r,b);F(h,(j)=>{return j.add(d),j})}return!0},p=(T,d,M)=>{let F=a(T,d);return M?F.has(M):F.size>0},u={getRelatedKeys:(T)=>a(this.toolkit,T),addRelation:(T,d)=>{c(this.toolkit,T,d)},deleteRelation:(T,d)=>{l(this.toolkit,T,d)},replaceRelationsSafely:(T,d)=>{s(this.toolkit,T,d)},replaceRelationsUnsafely:(T,d)=>{m(this.toolkit,T,d)},has:(T,d)=>p(this.toolkit,T,d)},x,R,v;if(o){R=re(t,{key:`${e.key}/content`,default:o},["join","content"]),v=Xo(t,{key:`${e.key}/content-molecules`,new:class k{key;constructor(b,h){this.key=h}}});let T=({get:k},b)=>k(this.retrieve(R,b)),d=({set:k},b,h)=>{k(this.retrieve(R,b),h)},M=(k,b)=>{let h=t.molecules.get(`"${b}"`);if(h)this.toolkit.dispose(h),this.molecules.delete(`"${b}"`)};x=Object.assign(u,{getContent:(k)=>{return T(this.toolkit,k)},setContent:(k,b)=>{d(this.toolkit,k,b)},deleteContent:(k)=>{M(this.toolkit,k)}})}else x=u;let f=new q(e,{externalStore:x,isAType:e.isAType,isBType:e.isBType,makeContentKey:(...T)=>{let d=T.sort(),M=`${d[0]}:${d[1]}`,[F,k]=d.map((b)=>this.molecules.get(S(b)));if(t.config.lifespan==="immortal"&&F&&k){let b=y(t),h=ne(b,[F,k],v,M);this.molecules.set(`"${M}"`,g(h,b))}return M}}),J=()=>le(t,{key:`${e.key}/singleRelatedKey`,get:(T)=>({get:d})=>{let M=this.retrieve(r,T),F=d(M);for(let k of F)return k;return null}},["join","keys"]),w=()=>{return le(t,{key:`${e.key}/multipleRelatedKeys`,get:(T)=>({get:d})=>{let M=uo(r,t),F=this.retrieve(M,T);return d(F).members}},["join","keys"])},B=()=>le(t,{key:`${e.key}/singleRelatedEntry`,get:(T)=>({get:d})=>{let M=this.retrieve(r,T),F=d(M);for(let k of F){let b=f.isAType?.(T)?T:void 0,h=b===void 0?T:void 0;b??=k,h??=k;let j=f.makeContentKey(b,h),E=this.retrieve(R,j),Y=d(E);return[k,Y]}return null}},["join","entries"]),U=()=>le(t,{key:`${e.key}/multipleRelatedEntries`,get:(T)=>({get:d})=>{let M=uo(r,t),F=this.retrieve(M,T);return d(F).members.map((b)=>{let h=f.isAType?.(T)?T:void 0,j=h===void 0?T:void 0;h??=b,j??=b;let E=f.makeContentKey(h,j),Y=this.retrieve(R,E),L=d(Y);return[b,L]})}},["join","entries"]);switch(e.cardinality){case"1:1":{let T=J(),d=`${n}KeyOf${_(i)}`,M=`${i}KeyOf${_(n)}`,F={[d]:T,[M]:T},k;if(o){let b=B(),h=`${n}EntryOf${_(i)}`,j=`${i}EntryOf${_(n)}`,E={[h]:b,[j]:b};k=Object.assign(F,E)}else k=F;this.relations=f,this.states=k;break}case"1:n":{let T=J(),d=w(),M=`${n}KeyOf${_(i)}`,F=`${i}KeysOf${_(n)}`,k={[M]:T,[F]:d},b;if(o){let h=B(),j=U(),E=`${n}EntryOf${_(i)}`,Y=`${i}EntriesOf${_(n)}`,L={[E]:h,[Y]:j};b=Object.assign(k,L)}else b=k;this.relations=f,this.states=b;break}default:{let T=w(),d=`${n}KeysOf${_(i)}`,M=`${i}KeysOf${_(n)}`,F={[d]:T,[M]:T},k;if(o){let b=U(),h=`${n}EntriesOf${_(i)}`,j=`${i}EntriesOf${_(n)}`,E={[h]:b,[j]:b};k=Object.assign(F,E)}else k=F;this.relations=f,this.states=k}}}}function Ue(e,o,t=$.STORE){return So(t).set(e.key,new ko(e,o,t)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function So(e){if("joins"in e&&e.joins instanceof Map)return e.joins;let o=new Map;return e.joins=o,o}function he(e,o){let t=So(o),n=t.get(e.key);if(n===void 0){if(n=So($.STORE).get(e.key)?.in(o),n===void 0)throw new Error(`Join "${e.key}" not found in store "${o.config.name}"`);t.set(e.key,n)}return n}function qe(e,o,t){let n=he(e,t),i;switch(e.cardinality){case"1:1":{let r=`${e.a}KeyOf${_(e.b)}`,a=`${e.b}KeyOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntryOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntryOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}break}case"1:n":{let r=`${e.a}KeyOf${_(e.b)}`,a=`${e.b}KeysOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntryOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntriesOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}break}case"n:n":{let r=`${e.a}KeysOf${_(e.b)}`,a=`${e.b}KeysOf${_(e.a)}`;i={get[r](){let l=n.states[r];return n.retrieve(l,o)},get[a](){let l=n.states[a];return n.retrieve(l,o)}};let c=`${e.a}EntriesOf${_(e.b)}`;if(c in n.states){let l=`${e.b}EntriesOf${_(e.a)}`;Object.assign(i,{get[c](){let s=n.states[c];return n.retrieve(s,o)},get[l](){let s=n.states[l];return n.retrieve(s,o)}})}}}return i}function Vo(e,o){return qe(e,o,$.STORE)}function Ye(e,o,t){let n=he(e,t),i=y(t);if(C(i)){let{toolkit:r}=i.transactionMeta;n.transact(r,({relations:a})=>{o(a)})}else o(n.relations)}function Jt(e,o){return he(e,o).core.findRelatedKeysState}function at(e){return Jt(e,$.STORE)}class lt extends Map{set(e,o){if(this.has(e))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:e,value:o}),this;return super.set(e,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Le{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new lt;static create(e,o){let t=new Le(e),{type:n,globals:i,actions:r,perspectives:a}=o(t),c={type:n,key:e,globals:i,actions:r,perspectives:a};return Le.existing.set(e,c),c}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":{let[t,n]=e;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:n})}break}return this}}function my(e){let{key:o,config:t}=e,n=Le.create(o,t),{actions:i}=n;for(let r of i)Lo(o,r.key,$.STORE);return Uo(o,-1,$.STORE),n}var uy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),bo=ue({key:"roomIndex",default:()=>new X,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),ht={enteredAtEpoch:0},we=Ue({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(e)=>typeof e==="string",isBType:(e)=>typeof e==="string"},ht),dy=We({key:"usersInMyRoomView",get:(e)=>({find:o})=>{let t=at(we);return[o(t,e)]}});import{spawn as $t}from"child_process";class Se{emit;listeners;globalListeners;handleEvent(e,...o){for(let n of this.globalListeners)n(e,...o);let t=this.listeners.get(e);if(t)for(let n of t)n(...o)}id="no_id_retrieved";constructor(e){this.emit=e;this.listeners=new Map,this.globalListeners=new Set}on(e,o){let t=this.listeners.get(e);if(t)t.add(o);else this.listeners.set(e,new Set([o]));return this}onAny(e){return this.globalListeners.add(e),this}off(e,o){let t=this.listeners.get(e);if(t)if(o)t.delete(o);else this.listeners.delete(e);return this}offAny(e){return this.globalListeners.delete(e),this}}class go extends Se{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(e){if(Array.isArray(e)){let[o,...t]=e;switch(o){case"i":this.logger.info(...t);break;case"w":this.logger.warn(...t);break;case"e":this.logger.error(...t);break}}}constructor(e,o,t){super((n,...i)=>{let r=JSON.stringify([n,...i])+"\x03",a=(c)=>{if(c.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});if(this.process=e,this.key=o,this.logger=t??{info:(...n)=>{console.info(this.id,this.key,...n)},warn:(...n)=>{console.warn(this.id,this.key,...n)},error:(...n)=>{console.error(this.id,this.key,...n)}},this.process.stdout.on("data",(n)=>{let i=n.toString();if(i==="ALIVE")return;this.unprocessedEvents.push(...i.split("\x03"));let r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let a=N(this.incompleteData);this.handleEvent(...a);while(this.unprocessedEvents.length>0){let c=this.unprocessedEvents.shift();if(c){if(this.unprocessedEvents.length===0)this.incompleteData=c;a=N(c),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)=>{let i=n.toString();this.unprocessedLogs.push(...i.split("\x03"));let r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let a=N(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=N(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 st extends Se{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(e){super((...o)=>{return this.out.next(o),this});this.id=e,this.in=new A,this.out=new A,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let e of this.disposalFunctions)e()}}class xo extends Se{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...e){this.process.stderr.write(S(e.map((o)=>o instanceof X?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...e)=>{this.log("i",...e)},warn:(...e)=>{this.log("w",...e)},error:(...e)=>{this.log("e",...e)}};constructor(){super((e,...o)=>{let t=JSON.stringify([e,...o]);return this.process.stdout.write(t+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(e)=>{let o=e.toString();this.unprocessedEvents.push(...o.split("\x03"));let t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{let n=N(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){let i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;let r=N(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");let o=new st(`user:${e}`);this.relays.set(e,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){let n=t(o);if(n)o.disposalFunctions.push(n)}this.on(`user:${e}`,(...t)=>{o.in.next(t)}),o.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(e)=>{let o=this.relays.get(e);if(this.off(`relay:${e}`),o)o.dispose(),this.relays.delete(e)}),process.stdout.write("ALIVE")}relay(e){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(e)}}var Ao=ye({key:"roomArguments",default:["echo",["Hello World!"]]}),ct=We({key:"room",get:(e)=>async({get:o,find:t})=>{let n=t(Ao,e),i=o(n),[r,a]=i,c=await new Promise((l)=>{let s=$t(r,a,{env:process.env}),m=(p)=>{if(p.toString()==="ALIVE")s.stdout.off("data",m),l(s)};s.stdout.on("data",m)});return new go(c,e)}});var Hy=Ke({key:"createRoom",do:({get:e,set:o,find:t},n,i,r)=>{let a=r?[i,r]:[i],c=t(Ao,n);o(c,a),o(bo,(m)=>m.add(n));let l=t(ct,n);return e(l)}}),Vy=Ke({key:"joinRoom",do:(e,o,t,n)=>{let i={enteredAtEpoch:n};return Ye(we,(r)=>{r.set({room:o,user:t},i)},e.env().store),i}}),Dy=Ke({key:"leaveRoom",do:(e,o,t)=>{Ye(we,(n)=>{n.delete({room:o,user:t})},e.env().store)}}),Uy=Ke({key:"destroyRoom",do:(e,o)=>{Ye(we,(t)=>{t.delete({room:o})},e.env().store),e.set(bo,(t)=>(t.delete(o),t))}});function Mo(e,o){return o.map((t)=>{switch(t.type){case"transaction_update":{let n=Mo(e,t.updates);return{...t,updates:n}}default:return t}}).filter((t)=>{switch(t.type){case"atom_update":case"selector_update":return e.includes(t.key);case"state_creation":return e.includes(t.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var Ly=ye({key:"redactor",default:{occlude:(e)=>e}}),ke=ye({key:"unacknowledgedUpdates",default:()=>[]});var mt=ye({key:"sockets",default:null}),op=ue({key:"socketsIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),tp=ue({key:"usersIndex",mutable:!0,default:()=>new X,toJson:(e)=>e.toJSON(),fromJson:(e)=>X.fromJSON(e)}),Fo=Ue({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(e)=>e.startsWith("user::"),isBType:(e)=>e.startsWith("socket::")});function yt(e,o,t,n){let i=o.key;return function r(){let a=[];for(let l of o.globals){let s=l.type==="mutable_atom"?z(e,l):l,m=O(e,s);a.push(s,m)}for(let l of o.perspectives){let{viewAtoms:s,resourceAtoms:m}=l,p=K(e,s,t),u=O(e,p);e.logger.info("\uD83D\uDC41","atom",m.key,`${t} can see`,{viewAtoms:s,resourceAtoms:m,userView:u});for(let x of u){let R=x.type==="mutable_atom"?z(e,x):x,v=O(e,R);a.push(R,v)}}let c=P(e)?e.transactionMeta.epoch.get(i)??null:null;n?.emit(`continuity-init:${i}`,c,a)}}function pt(e,o,t){let n=o.key;return function i(r){e.logger.info("\uD83D\uDECE\uFE0F","continuity",n,"received",r);let{key:a,id:c}=r,l=`tx-run:${a}:${c}`,s=`${l}:start`,m=`${l}:end`;performance.mark(s);try{se({type:"transaction",key:a},c,e)(...r.params)}catch(u){if(u instanceof Error)e.logger.error("\u274C","continuity",n,`failed to run transaction ${a} from ${t} with update ${c}`,u.message)}performance.mark(m);let p=performance.measure(l,s,m);e?.logger.info("\uD83D\uDE80","transaction",a,c,t,p.duration)}}function Tt(e,o,t,n){let i=o.key;return function r(a){if(e.logger.info("\uD83D\uDC4D","continuity",i,`${t} acknowledged epoch ${a}`),n[0]?.epoch===a)I(e,ke,t,(l)=>{return l.shift(),e.logger.info("\uD83D\uDC4D","continuity",i,`${t} unacknowledged update queue now has`,l.length,"items"),l})}}function ft(e,o,t,n){let i=o.key,r=[];for(let a of o.actions){let c=po(a,(l)=>{try{let s=o.globals.map((u)=>{if(u.type==="atom")return u.key;return ie(u).key}).concat(o.perspectives.flatMap((u)=>{let{viewAtoms:x}=u,R=K(e,x,t);return O(e,R).map((f)=>{return f.type==="mutable_atom"?"*"+f.key:f.key})})),m=Mo(s,l.updates),p={...l,updates:m};I(e,ke,t,(u)=>{if(p)u.push(p),u.sort((x,R)=>x.epoch-R.epoch),e.logger.info("\uD83D\uDC4D","continuity",i,`${t} unacknowledged update queue now has`,u.length,"items");return u}),n?.emit(`tx-new:${i}`,p)}catch(s){if(s instanceof Error)e.logger.error("\u274C","continuity",i,`${t} failed to send update from transaction ${a.key} to ${t}`,s.message)}},`sync-continuity:${i}:${t}`,e);r.push(c)}return r}function ut(e,o,t,n){let i=o.key,r=[];for(let a of o.perspectives){let{viewAtoms:c}=a,l=K(e,c,t),s=H(l,({oldValue:m,newValue:p})=>{let u=m.map((f)=>f.key),x=p.map((f)=>f.key),R=m.filter((f)=>!x.includes(f.key)),v=p.filter((f)=>!u.includes(f.key)).flatMap((f)=>{let J=f.type==="mutable_atom"?z(e,f):f,w=O(e,J);return[J,w]});if(e.logger.info("\uD83D\uDC41","atom",a.resourceAtoms.key,`${t} has a new perspective`,{oldKeys:u,newKeys:x,revealed:v,concealed:R}),v.length>0)n?.emit(`reveal:${i}`,v);if(R.length>0)n?.emit(`conceal:${i}`,R)},`sync-continuity:${i}:${t}:perspective:${a.resourceAtoms.key}`,e);r.push(s)}return r}function wp({socket:e,store:o=$.STORE}){return function t(n){let i=e,r=n.key,a=qe(Fo,`socket::${i.id}`,o).userKeyOfSocket,c=O(o,a);if(!c)return o.logger.error("\u274C","continuity",r,`Tried to create a synchronizer for a socket (${i.id}) that is not connected to a user.`),()=>{};let l=qe(Fo,c,o).socketKeyOfUser,s=H(l,({newValue:J})=>{if(o.logger.info("\uD83D\uDC4B","continuity",r,`seeing ${c} on new socket ${J}`),J===null){o.logger.warn("\u274C","continuity",r,`User (${c}) is not connected to a socket, waiting for them to reappear.`);return}let w=K(o,mt,J);i=O(o,w);for(let U of m)i?.emit(`tx-new:${r}`,U)},`sync-continuity:${r}:${c}`,o),m=O(o,ke,c),p=[],u=ut(o,n,c,i),x=ft(o,n,c,i);p.push(...u,...x);let R=yt(o,n,c,e);i.off(`get:${r}`,R),i.on(`get:${r}`,R);let v=pt(o,n,c);i.off(`tx-run:${r}`,v),i.on(`tx-run:${r}`,v);let f=Tt(o,n,c,m);return i?.on(`ack:${r}`,f),()=>{for(let J of p)J();i?.off(`ack:${r}`,f),i?.off(`get:${r}`,R),i?.off(`tx-run:${r}`,v)}}}var Be=new xo;Object.assign(console,Be.logger,{log:Be.logger.info});Be.on("timeToStop",function e(){Be.logger.info("\uD83D\uDEEC game worker exiting"),process.exit(0)});Be.logger.info("\uD83D\uDEEB game worker ready");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tempest.games",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.25",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"eslint-plugin-react-refresh": "0.4.16",
|
|
52
52
|
"globals": "15.14.0",
|
|
53
53
|
"rimraf": "6.0.1",
|
|
54
|
-
"sass-embedded": "1.83.
|
|
54
|
+
"sass-embedded": "1.83.1",
|
|
55
55
|
"tsx": "4.19.2",
|
|
56
56
|
"typescript": "5.7.2",
|
|
57
57
|
"typescript-eslint": "8.19.0",
|