tempest.games 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # tempest.games
2
2
 
3
+ ## 0.1.19
4
+
5
+ ### Patch Changes
6
+
7
+ - eee505e: 🐛 ixed bug where tribunal would throw when trying to ban an IP again.
8
+ - eee505e: 🐛 Added missing `interactive-db` script to bin.
9
+
3
10
  ## 0.1.18
4
11
 
5
12
  ### Patch Changes
@@ -35,4 +35,4 @@ var z4=Object.create;var{getPrototypeOf:_4,defineProperty:hW,getOwnPropertyNames
35
35
  hash text NOT NULL,
36
36
  created_at bigint
37
37
  )
38
- `;await S.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(M)}`),await S.execute(J);let W=(await S.all(R`select id, hash, created_at from ${R.identifier(M)}.${R.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(A)=>{for await(let k of T)if(!W||Number(W.created_at)<k.folderMillis){for(let X of k.sql)await A.execute(R.raw(X));await A.execute(R`insert into ${R.identifier(M)}.${R.identifier(f)} ("hash", "created_at") values(${k.hash}, ${k.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`\$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let S=[R`with `];for(let[$,f]of T.entries())if(S.push(R`${R.identifier(f._.alias)} as (${f._.sql})`),$<T.length-1)S.push(R`, `);return S.push(R` `),R.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:f}){let M=this.buildWithCTE(f),J=$?R` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?R` where ${S}`:void 0;return R`${M}delete from ${T}${F}${J}`}buildUpdateSet(T,S){let $=T[c.Symbol.Columns],f=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),M=f.length;return R.join(f.flatMap((J,F)=>{let W=$[J],A=S[J]??R.param(W.onUpdateFn(),W),k=R`${R.identifier(this.casing.getColumnCasing(W))} = ${A}`;if(F<M-1)return[k,R.raw(", ")];return[k]}))}buildUpdateQuery({table:T,set:S,where:$,returning:f,withList:M}){let J=this.buildWithCTE(M),F=this.buildUpdateSet(T,S),W=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,A=$?R` where ${$}`:void 0;return R`${J}update ${T} set ${F}${A}${W}`}buildSelection(T,{isSingleTable:S=!1}={}){let $=T.length,f=T.flatMap(({field:M},J)=>{let F=[];if(V(M,t.Aliased)&&M.isSelectionField)F.push(R.identifier(M.fieldAlias));else if(V(M,t.Aliased)||V(M,t)){let W=V(M,t.Aliased)?M.sql:M;if(S)F.push(new t(W.queryChunks.map((A)=>{if(V(A,q))return R.identifier(this.casing.getColumnCasing(A));return A})));else F.push(W);if(V(M,t.Aliased))F.push(R` as ${R.identifier(M.fieldAlias)}`)}else if(V(M,NT))if(S)F.push(R.identifier(this.casing.getColumnCasing(M)));else F.push(M);if(J<$-1)F.push(R`, `);return F});return R.join(f)}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:f,having:M,table:J,joins:F,orderBy:W,groupBy:A,limit:k,offset:X,lockingClause:y,distinct:K,setOperators:G}){let z=$??nS(S);for(let MT of z)if(V(MT.field,NT)&&PS(MT.field.table)!==(V(J,fS)?J._.alias:V(J,nJ)?J[hT].name:V(J,t)?void 0:PS(J))&&!((fT)=>F?.some(({alias:UT})=>UT===(fT[c.Symbol.IsAlias]?PS(fT):fT[c.Symbol.BaseName])))(MT.field.table)){let fT=PS(MT.field.table);throw new Error(`Your "${MT.path.join("->")}" field references a column "${fT}"."${MT.field.name}", but the table "${fT}" is not part of the query! Did you forget to join it?`)}let Q=!F||F.length===0,E=this.buildWithCTE(T),B;if(K)B=K===!0?R` distinct`:R` distinct on (${R.join(K.on,R`, `)})`;let L=this.buildSelection(z,{isSingleTable:Q}),b=(()=>{if(V(J,c)&&J[c.Symbol.OriginalName]!==J[c.Symbol.Name]){let MT=R`${R.identifier(J[c.Symbol.OriginalName])}`;if(J[c.Symbol.Schema])MT=R`${R.identifier(J[c.Symbol.Schema])}.${MT}`;return R`${MT} ${R.identifier(J[c.Symbol.Name])}`}return J})(),C=[];if(F)for(let[MT,fT]of F.entries()){if(MT===0)C.push(R` `);let UT=fT.table,VS=fT.lateral?R` lateral`:void 0;if(V(UT,cS)){let N=UT[cS.Symbol.Name],p=UT[cS.Symbol.Schema],kT=UT[cS.Symbol.OriginalName],_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else if(V(UT,ES)){let N=UT[hT].name,p=UT[hT].schema,kT=UT[hT].originalName,_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else C.push(R`${R.raw(fT.joinType)} join${VS} ${UT} on ${fT.on}`);if(MT<F.length-1)C.push(R` `)}let D=R.join(C),H=f?R` where ${f}`:void 0,U=M?R` having ${M}`:void 0,Z;if(W&&W.length>0)Z=R` order by ${R.join(W,R`, `)}`;let h;if(A&&A.length>0)h=R` group by ${R.join(A,R`, `)}`;let O=typeof k==="object"||typeof k==="number"&&k>=0?R` limit ${k}`:void 0,o=X?R` offset ${X}`:void 0,P=R.empty();if(y){let MT=R` for ${R.raw(y.strength)}`;if(y.config.of)MT.append(R` of ${R.join(Array.isArray(y.config.of)?y.config.of:[y.config.of],R`, `)}`);if(y.config.noWait)MT.append(R` no wait`);else if(y.config.skipLocked)MT.append(R` skip locked`);P.append(MT)}let a=R`${E}select${B} ${L} from ${b}${D}${H}${h}${U}${Z}${O}${o}${P}`;if(G.length>0)return this.buildSetOperations(a,G);return a}buildSetOperations(T,S){let[$,...f]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:f,limit:M,orderBy:J,offset:F}}){let W=R`(${T.getSQL()}) `,A=R`(${f.getSQL()})`,k;if(J&&J.length>0){let G=[];for(let z of J)if(V(z,q))G.push(R.identifier(z.name));else if(V(z,t)){for(let Q=0;Q<z.queryChunks.length;Q++){let E=z.queryChunks[Q];if(V(E,q))z.queryChunks[Q]=R.identifier(E.name)}G.push(R`${z}`)}else G.push(R`${z}`);k=R` order by ${R.join(G,R`, `)} `}let X=typeof M==="object"||typeof M==="number"&&M>=0?R` limit ${M}`:void 0,y=R.raw(`${S} ${$?"all ":""}`),K=F?R` offset ${F}`:void 0;return R`${W}${y}${A}${k}${X}${K}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:f,withList:M}){let J=[],F=T[c.Symbol.Columns],W=Object.entries(F).filter(([G,z])=>!z.shouldDisableInsert()),A=W.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,z]of S.entries()){let Q=[];for(let[E,B]of W){let L=z[E];if(L===void 0||V(L,IS)&&L.value===void 0)if(B.defaultFn!==void 0){let b=B.defaultFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else if(!B.default&&B.onUpdateFn!==void 0){let b=B.onUpdateFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else Q.push(R`default`);else Q.push(L)}if(J.push(Q),G<S.length-1)J.push(R`, `)}let k=this.buildWithCTE(M),X=R.join(J),y=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,K=$?R` on conflict ${$}`:void 0;return R`${k}insert into ${T} ${A} values ${X}${K}${y}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){let f=S?R` concurrently`:void 0,M=$?R` with no data`:void 0;return R`refresh materialized view${f} ${T}${M}`}prepareTyping(T){if(V(T,WW)||V(T,FW))return"json";else if(V(T,AW))return"decimal";else if(V(T,kW))return"time";else if(V(T,XW)||V(T,yW))return"timestamp";else if(V(T,fW)||V(T,MW))return"date";else if(V(T,KW))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:f,tableConfig:M,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:A}){let k=[],X,y,K=[],G,z=[];if(J===!0)k=Object.entries(M.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:w$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let E=Object.fromEntries(Object.entries(M.columns).map(([H,U])=>[H,w$(U,F)]));if(J.where){let H=typeof J.where==="function"?J.where(E,h8()):J.where;G=H&&xJ(H,F)}let B=[],L=[];if(J.columns){let H=!1;for(let[U,Z]of Object.entries(J.columns)){if(Z===void 0)continue;if(U in M.columns){if(!H&&Z===!0)H=!0;L.push(U)}}if(L.length>0)L=H?L.filter((U)=>J.columns?.[U]===!0):Object.keys(M.columns).filter((U)=>!L.includes(U))}else L=Object.keys(M.columns);for(let H of L){let U=M.columns[H];B.push({tsKey:H,value:U})}let b=[];if(J.with)b=Object.entries(J.with).filter((H)=>!!H[1]).map(([H,U])=>({tsKey:H,queryConfig:U,relation:M.relations[H]}));let C;if(J.extras){C=typeof J.extras==="function"?J.extras(E,{sql:R}):J.extras;for(let[H,U]of Object.entries(C))B.push({tsKey:H,value:_1(U,F)})}for(let{tsKey:H,value:U}of B)k.push({dbKey:V(U,t.Aliased)?U.fieldAlias:M.columns[H].name,tsKey:H,field:V(U,NT)?w$(U,F):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof J.orderBy==="function"?J.orderBy(E,v8()):J.orderBy??[];if(!Array.isArray(D))D=[D];K=D.map((H)=>{if(V(H,NT))return w$(H,F);return xJ(H,F)}),X=J.limit,y=J.offset;for(let{tsKey:H,queryConfig:U,relation:Z}of b){let h=n8(S,$,Z),O=Hf(Z.referencedTable),o=$[O],P=`${F}_${H}`,a=jJ(...h.fields.map((UT,VS)=>TW(w$(h.references[VS],P),w$(UT,F)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[o],tableConfig:S[o],queryConfig:V(Z,r$)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:P,joinOn:a,nestedQueryRelation:Z}),fT=R`${R.identifier(P)}.${R.identifier("data")}`.as(H);z.push({on:R`true`,table:new fS(MT.sql,{},P),alias:P,joinType:"left",lateral:!0}),k.push({dbKey:H,tsKey:H,field:fT,relationTableTsKey:o,isJson:!0,selection:MT.selection})}}if(k.length===0)throw new sF({message:`No fields selected for table "${M.tsName}" ("${F}")`});let Q;if(G=jJ(A,G),W){let E=R`json_build_array(${R.join(k.map(({field:b,tsKey:C,isJson:D})=>D?R`${R.identifier(`${F}_${C}`)}.${R.identifier("data")}`:V(b,t.Aliased)?b.sql:b),R`, `)})`;if(V(W,qJ))E=R`coalesce(json_agg(${E}${K.length>0?R` order by ${R.join(K,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:E.as("data"),isJson:!0,relationTableTsKey:M.tsName,selection:k}];if(X!==void 0||y!==void 0||K.length>0)Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:X,offset:y,orderBy:K,setOperators:[]}),G=void 0,X=void 0,y=void 0,K=[];else Q=eF(f,F);Q=this.buildSelectQuery({table:V(Q,cS)?Q:new fS(Q,{},F),fields:{},fieldsFlat:B.map(({field:b})=>({path:[],field:V(b,NT)?w$(b,F):b})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]})}else Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:k.map(({field:E})=>({path:[],field:V(E,NT)?w$(E,F):E})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]});return{tableTsKey:M.tsName,sql:Q,selection:k}}}class US{static[Y]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===hT)return{...T[hT],selectedFields:new Proxy(T[hT].selectedFields,this)};if(typeof S==="symbol")return T[S];let f=(V(T,fS)?T._.selectedFields:V(T,ES)?T[hT].selectedFields:T)[S];if(V(f,t.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let M=f.clone();return M.isSelectionField=!0,M}if(V(f,t)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(V(f,NT)){if(this.config.alias)return new Proxy(f,new GM(new Proxy(f.table,new CJ(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new US(this.config))}}class l1{static[Y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class zS{static[Y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}from(T){let S=!!this.fields,$;if(this.fields)$=this.fields;else if(V(T,fS))$=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(V(T,nJ))$=T[hT].selectedFields;else if(V(T,t))$={};else $=c2(T);return new u1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class kK extends l1{static[Y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:f,dialect:M,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=f,this.dialect=M,this._={selectedFields:S},this.tableName=U1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{let f=this.tableName,M=U1(S);if(typeof M==="string"&&this.config.joins?.some((J)=>J.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof M==="string"&&!V(S,t)){let J=V(S,fS)?S._.selectedFields:V(S,ES)?S[hT].selectedFields:S[c.Symbol.Columns];this.config.fields[M]=J}}if(typeof $==="function")$=$(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:$,table:S,joinType:T,alias:M}),typeof M==="string")switch(T){case"left":{this.joinsNotNullableMap[M]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return($)=>{let f=typeof $==="function"?$(iY()):$;if(!Q1(this.getSelectedFields(),f.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:T,isAll:S,rightSelect:f}),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(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}else{let S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new fS(this.getSQL(),this.config.fields,T),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new US({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class u1 extends kK{static[Y]="PgSelect";_prepare(T){let{session:S,config:$,dialect:f,joinsNotNullableMap:M}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return QT.startActiveSpan("drizzle.prepareQuery",()=>{let J=nS($.fields),F=S.prepareQuery(f.sqlToQuery(this.getSQL()),J,T,!0);return F.joinsNotNullableMap=M,F})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}n2(u1,[GS]);function EM(T,S){return($,f,...M)=>{let J=[f,...M].map((F)=>({type:T,isAll:S,rightSelect:F}));for(let F of J)if(!Q1($.getSelectedFields(),F.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return $.addSetOperators(J)}}var iY=()=>({union:lY,unionAll:uY,intersect:dY,intersectAll:rY,except:aY,exceptAll:eY}),lY=EM("union",!1),uY=EM("union",!0),dY=EM("intersect",!1),rY=EM("intersect",!0),aY=EM("except",!1),eY=EM("except",!0);class d1{static[Y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,Vf)?T:void 0,this.dialectConfig=V(T,Vf)?void 0:T}$with(T){let S=this;return{as($){if(typeof $==="function")$=$(S);return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...T){let S=this;function $(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function M(J,F){return new zS({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:f,selectDistinctOn:M}}select(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Vf(this.dialectConfig);return this.dialect}}class r1 extends GS{constructor(T,S,$){super();this.session=S,this.dialect=$,this.config={view:T}}static[Y]="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:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}class LW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgUpdateBuilder";set(T){return new XK(this.table,$W(this.table,T),this.session,this.dialect,this.withList)}}class XK extends GS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={set:S,table:T,withList:M}}static[Y]="PgUpdate";config;where(T){return this.config.where=T,this}returning(T=this.config.table[c.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)}prepare(T){return this._prepare(T)}execute=(T)=>{return this._prepare().execute(T)};$dynamic(){return this}}class cJ extends t{constructor(T){super(cJ.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=cJ.buildCount(T.source,T.filters)}sql;static[Y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return R`(select count(*) from ${T}${R.raw(" where ").if(S)}${S})`}static buildCount(T,S){return R`select count(*) as count from ${T}${R.raw(" where ").if(S)}${S};`}then(T,S){return Promise.resolve(this.session.count(this.sql)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class e1{constructor(T,S,$,f,M,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F}static[Y]="PgRelationalQueryBuilder";findMany(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class a1 extends GS{constructor(T,S,$,f,M,J,F,W,A){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F,this.config=W,this.mode=A}static[Y]="PgRelationalQuery";_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:S,builtQuery:$}=this._toSQL();return this.session.prepareQuery($,void 0,T,!0,(f,M)=>{let J=f.map((F)=>wW(this.schema,this.tableConfig,F,S.selection,M));if(this.mode==="first")return J[0];return J})})}prepare(T){return this._prepare(T)}_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 T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}execute(){return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class s1 extends GS{constructor(T,S,$,f){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=f}static[Y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class oJ{constructor(T,S,$){if(this.dialect=T,this.session=S,this._=$?{schema:$.schema,fullSchema:$.fullSchema,tableNamesMap:$.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,M]of Object.entries(this._.schema))this.query[f]=new e1($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[f],M,T,S)}static[Y]="PgDatabase";query;$with(T){let S=this;return{as($){if(typeof $==="function")$=$(new d1(S.dialect));return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(T,S){return new cJ({source:T,filters:S,session:this.session})}with(...T){let S=this;function $(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function M(A,k){return new zS({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:A}})}function J(A){return new LW(A,S.session,S.dialect,T)}function F(A){return new BW(A,S.session,S.dialect,T)}function W(A){return new VW(A,S.session,S.dialect,T)}return{select:$,selectDistinct:f,selectDistinctOn:M,update:J,insert:F,delete:W}}select(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new LW(T,this.session,this.dialect)}insert(T){return new BW(T,this.session,this.dialect)}delete(T){return new VW(T,this.session,this.dialect)}refreshMaterializedView(T){return new r1(T,this.session,this.dialect)}execute(T){let S=typeof T==="string"?R.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),f=this.session.prepareQuery($,void 0,void 0,!1);return new s1(()=>f.execute(),S,$,(M)=>f.mapResult(M,!0))}transaction(T,S){return this.session.transaction(T,S)}}class yK{constructor(T,S){this.unique=T,this.name=S}static[Y]="PgIndexBuilderOn";on(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),$}),this.unique,!1,this.name)}onOnly(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,$}),this.unique,!0,this.name)}using(T,...S){return new NW(S.map(($)=>{if(V($,t))return $;$=$;let f=new LJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),f}),this.unique,!0,this.name,T)}}class NW{static[Y]="PgIndexBuilder";config;constructor(T,S,$,f,M="btree"){this.config={name:f,columns:T,unique:S,only:$,method:M}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new KK(this.config,T)}}class KK{static[Y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function TA(T){return new yK(!0,T)}class SA{constructor(T){this.query=T}getQuery(){return this.query}mapResult(T,S){return T}static[Y]="PgPreparedQuery";joinsNotNullableMap}class $A{constructor(T){this.dialect=T}static[Y]="PgSession";execute(T){return QT.startActiveSpan("drizzle.operation",()=>{return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).execute()})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T){let S=await this.execute(T);return Number(S[0].count)}}class fA extends oJ{constructor(T,S,$,f=0){super(T,S,$);this.schema=$,this.nestedIndex=f}static[Y]="PgTransaction";rollback(){throw new H1}getTransactionConfigSQL(T){let S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return R.raw(S.join(" "))}setTransaction(T){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(T)}`)}}class wK extends SA{constructor(T,S,$,f,M,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=f,this.fields=M,this._isResponseInArrayMode=J,this.customResultMapper=F}static[Y]="PostgresJsPreparedQuery";async execute(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$);let{fields:f,queryString:M,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!f&&!W)return QT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(M,$)});let A=await QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":M,"drizzle.query.params":JSON.stringify($)}),J.unsafe(M,$).values()});return QT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(A):A.map((k)=>P2(f,k,F))})})}all(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$),QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.client.unsafe(this.queryString,$)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class gJ extends $A{constructor(T,S,$,f={}){super(S);this.client=T,this.schema=$,this.options=f,this.logger=f.logger??new E1}static[Y]="PostgresJsSession";logger;prepareQuery(T,S,$,f,M){return new wK(this.client,T.sql,T.params,this.logger,S,f,M)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async($)=>{let f=new gJ($,this.dialect,this.schema,this.options),M=new MA(this.dialect,f,this.schema);if(S)await M.setTransaction(S);return T(M)})}}class MA extends fA{constructor(T,S,$,f=0){super(T,S,$,f);this.session=S}static[Y]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{let $=new gJ(S,this.dialect,this.schema,this.session.options),f=new MA(this.dialect,$,this.schema);return T(f)})}}class YK extends oJ{static[Y]="PostgresJsDatabase"}function QM(T,S={}){let $=(A)=>A;for(let A of["1184","1082","1083","1114"])T.options.parsers[A]=$,T.options.serializers[A]=$;T.options.serializers["114"]=$,T.options.serializers["3802"]=$;let f=new Vf({casing:S.casing}),M;if(S.logger===!0)M=new D1;else if(S.logger!==!1)M=S.logger;let J;if(S.schema){let A=P8(S.schema,c8);J={fullSchema:S.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let F=new gJ(T,f,J,{logger:M}),W=new YK(f,F,J);return W.$client=T,W}function CW(...T){if(typeof T[0]==="string"){let S=DM(T[0]);return QM(S,T[1])}if(o2(T[0])){let{connection:S,client:$,...f}=T[0];if($)return QM($,f);if(typeof S==="object"&&S.url!==void 0){let{url:J,...F}=S,W=DM(J,F);return QM(W,f)}let M=DM(S);return QM(M,f)}return QM(T[0],T[1])}((T)=>{function S($){return QM({},$)}T.mock=S})(CW||(CW={}));function RK(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[H,U]of Object.entries(S))if(U==="")delete S[H]}if(!!T.skipValidation)return S;let M=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=dM(M),A=dM(J),k=dM(F),X=T.isServer??(typeof window==="undefined"||("Deno"in window)),y=W.merge(k),K=A.merge(k).merge(W),G=X?K.safeParse(S):y.safeParse(S),z=T.onValidationError??((H)=>{throw console.error("\u274C Invalid environment variables:",H.flatten().fieldErrors),new Error("Invalid environment variables")}),Q=T.onInvalidAccess??((H)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return z(G.error);let E=(H)=>{if(!T.clientPrefix)return!0;return!H.startsWith(T.clientPrefix)&&!(H in k.shape)},B=(H)=>{return X||!E(H)},L=(H)=>{return H==="__esModule"||H==="$$typeof"},b=(T.extends??[]).reduce((H,U)=>{return Object.assign(H,U)},{}),C=Object.assign(G.data,b);return new Proxy(C,{get(H,U){if(typeof U!=="string")return;if(L(U))return;if(!B(U))return Q(U);return Reflect.get(H,U)}})}var sY="__vite_start_time"in globalThis,T7=typeof window!=="undefined",Xm="vitest"in globalThis,j$=RK({isServer:!sY&&!T7,server:{CI:HT.string().transform((T)=>!0).optional(),POSTGRES_USER:HT.string(),POSTGRES_PASSWORD:HT.string(),POSTGRES_DATABASE:HT.string(),POSTGRES_HOST:HT.string(),POSTGRES_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:HT.string().transform((T)=>JSON.parse(T)).pipe(HT.array(HT.string())),OPENAI_API_KEY:HT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:HT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var FA={};E4(FA,{users:()=>Bf,userChanges:()=>$7,untrackedUserColumnNames:()=>S7,twoFactorMethod:()=>HK,trackedUserColumnName:()=>_K,trackableUserColumnNames:()=>zK,role:()=>GK,players:()=>JA,passwordResetAttempts:()=>M7,loginHistory:()=>f7,games:()=>xW,banishedIps:()=>jW});function OK(T){return R`lower(${T})`}var GK=dF("role",["admin","user"]),Bf=d$("users",{id:bS().primaryKey().defaultRandom(),username:MS({length:16}).notNull(),email:MS({length:254}).notNull(),hash:MS({length:64}).notNull(),salt:MS({length:36}).notNull(),createdAt:M$({withTimezone:!0}).notNull().defaultNow(),createdIp:MS({length:45}).notNull(),isActive:IJ().notNull().default(!1),verifiedAt:M$({withTimezone:!0}),userRole:GK().default("user")},(T)=>[TA("usernameUniqueIndex").on(OK(T.username)),TA("emailUniqueIndex").on(OK(T.email))]),S7=["id","createdAt","createdIp","isActive","salt","verifiedAt"],zK=["username","email","hash","userRole"],_K=dF("trackedUserColumnName",zK),$7=d$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),xW=d$("games",{id:bS().primaryKey().defaultRandom()}),JA=d$("players",{userId:bS().notNull().references(()=>Bf.id),gameId:bS().notNull().references(()=>xW.id),score:JW().notNull()},(T)=>[q8({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),f7=d$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Bf.id),loginTime:M$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:IJ().notNull().default(!1)}),HK=dF("twoFactorMethod",["email","phone"]),M7=d$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:HK().notNull()}),jW=d$("banishedIps",{ip:MS({length:45}).primaryKey(),reason:MS({length:2048}).notNull(),banishedAt:M$({withTimezone:!0}).notNull().defaultNow(),banishedUntil:M$({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class WA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(J7.resolve(__dirname,"notify_update.sql"));let T=[PS(Bf),PS(xW),PS(JA)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{let $=S.split(","),f=$[0],M=$[1],J=`${f}("${M}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(T=!1,S={host:j$.POSTGRES_HOST,port:j$.POSTGRES_PORT,user:j$.POSTGRES_USER,password:j$.POSTGRES_PASSWORD,database:j$.POSTGRES_DATABASE}){this.options=S,this.sql=DM(S),this.drizzle=CW(this.sql,{schema:FA,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new JT);this.observers.get(T).subscribe("SINGLETON",S)}}import*as IW from"fs";import*as DK from"readline";function F7(T){let $=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(f,M,J,F,W)=>{let k={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[J];return`${F}-${k}-${M}T${W}`});return new Date($)}async function EK(T,S="/var/log/nginx/access.log",$=new Date){let f=new Map;if(!IW.existsSync(S))return T.error(`Log file not found: ${S}`),f;let M=IW.createReadStream(S),J=DK.createInterface({input:M,crlfDelay:Number.POSITIVE_INFINITY}),F=new Date($.getTime()-3600000);return J.on("line",(W)=>{let A=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,k=W.match(A);if(k?.groups){let X=k.groups.ip,y=k.groups.dateTime,K=F7(y);if(!Number.isNaN(K.getTime())){if(K>=F&&K<=$){let G=f.get(X);if(!G)G=[],f.set(X,G);G.push(W)}}else T.error(`Failed to parse date: ${y}`)}}),new Promise((W,A)=>{J.on("error",(k)=>{A(k)}),J.on("close",()=>{W(f)})})}var W7=["Network security adjudicator, your job is to determine if an IP address should be banned.","The IP address in question created the following logs on our server today:","```nginx.log\n"].join("\n");function QK(T){return W7+T.join("\n\n")}var UK={schema:HT.union([HT.object({shouldBanIp:HT.literal(!1)}),HT.object({shouldBanIp:HT.literal(!0),veryConciseReason:HT.string()})]),fallback:{shouldBanIp:!1}};var w7=[".env","php"];async function VK({generator:T,logFilePath:S,logger:$,now:f}){let M=T.usdBudget,J=new WA({logQuery(C,D){$.info("\uD83D\uDCDD query",C,D)}}),F=await EK($,S,f),W=[],A=T.from(UK),k=0,X=0;for(let[C,D]of F){$.info(`\uD83D\uDD0D ruling on ${C}. logs:`),$.info(D.map((U)=>`\t${U}`).join("\n"));let H=!1;for(let U of w7)if(D.some((Z)=>Z.includes(U))){W.push({ip:C,reason:`Always ban ${U}`}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--always ban ${U}\n`),H=!0;break}if(H)continue;if(T.usdBudget>T.usdFloor){let U=QK(D),Z=await A(U);if(Z.shouldBanIp)W.push({ip:C,reason:Z.veryConciseReason}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--${Z.veryConciseReason}\n`);else X++,$.info(` \uD83D\uDD4A\uFE0F not banning ${C}\n`);k++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${k}/${F.size} ips\n`);break}}let y=W.length;if(W.length>0)await J.drizzle.insert(jW).values(W);let K=[],G=HT.object({lastDay:HT.string()}),z=K7(import.meta.dirname,"tribunal.cache.json");if(k7(z)){let C=await X7(z,"utf-8");try{let D=JSON.parse(C),{lastDay:H}=G.parse(D);if(H){let U=new Date(H);K.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:SW(jW.banishedAt,U)}))}}catch(D){$.error(D)}}try{await Promise.all(K.map((C)=>new Promise((D,H)=>A7(`iptables -D INPUT -s ${C.ip} -j DROP`).on("exit",(U)=>{if(U===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${C.ip}`),D();else H(new Error(`iptables exited with code ${U}`))}))))}catch(C){if(C instanceof Error)$.error(C.message);else{let D=OM(C);$.error("iptables exited with error",D)}}await y7(z,JSON.stringify({lastDay:f}),"utf-8"),$.info(`\u2728 banned ${y} ips, didn't ban ${X} ips`);let E=M-T.usdBudget,B=E.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),L=M.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),b=Math.round(E/M*100);$.info(`\uD83D\uDCB8 spent ${B}, ${b}% of ${L} budget`)}var I$=new F0;Object.assign(console,I$.logger,{log:I$.logger.info});process.on("SIGINT",()=>{I$.logger.info("\u2757 received SIGINT; exiting gracefully"),bW()});process.on("SIGTERM",()=>{I$.logger.info("\u2757 received SIGTERM; exiting gracefully"),bW()});process.on("exit",()=>{I$.logger.info("\u2757 received exit; exiting gracefully"),bW()});I$.logger.info("\uD83D\uDEEB tribunal worker ready");var Y7=new rX({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:j$.OPENAI_API_KEY,cachingMode:"off",logger:I$.logger});if(j$.OPENAI_API_KEY===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await VK({generator:Y7,logFilePath:"/var/log/nginx/access.log",logger:I$.logger});bW();function bW(){I$.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
38
+ `;await S.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(M)}`),await S.execute(J);let W=(await S.all(R`select id, hash, created_at from ${R.identifier(M)}.${R.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(A)=>{for await(let k of T)if(!W||Number(W.created_at)<k.folderMillis){for(let X of k.sql)await A.execute(R.raw(X));await A.execute(R`insert into ${R.identifier(M)}.${R.identifier(f)} ("hash", "created_at") values(${k.hash}, ${k.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`\$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let S=[R`with `];for(let[$,f]of T.entries())if(S.push(R`${R.identifier(f._.alias)} as (${f._.sql})`),$<T.length-1)S.push(R`, `);return S.push(R` `),R.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:f}){let M=this.buildWithCTE(f),J=$?R` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?R` where ${S}`:void 0;return R`${M}delete from ${T}${F}${J}`}buildUpdateSet(T,S){let $=T[c.Symbol.Columns],f=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),M=f.length;return R.join(f.flatMap((J,F)=>{let W=$[J],A=S[J]??R.param(W.onUpdateFn(),W),k=R`${R.identifier(this.casing.getColumnCasing(W))} = ${A}`;if(F<M-1)return[k,R.raw(", ")];return[k]}))}buildUpdateQuery({table:T,set:S,where:$,returning:f,withList:M}){let J=this.buildWithCTE(M),F=this.buildUpdateSet(T,S),W=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,A=$?R` where ${$}`:void 0;return R`${J}update ${T} set ${F}${A}${W}`}buildSelection(T,{isSingleTable:S=!1}={}){let $=T.length,f=T.flatMap(({field:M},J)=>{let F=[];if(V(M,t.Aliased)&&M.isSelectionField)F.push(R.identifier(M.fieldAlias));else if(V(M,t.Aliased)||V(M,t)){let W=V(M,t.Aliased)?M.sql:M;if(S)F.push(new t(W.queryChunks.map((A)=>{if(V(A,q))return R.identifier(this.casing.getColumnCasing(A));return A})));else F.push(W);if(V(M,t.Aliased))F.push(R` as ${R.identifier(M.fieldAlias)}`)}else if(V(M,NT))if(S)F.push(R.identifier(this.casing.getColumnCasing(M)));else F.push(M);if(J<$-1)F.push(R`, `);return F});return R.join(f)}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:f,having:M,table:J,joins:F,orderBy:W,groupBy:A,limit:k,offset:X,lockingClause:y,distinct:K,setOperators:G}){let z=$??nS(S);for(let MT of z)if(V(MT.field,NT)&&PS(MT.field.table)!==(V(J,fS)?J._.alias:V(J,nJ)?J[hT].name:V(J,t)?void 0:PS(J))&&!((fT)=>F?.some(({alias:UT})=>UT===(fT[c.Symbol.IsAlias]?PS(fT):fT[c.Symbol.BaseName])))(MT.field.table)){let fT=PS(MT.field.table);throw new Error(`Your "${MT.path.join("->")}" field references a column "${fT}"."${MT.field.name}", but the table "${fT}" is not part of the query! Did you forget to join it?`)}let Q=!F||F.length===0,E=this.buildWithCTE(T),B;if(K)B=K===!0?R` distinct`:R` distinct on (${R.join(K.on,R`, `)})`;let L=this.buildSelection(z,{isSingleTable:Q}),b=(()=>{if(V(J,c)&&J[c.Symbol.OriginalName]!==J[c.Symbol.Name]){let MT=R`${R.identifier(J[c.Symbol.OriginalName])}`;if(J[c.Symbol.Schema])MT=R`${R.identifier(J[c.Symbol.Schema])}.${MT}`;return R`${MT} ${R.identifier(J[c.Symbol.Name])}`}return J})(),C=[];if(F)for(let[MT,fT]of F.entries()){if(MT===0)C.push(R` `);let UT=fT.table,VS=fT.lateral?R` lateral`:void 0;if(V(UT,cS)){let N=UT[cS.Symbol.Name],p=UT[cS.Symbol.Schema],kT=UT[cS.Symbol.OriginalName],_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else if(V(UT,ES)){let N=UT[hT].name,p=UT[hT].schema,kT=UT[hT].originalName,_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else C.push(R`${R.raw(fT.joinType)} join${VS} ${UT} on ${fT.on}`);if(MT<F.length-1)C.push(R` `)}let D=R.join(C),H=f?R` where ${f}`:void 0,U=M?R` having ${M}`:void 0,Z;if(W&&W.length>0)Z=R` order by ${R.join(W,R`, `)}`;let h;if(A&&A.length>0)h=R` group by ${R.join(A,R`, `)}`;let O=typeof k==="object"||typeof k==="number"&&k>=0?R` limit ${k}`:void 0,o=X?R` offset ${X}`:void 0,P=R.empty();if(y){let MT=R` for ${R.raw(y.strength)}`;if(y.config.of)MT.append(R` of ${R.join(Array.isArray(y.config.of)?y.config.of:[y.config.of],R`, `)}`);if(y.config.noWait)MT.append(R` no wait`);else if(y.config.skipLocked)MT.append(R` skip locked`);P.append(MT)}let a=R`${E}select${B} ${L} from ${b}${D}${H}${h}${U}${Z}${O}${o}${P}`;if(G.length>0)return this.buildSetOperations(a,G);return a}buildSetOperations(T,S){let[$,...f]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:f,limit:M,orderBy:J,offset:F}}){let W=R`(${T.getSQL()}) `,A=R`(${f.getSQL()})`,k;if(J&&J.length>0){let G=[];for(let z of J)if(V(z,q))G.push(R.identifier(z.name));else if(V(z,t)){for(let Q=0;Q<z.queryChunks.length;Q++){let E=z.queryChunks[Q];if(V(E,q))z.queryChunks[Q]=R.identifier(E.name)}G.push(R`${z}`)}else G.push(R`${z}`);k=R` order by ${R.join(G,R`, `)} `}let X=typeof M==="object"||typeof M==="number"&&M>=0?R` limit ${M}`:void 0,y=R.raw(`${S} ${$?"all ":""}`),K=F?R` offset ${F}`:void 0;return R`${W}${y}${A}${k}${X}${K}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:f,withList:M}){let J=[],F=T[c.Symbol.Columns],W=Object.entries(F).filter(([G,z])=>!z.shouldDisableInsert()),A=W.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,z]of S.entries()){let Q=[];for(let[E,B]of W){let L=z[E];if(L===void 0||V(L,IS)&&L.value===void 0)if(B.defaultFn!==void 0){let b=B.defaultFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else if(!B.default&&B.onUpdateFn!==void 0){let b=B.onUpdateFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else Q.push(R`default`);else Q.push(L)}if(J.push(Q),G<S.length-1)J.push(R`, `)}let k=this.buildWithCTE(M),X=R.join(J),y=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,K=$?R` on conflict ${$}`:void 0;return R`${k}insert into ${T} ${A} values ${X}${K}${y}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){let f=S?R` concurrently`:void 0,M=$?R` with no data`:void 0;return R`refresh materialized view${f} ${T}${M}`}prepareTyping(T){if(V(T,WW)||V(T,FW))return"json";else if(V(T,AW))return"decimal";else if(V(T,kW))return"time";else if(V(T,XW)||V(T,yW))return"timestamp";else if(V(T,fW)||V(T,MW))return"date";else if(V(T,KW))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:f,tableConfig:M,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:A}){let k=[],X,y,K=[],G,z=[];if(J===!0)k=Object.entries(M.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:w$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let E=Object.fromEntries(Object.entries(M.columns).map(([H,U])=>[H,w$(U,F)]));if(J.where){let H=typeof J.where==="function"?J.where(E,h8()):J.where;G=H&&xJ(H,F)}let B=[],L=[];if(J.columns){let H=!1;for(let[U,Z]of Object.entries(J.columns)){if(Z===void 0)continue;if(U in M.columns){if(!H&&Z===!0)H=!0;L.push(U)}}if(L.length>0)L=H?L.filter((U)=>J.columns?.[U]===!0):Object.keys(M.columns).filter((U)=>!L.includes(U))}else L=Object.keys(M.columns);for(let H of L){let U=M.columns[H];B.push({tsKey:H,value:U})}let b=[];if(J.with)b=Object.entries(J.with).filter((H)=>!!H[1]).map(([H,U])=>({tsKey:H,queryConfig:U,relation:M.relations[H]}));let C;if(J.extras){C=typeof J.extras==="function"?J.extras(E,{sql:R}):J.extras;for(let[H,U]of Object.entries(C))B.push({tsKey:H,value:_1(U,F)})}for(let{tsKey:H,value:U}of B)k.push({dbKey:V(U,t.Aliased)?U.fieldAlias:M.columns[H].name,tsKey:H,field:V(U,NT)?w$(U,F):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof J.orderBy==="function"?J.orderBy(E,v8()):J.orderBy??[];if(!Array.isArray(D))D=[D];K=D.map((H)=>{if(V(H,NT))return w$(H,F);return xJ(H,F)}),X=J.limit,y=J.offset;for(let{tsKey:H,queryConfig:U,relation:Z}of b){let h=n8(S,$,Z),O=Hf(Z.referencedTable),o=$[O],P=`${F}_${H}`,a=jJ(...h.fields.map((UT,VS)=>TW(w$(h.references[VS],P),w$(UT,F)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[o],tableConfig:S[o],queryConfig:V(Z,r$)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:P,joinOn:a,nestedQueryRelation:Z}),fT=R`${R.identifier(P)}.${R.identifier("data")}`.as(H);z.push({on:R`true`,table:new fS(MT.sql,{},P),alias:P,joinType:"left",lateral:!0}),k.push({dbKey:H,tsKey:H,field:fT,relationTableTsKey:o,isJson:!0,selection:MT.selection})}}if(k.length===0)throw new sF({message:`No fields selected for table "${M.tsName}" ("${F}")`});let Q;if(G=jJ(A,G),W){let E=R`json_build_array(${R.join(k.map(({field:b,tsKey:C,isJson:D})=>D?R`${R.identifier(`${F}_${C}`)}.${R.identifier("data")}`:V(b,t.Aliased)?b.sql:b),R`, `)})`;if(V(W,qJ))E=R`coalesce(json_agg(${E}${K.length>0?R` order by ${R.join(K,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:E.as("data"),isJson:!0,relationTableTsKey:M.tsName,selection:k}];if(X!==void 0||y!==void 0||K.length>0)Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:X,offset:y,orderBy:K,setOperators:[]}),G=void 0,X=void 0,y=void 0,K=[];else Q=eF(f,F);Q=this.buildSelectQuery({table:V(Q,cS)?Q:new fS(Q,{},F),fields:{},fieldsFlat:B.map(({field:b})=>({path:[],field:V(b,NT)?w$(b,F):b})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]})}else Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:k.map(({field:E})=>({path:[],field:V(E,NT)?w$(E,F):E})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]});return{tableTsKey:M.tsName,sql:Q,selection:k}}}class US{static[Y]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===hT)return{...T[hT],selectedFields:new Proxy(T[hT].selectedFields,this)};if(typeof S==="symbol")return T[S];let f=(V(T,fS)?T._.selectedFields:V(T,ES)?T[hT].selectedFields:T)[S];if(V(f,t.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let M=f.clone();return M.isSelectionField=!0,M}if(V(f,t)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(V(f,NT)){if(this.config.alias)return new Proxy(f,new GM(new Proxy(f.table,new CJ(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new US(this.config))}}class l1{static[Y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class zS{static[Y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}from(T){let S=!!this.fields,$;if(this.fields)$=this.fields;else if(V(T,fS))$=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(V(T,nJ))$=T[hT].selectedFields;else if(V(T,t))$={};else $=c2(T);return new u1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class kK extends l1{static[Y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:f,dialect:M,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=f,this.dialect=M,this._={selectedFields:S},this.tableName=U1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{let f=this.tableName,M=U1(S);if(typeof M==="string"&&this.config.joins?.some((J)=>J.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof M==="string"&&!V(S,t)){let J=V(S,fS)?S._.selectedFields:V(S,ES)?S[hT].selectedFields:S[c.Symbol.Columns];this.config.fields[M]=J}}if(typeof $==="function")$=$(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:$,table:S,joinType:T,alias:M}),typeof M==="string")switch(T){case"left":{this.joinsNotNullableMap[M]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return($)=>{let f=typeof $==="function"?$(iY()):$;if(!Q1(this.getSelectedFields(),f.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:T,isAll:S,rightSelect:f}),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(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}else{let S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new fS(this.getSQL(),this.config.fields,T),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new US({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class u1 extends kK{static[Y]="PgSelect";_prepare(T){let{session:S,config:$,dialect:f,joinsNotNullableMap:M}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return QT.startActiveSpan("drizzle.prepareQuery",()=>{let J=nS($.fields),F=S.prepareQuery(f.sqlToQuery(this.getSQL()),J,T,!0);return F.joinsNotNullableMap=M,F})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}n2(u1,[GS]);function EM(T,S){return($,f,...M)=>{let J=[f,...M].map((F)=>({type:T,isAll:S,rightSelect:F}));for(let F of J)if(!Q1($.getSelectedFields(),F.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return $.addSetOperators(J)}}var iY=()=>({union:lY,unionAll:uY,intersect:dY,intersectAll:rY,except:aY,exceptAll:eY}),lY=EM("union",!1),uY=EM("union",!0),dY=EM("intersect",!1),rY=EM("intersect",!0),aY=EM("except",!1),eY=EM("except",!0);class d1{static[Y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,Vf)?T:void 0,this.dialectConfig=V(T,Vf)?void 0:T}$with(T){let S=this;return{as($){if(typeof $==="function")$=$(S);return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...T){let S=this;function $(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function M(J,F){return new zS({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:f,selectDistinctOn:M}}select(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Vf(this.dialectConfig);return this.dialect}}class r1 extends GS{constructor(T,S,$){super();this.session=S,this.dialect=$,this.config={view:T}}static[Y]="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:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}class LW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgUpdateBuilder";set(T){return new XK(this.table,$W(this.table,T),this.session,this.dialect,this.withList)}}class XK extends GS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={set:S,table:T,withList:M}}static[Y]="PgUpdate";config;where(T){return this.config.where=T,this}returning(T=this.config.table[c.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)}prepare(T){return this._prepare(T)}execute=(T)=>{return this._prepare().execute(T)};$dynamic(){return this}}class cJ extends t{constructor(T){super(cJ.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=cJ.buildCount(T.source,T.filters)}sql;static[Y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return R`(select count(*) from ${T}${R.raw(" where ").if(S)}${S})`}static buildCount(T,S){return R`select count(*) as count from ${T}${R.raw(" where ").if(S)}${S};`}then(T,S){return Promise.resolve(this.session.count(this.sql)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class e1{constructor(T,S,$,f,M,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F}static[Y]="PgRelationalQueryBuilder";findMany(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class a1 extends GS{constructor(T,S,$,f,M,J,F,W,A){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F,this.config=W,this.mode=A}static[Y]="PgRelationalQuery";_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:S,builtQuery:$}=this._toSQL();return this.session.prepareQuery($,void 0,T,!0,(f,M)=>{let J=f.map((F)=>wW(this.schema,this.tableConfig,F,S.selection,M));if(this.mode==="first")return J[0];return J})})}prepare(T){return this._prepare(T)}_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 T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}execute(){return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class s1 extends GS{constructor(T,S,$,f){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=f}static[Y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class oJ{constructor(T,S,$){if(this.dialect=T,this.session=S,this._=$?{schema:$.schema,fullSchema:$.fullSchema,tableNamesMap:$.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,M]of Object.entries(this._.schema))this.query[f]=new e1($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[f],M,T,S)}static[Y]="PgDatabase";query;$with(T){let S=this;return{as($){if(typeof $==="function")$=$(new d1(S.dialect));return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(T,S){return new cJ({source:T,filters:S,session:this.session})}with(...T){let S=this;function $(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function M(A,k){return new zS({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:A}})}function J(A){return new LW(A,S.session,S.dialect,T)}function F(A){return new BW(A,S.session,S.dialect,T)}function W(A){return new VW(A,S.session,S.dialect,T)}return{select:$,selectDistinct:f,selectDistinctOn:M,update:J,insert:F,delete:W}}select(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new LW(T,this.session,this.dialect)}insert(T){return new BW(T,this.session,this.dialect)}delete(T){return new VW(T,this.session,this.dialect)}refreshMaterializedView(T){return new r1(T,this.session,this.dialect)}execute(T){let S=typeof T==="string"?R.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),f=this.session.prepareQuery($,void 0,void 0,!1);return new s1(()=>f.execute(),S,$,(M)=>f.mapResult(M,!0))}transaction(T,S){return this.session.transaction(T,S)}}class yK{constructor(T,S){this.unique=T,this.name=S}static[Y]="PgIndexBuilderOn";on(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),$}),this.unique,!1,this.name)}onOnly(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,$}),this.unique,!0,this.name)}using(T,...S){return new NW(S.map(($)=>{if(V($,t))return $;$=$;let f=new LJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),f}),this.unique,!0,this.name,T)}}class NW{static[Y]="PgIndexBuilder";config;constructor(T,S,$,f,M="btree"){this.config={name:f,columns:T,unique:S,only:$,method:M}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new KK(this.config,T)}}class KK{static[Y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function TA(T){return new yK(!0,T)}class SA{constructor(T){this.query=T}getQuery(){return this.query}mapResult(T,S){return T}static[Y]="PgPreparedQuery";joinsNotNullableMap}class $A{constructor(T){this.dialect=T}static[Y]="PgSession";execute(T){return QT.startActiveSpan("drizzle.operation",()=>{return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).execute()})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T){let S=await this.execute(T);return Number(S[0].count)}}class fA extends oJ{constructor(T,S,$,f=0){super(T,S,$);this.schema=$,this.nestedIndex=f}static[Y]="PgTransaction";rollback(){throw new H1}getTransactionConfigSQL(T){let S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return R.raw(S.join(" "))}setTransaction(T){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(T)}`)}}class wK extends SA{constructor(T,S,$,f,M,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=f,this.fields=M,this._isResponseInArrayMode=J,this.customResultMapper=F}static[Y]="PostgresJsPreparedQuery";async execute(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$);let{fields:f,queryString:M,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!f&&!W)return QT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(M,$)});let A=await QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":M,"drizzle.query.params":JSON.stringify($)}),J.unsafe(M,$).values()});return QT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(A):A.map((k)=>P2(f,k,F))})})}all(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$),QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.client.unsafe(this.queryString,$)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class gJ extends $A{constructor(T,S,$,f={}){super(S);this.client=T,this.schema=$,this.options=f,this.logger=f.logger??new E1}static[Y]="PostgresJsSession";logger;prepareQuery(T,S,$,f,M){return new wK(this.client,T.sql,T.params,this.logger,S,f,M)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async($)=>{let f=new gJ($,this.dialect,this.schema,this.options),M=new MA(this.dialect,f,this.schema);if(S)await M.setTransaction(S);return T(M)})}}class MA extends fA{constructor(T,S,$,f=0){super(T,S,$,f);this.session=S}static[Y]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{let $=new gJ(S,this.dialect,this.schema,this.session.options),f=new MA(this.dialect,$,this.schema);return T(f)})}}class YK extends oJ{static[Y]="PostgresJsDatabase"}function QM(T,S={}){let $=(A)=>A;for(let A of["1184","1082","1083","1114"])T.options.parsers[A]=$,T.options.serializers[A]=$;T.options.serializers["114"]=$,T.options.serializers["3802"]=$;let f=new Vf({casing:S.casing}),M;if(S.logger===!0)M=new D1;else if(S.logger!==!1)M=S.logger;let J;if(S.schema){let A=P8(S.schema,c8);J={fullSchema:S.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let F=new gJ(T,f,J,{logger:M}),W=new YK(f,F,J);return W.$client=T,W}function CW(...T){if(typeof T[0]==="string"){let S=DM(T[0]);return QM(S,T[1])}if(o2(T[0])){let{connection:S,client:$,...f}=T[0];if($)return QM($,f);if(typeof S==="object"&&S.url!==void 0){let{url:J,...F}=S,W=DM(J,F);return QM(W,f)}let M=DM(S);return QM(M,f)}return QM(T[0],T[1])}((T)=>{function S($){return QM({},$)}T.mock=S})(CW||(CW={}));function RK(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[H,U]of Object.entries(S))if(U==="")delete S[H]}if(!!T.skipValidation)return S;let M=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=dM(M),A=dM(J),k=dM(F),X=T.isServer??(typeof window==="undefined"||("Deno"in window)),y=W.merge(k),K=A.merge(k).merge(W),G=X?K.safeParse(S):y.safeParse(S),z=T.onValidationError??((H)=>{throw console.error("\u274C Invalid environment variables:",H.flatten().fieldErrors),new Error("Invalid environment variables")}),Q=T.onInvalidAccess??((H)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return z(G.error);let E=(H)=>{if(!T.clientPrefix)return!0;return!H.startsWith(T.clientPrefix)&&!(H in k.shape)},B=(H)=>{return X||!E(H)},L=(H)=>{return H==="__esModule"||H==="$$typeof"},b=(T.extends??[]).reduce((H,U)=>{return Object.assign(H,U)},{}),C=Object.assign(G.data,b);return new Proxy(C,{get(H,U){if(typeof U!=="string")return;if(L(U))return;if(!B(U))return Q(U);return Reflect.get(H,U)}})}var sY="__vite_start_time"in globalThis,T7=typeof window!=="undefined",Xm="vitest"in globalThis,j$=RK({isServer:!sY&&!T7,server:{CI:HT.string().transform((T)=>!0).optional(),POSTGRES_USER:HT.string(),POSTGRES_PASSWORD:HT.string(),POSTGRES_DATABASE:HT.string(),POSTGRES_HOST:HT.string(),POSTGRES_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:HT.string().transform((T)=>JSON.parse(T)).pipe(HT.array(HT.string())),OPENAI_API_KEY:HT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:HT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var FA={};E4(FA,{users:()=>Bf,userChanges:()=>$7,untrackedUserColumnNames:()=>S7,twoFactorMethod:()=>HK,trackedUserColumnName:()=>_K,trackableUserColumnNames:()=>zK,role:()=>GK,players:()=>JA,passwordResetAttempts:()=>M7,loginHistory:()=>f7,games:()=>xW,banishedIps:()=>jW});function OK(T){return R`lower(${T})`}var GK=dF("role",["admin","user"]),Bf=d$("users",{id:bS().primaryKey().defaultRandom(),username:MS({length:16}).notNull(),email:MS({length:254}).notNull(),hash:MS({length:64}).notNull(),salt:MS({length:36}).notNull(),createdAt:M$({withTimezone:!0}).notNull().defaultNow(),createdIp:MS({length:45}).notNull(),isActive:IJ().notNull().default(!1),verifiedAt:M$({withTimezone:!0}),userRole:GK().default("user")},(T)=>[TA("usernameUniqueIndex").on(OK(T.username)),TA("emailUniqueIndex").on(OK(T.email))]),S7=["id","createdAt","createdIp","isActive","salt","verifiedAt"],zK=["username","email","hash","userRole"],_K=dF("trackedUserColumnName",zK),$7=d$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),xW=d$("games",{id:bS().primaryKey().defaultRandom()}),JA=d$("players",{userId:bS().notNull().references(()=>Bf.id),gameId:bS().notNull().references(()=>xW.id),score:JW().notNull()},(T)=>[q8({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),f7=d$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Bf.id),loginTime:M$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:IJ().notNull().default(!1)}),HK=dF("twoFactorMethod",["email","phone"]),M7=d$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:HK().notNull()}),jW=d$("banishedIps",{ip:MS({length:45}).primaryKey(),reason:MS({length:2048}).notNull(),banishedAt:M$({withTimezone:!0}).notNull().defaultNow(),banishedUntil:M$({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class WA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(J7.resolve(__dirname,"notify_update.sql"));let T=[PS(Bf),PS(xW),PS(JA)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{let $=S.split(","),f=$[0],M=$[1],J=`${f}("${M}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(T=!1,S={host:j$.POSTGRES_HOST,port:j$.POSTGRES_PORT,user:j$.POSTGRES_USER,password:j$.POSTGRES_PASSWORD,database:j$.POSTGRES_DATABASE}){this.options=S,this.sql=DM(S),this.drizzle=CW(this.sql,{schema:FA,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new JT);this.observers.get(T).subscribe("SINGLETON",S)}}import*as IW from"fs";import*as DK from"readline";function F7(T){let $=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(f,M,J,F,W)=>{let k={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[J];return`${F}-${k}-${M}T${W}`});return new Date($)}async function EK(T,S="/var/log/nginx/access.log",$=new Date){let f=new Map;if(!IW.existsSync(S))return T.error(`Log file not found: ${S}`),f;let M=IW.createReadStream(S),J=DK.createInterface({input:M,crlfDelay:Number.POSITIVE_INFINITY}),F=new Date($.getTime()-3600000);return J.on("line",(W)=>{let A=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,k=W.match(A);if(k?.groups){let X=k.groups.ip,y=k.groups.dateTime,K=F7(y);if(!Number.isNaN(K.getTime())){if(K>=F&&K<=$){let G=f.get(X);if(!G)G=[],f.set(X,G);G.push(W)}}else T.error(`Failed to parse date: ${y}`)}}),new Promise((W,A)=>{J.on("error",(k)=>{A(k)}),J.on("close",()=>{W(f)})})}var W7=["Network security adjudicator, your job is to determine if an IP address should be banned.","The IP address in question created the following logs on our server today:","```nginx.log\n"].join("\n");function QK(T){return W7+T.join("\n\n")}var UK={schema:HT.union([HT.object({shouldBanIp:HT.literal(!1)}),HT.object({shouldBanIp:HT.literal(!0),veryConciseReason:HT.string()})]),fallback:{shouldBanIp:!1}};var w7=[".env","php"];async function VK({generator:T,logFilePath:S,logger:$,now:f}){let M=T.usdBudget,J=new WA({logQuery(C,D){$.info("\uD83D\uDCDD query",C,D)}}),F=await EK($,S,f),W=[],A=T.from(UK),k=0,X=0;for(let[C,D]of F){$.info(`\uD83D\uDD0D ruling on ${C}. logs:`),$.info(D.map((U)=>`\t${U}`).join("\n"));let H=!1;for(let U of w7)if(D.some((Z)=>Z.includes(U))){W.push({ip:C,reason:`Always ban ${U}`}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--always ban ${U}\n`),H=!0;break}if(H)continue;if(T.usdBudget>T.usdFloor){let U=QK(D),Z=await A(U);if(Z.shouldBanIp)W.push({ip:C,reason:Z.veryConciseReason}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--${Z.veryConciseReason}\n`);else X++,$.info(` \uD83D\uDD4A\uFE0F not banning ${C}\n`);k++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${k}/${F.size} ips\n`);break}}let y=W.length;if(W.length>0)await J.drizzle.insert(jW).values(W).onConflictDoNothing();let K=[],G=HT.object({lastDay:HT.string()}),z=K7(import.meta.dirname,"tribunal.cache.json");if(k7(z)){let C=await X7(z,"utf-8");try{let D=JSON.parse(C),{lastDay:H}=G.parse(D);if(H){let U=new Date(H);K.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:SW(jW.banishedAt,U)}))}}catch(D){$.error(D)}}try{await Promise.all(K.map((C)=>new Promise((D,H)=>A7(`iptables -D INPUT -s ${C.ip} -j DROP`).on("exit",(U)=>{if(U===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${C.ip}`),D();else H(new Error(`iptables exited with code ${U}`))}))))}catch(C){if(C instanceof Error)$.error(C.message);else{let D=OM(C);$.error("iptables exited with error",D)}}await y7(z,JSON.stringify({lastDay:f}),"utf-8"),$.info(`\u2728 banned ${y} ips, didn't ban ${X} ips`);let E=M-T.usdBudget,B=E.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),L=M.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),b=Math.round(E/M*100);$.info(`\uD83D\uDCB8 spent ${B}, ${b}% of ${L} budget`)}var I$=new F0;Object.assign(console,I$.logger,{log:I$.logger.info});process.on("SIGINT",()=>{I$.logger.info("\u2757 received SIGINT; exiting gracefully"),bW()});process.on("SIGTERM",()=>{I$.logger.info("\u2757 received SIGTERM; exiting gracefully"),bW()});process.on("exit",()=>{I$.logger.info("\u2757 received exit; exiting gracefully"),bW()});I$.logger.info("\uD83D\uDEEB tribunal worker ready");var Y7=new rX({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:j$.OPENAI_API_KEY,cachingMode:"off",logger:I$.logger});if(j$.OPENAI_API_KEY===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await VK({generator:Y7,logFilePath:"/var/log/nginx/access.log",logger:I$.logger});bW();function bW(){I$.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tempest.games",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -8,7 +8,8 @@
8
8
  "bin": {
9
9
  "frontend": "./bin/frontend.bun.js",
10
10
  "backend": "./bin/backend.bun.js",
11
- "setup-db": "./bin/setup-db.bun.js"
11
+ "setup-db": "./bin/setup-db.bun.js",
12
+ "interactive-db": "./bin/interactive-db.bun.js"
12
13
  },
13
14
  "files": [
14
15
  "app",