@vitnode/core 1.2.0-canary.18 → 1.2.0-canary.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/dist/scripts/scripts.js
CHANGED
|
@@ -10,7 +10,7 @@ import{stat as ca}from"fs";import{stat as ua,readdir as ma}from"fs/promises";imp
|
|
|
10
10
|
created_at bigint
|
|
11
11
|
)
|
|
12
12
|
`;await t.execute(c`CREATE SCHEMA IF NOT EXISTS ${c.identifier(n)}`),await t.execute(o);let m=(await t.all(c`select id, hash, created_at from ${c.identifier(n)}.${c.identifier(s)} order by created_at desc limit 1`))[0];await t.transaction(async f=>{for await(let u of e)if(!m||Number(m.created_at)<u.folderMillis){for(let h of u.sql)await f.execute(c.raw(h));await f.execute(c`insert into ${c.identifier(n)}.${c.identifier(s)} ("hash", "created_at") values(${u.hash}, ${u.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[c`with `];for(let[i,s]of e.entries())t.push(c`${c.identifier(s._.alias)} as (${s._.sql})`),i<e.length-1&&t.push(c`, `);return t.push(c` `),c.join(t)}buildDeleteQuery({table:e,where:t,returning:i,withList:s}){let n=this.buildWithCTE(s),o=i?c` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,a=t?c` where ${t}`:void 0;return c`${n}delete from ${e}${a}${o}`}buildUpdateSet(e,t){let i=e[y.Symbol.Columns],s=Object.keys(i).filter(o=>t[o]!==void 0||i[o]?.onUpdateFn!==void 0),n=s.length;return c.join(s.flatMap((o,a)=>{let m=i[o],f=t[o]??c.param(m.onUpdateFn(),m),u=c`${c.identifier(this.casing.getColumnCasing(m))} = ${f}`;return a<n-1?[u,c.raw(", ")]:[u]}))}buildUpdateQuery({table:e,set:t,where:i,returning:s,withList:n,from:o,joins:a}){let m=this.buildWithCTE(n),f=e[B.Symbol.Name],u=e[B.Symbol.Schema],h=e[B.Symbol.OriginalName],p=f===h?void 0:f,x=c`${u?c`${c.identifier(u)}.`:void 0}${c.identifier(h)}${p&&c` ${c.identifier(p)}`}`,_=this.buildUpdateSet(e,t),$=o&&c.join([c.raw(" from "),this.buildFromTable(o)]),q=this.buildJoins(a),w=s?c` returning ${this.buildSelection(s,{isSingleTable:!o})}`:void 0,N=i?c` where ${i}`:void 0;return c`${m}update ${x} set ${_}${$}${q}${N}${w}`}buildSelection(e,{isSingleTable:t=!1}={}){let i=e.length,s=e.flatMap(({field:n},o)=>{let a=[];if(d(n,b.Aliased)&&n.isSelectionField)a.push(c.identifier(n.fieldAlias));else if(d(n,b.Aliased)||d(n,b)){let m=d(n,b.Aliased)?n.sql:n;t?a.push(new b(m.queryChunks.map(f=>d(f,g)?c.identifier(this.casing.getColumnCasing(f)):f))):a.push(m),d(n,b.Aliased)&&a.push(c` as ${c.identifier(n.fieldAlias)}`)}else d(n,E)&&(t?a.push(c.identifier(this.casing.getColumnCasing(n))):a.push(n));return o<i-1&&a.push(c`, `),a});return c.join(s)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[i,s]of e.entries()){i===0&&t.push(c` `);let n=s.table,o=s.lateral?c` lateral`:void 0,a=s.on?c` on ${s.on}`:void 0;if(d(n,B)){let m=n[B.Symbol.Name],f=n[B.Symbol.Schema],u=n[B.Symbol.OriginalName],h=m===u?void 0:s.alias;t.push(c`${c.raw(s.joinType)} join${o} ${f?c`${c.identifier(f)}.`:void 0}${c.identifier(u)}${h&&c` ${c.identifier(h)}`}${a}`)}else if(d(n,H)){let m=n[F].name,f=n[F].schema,u=n[F].originalName,h=m===u?void 0:s.alias;t.push(c`${c.raw(s.joinType)} join${o} ${f?c`${c.identifier(f)}.`:void 0}${c.identifier(u)}${h&&c` ${c.identifier(h)}`}${a}`)}else t.push(c`${c.raw(s.joinType)} join${o} ${n}${a}`);i<e.length-1&&t.push(c` `)}return c.join(t)}buildFromTable(e){if(d(e,y)&&e[y.Symbol.IsAlias]){let t=c`${c.identifier(e[y.Symbol.OriginalName])}`;return e[y.Symbol.Schema]&&(t=c`${c.identifier(e[y.Symbol.Schema])}.${t}`),c`${t} ${c.identifier(e[y.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:i,where:s,having:n,table:o,joins:a,orderBy:m,groupBy:f,limit:u,offset:h,lockingClause:p,distinct:x,setOperators:_}){let $=i??ie(t);for(let te of $)if(d(te.field,E)&&Z(te.field.table)!==(d(o,z)?o._.alias:d(o,Ie)?o[F].name:d(o,b)?void 0:Z(o))&&!(de=>a?.some(({alias:ar})=>ar===(de[y.Symbol.IsAlias]?Z(de):de[y.Symbol.BaseName])))(te.field.table)){let de=Z(te.field.table);throw new Error(`Your "${te.path.join("->")}" field references a column "${de}"."${te.field.name}", but the table "${de}" is not part of the query! Did you forget to join it?`)}let q=!a||a.length===0,w=this.buildWithCTE(e),N;x&&(N=x===!0?c` distinct`:c` distinct on (${c.join(x.on,c`, `)})`);let R=this.buildSelection($,{isSingleTable:q}),I=this.buildFromTable(o),J=this.buildJoins(a),Q=s?c` where ${s}`:void 0,C=n?c` having ${n}`:void 0,T;m&&m.length>0&&(T=c` order by ${c.join(m,c`, `)}`);let G;f&&f.length>0&&(G=c` group by ${c.join(f,c`, `)}`);let yt=typeof u=="object"||typeof u=="number"&&u>=0?c` limit ${u}`:void 0,or=h?c` offset ${h}`:void 0,De=c.empty();if(p){let te=c` for ${c.raw(p.strength)}`;p.config.of&&te.append(c` of ${c.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],c`, `)}`),p.config.noWait?te.append(c` nowait`):p.config.skipLocked&&te.append(c` skip locked`),De.append(te)}let Se=c`${w}select${N} ${R} from ${I}${J}${Q}${G}${C}${T}${yt}${or}${De}`;return _.length>0?this.buildSetOperations(Se,_):Se}buildSetOperations(e,t){let[i,...s]=t;if(!i)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:i,rightSelect:s,limit:n,orderBy:o,offset:a}}){let m=c`(${e.getSQL()}) `,f=c`(${s.getSQL()})`,u;if(o&&o.length>0){let _=[];for(let $ of o)if(d($,g))_.push(c.identifier($.name));else if(d($,b)){for(let q=0;q<$.queryChunks.length;q++){let w=$.queryChunks[q];d(w,g)&&($.queryChunks[q]=c.identifier(w.name))}_.push(c`${$}`)}else _.push(c`${$}`);u=c` order by ${c.join(_,c`, `)} `}let h=typeof n=="object"||typeof n=="number"&&n>=0?c` limit ${n}`:void 0,p=c.raw(`${t} ${i?"all ":""}`),x=a?c` offset ${a}`:void 0;return c`${m}${p}${f}${u}${h}${x}`}buildInsertQuery({table:e,values:t,onConflict:i,returning:s,withList:n,select:o,overridingSystemValue_:a}){let m=[],f=e[y.Symbol.Columns],u=Object.entries(f).filter(([w,N])=>!N.shouldDisableInsert()),h=u.map(([,w])=>c.identifier(this.casing.getColumnCasing(w)));if(o){let w=t;d(w,b)?m.push(w):m.push(w.getSQL())}else{let w=t;m.push(c.raw("values "));for(let[N,R]of w.entries()){let I=[];for(let[J,Q]of u){let C=R[J];if(C===void 0||d(C,X)&&C.value===void 0)if(Q.defaultFn!==void 0){let T=Q.defaultFn(),G=d(T,b)?T:c.param(T,Q);I.push(G)}else if(!Q.default&&Q.onUpdateFn!==void 0){let T=Q.onUpdateFn(),G=d(T,b)?T:c.param(T,Q);I.push(G)}else I.push(c`default`);else I.push(C)}m.push(I),N<w.length-1&&m.push(c`, `)}}let p=this.buildWithCTE(n),x=c.join(m),_=s?c` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,$=i?c` on conflict ${i}`:void 0,q=a===!0?c`overriding system value `:void 0;return c`${p}insert into ${e} ${h} ${q}${x}${$}${_}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:i}){let s=t?c` concurrently`:void 0,n=i?c` with no data`:void 0;return c`refresh materialized view${s} ${e}${n}`}prepareTyping(e){return d(e,tt)||d(e,et)?"json":d(e,rt)?"decimal":d(e,it)?"time":d(e,st)||d(e,nt)?"timestamp":d(e,Ze)||d(e,Xe)?"date":d(e,ot)?"uuid":"none"}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:s,tableConfig:n,queryConfig:o,tableAlias:a,nestedQueryRelation:m,joinOn:f}){let u=[],h,p,x=[],_,$=[];if(o===!0)u=Object.entries(n.columns).map(([N,R])=>({dbKey:R.name,tsKey:N,field:ce(R,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let w=Object.fromEntries(Object.entries(n.columns).map(([C,T])=>[C,ce(T,a)]));if(o.where){let C=typeof o.where=="function"?o.where(w,bo()):o.where;_=C&&He(C,a)}let N=[],R=[];if(o.columns){let C=!1;for(let[T,G]of Object.entries(o.columns))G!==void 0&&T in n.columns&&(!C&&G===!0&&(C=!0),R.push(T));R.length>0&&(R=C?R.filter(T=>o.columns?.[T]===!0):Object.keys(n.columns).filter(T=>!R.includes(T)))}else R=Object.keys(n.columns);for(let C of R){let T=n.columns[C];N.push({tsKey:C,value:T})}let I=[];o.with&&(I=Object.entries(o.with).filter(C=>!!C[1]).map(([C,T])=>({tsKey:C,queryConfig:T,relation:n.relations[C]})));let J;if(o.extras){J=typeof o.extras=="function"?o.extras(w,{sql:c}):o.extras;for(let[C,T]of Object.entries(J))N.push({tsKey:C,value:zr(T,a)})}for(let{tsKey:C,value:T}of N)u.push({dbKey:d(T,b.Aliased)?T.fieldAlias:n.columns[C].name,tsKey:C,field:d(T,E)?ce(T,a):T,relationTableTsKey:void 0,isJson:!1,selection:[]});let Q=typeof o.orderBy=="function"?o.orderBy(w,So()):o.orderBy??[];Array.isArray(Q)||(Q=[Q]),x=Q.map(C=>d(C,E)?ce(C,a):He(C,a)),h=o.limit,p=o.offset;for(let{tsKey:C,queryConfig:T,relation:G}of I){let yt=_o(t,i,G),or=Pe(G.referencedTable),De=i[or],Se=`${a}_${C}`,te=at(...yt.fields.map((Fo,qo)=>Qt(ce(yt.references[qo],Se),ce(Fo,a)))),de=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:e[De],tableConfig:t[De],queryConfig:d(G,xe)?T===!0?{limit:1}:{...T,limit:1}:T,tableAlias:Se,joinOn:te,nestedQueryRelation:G}),ar=c`${c.identifier(Se)}.${c.identifier("data")}`.as(C);$.push({on:c`true`,table:new z(de.sql,{},Se),alias:Se,joinType:"left",lateral:!0}),u.push({dbKey:C,tsKey:C,field:ar,relationTableTsKey:De,isJson:!0,selection:de.selection})}}if(u.length===0)throw new Ye({message:`No fields selected for table "${n.tsName}" ("${a}")`});let q;if(_=at(f,_),m){let w=c`json_build_array(${c.join(u.map(({field:I,tsKey:J,isJson:Q})=>Q?c`${c.identifier(`${a}_${J}`)}.${c.identifier("data")}`:d(I,b.Aliased)?I.sql:I),c`, `)})`;d(m,lt)&&(w=c`coalesce(json_agg(${w}${x.length>0?c` order by ${c.join(x,c`, `)}`:void 0}), '[]'::json)`);let N=[{dbKey:"data",tsKey:"data",field:w.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];h!==void 0||p!==void 0||x.length>0?(q=this.buildSelectQuery({table:Je(s,a),fields:{},fieldsFlat:[{path:[],field:c.raw("*")}],where:_,limit:h,offset:p,orderBy:x,setOperators:[]}),_=void 0,h=void 0,p=void 0,x=[]):q=Je(s,a),q=this.buildSelectQuery({table:d(q,B)?q:new z(q,{},a),fields:{},fieldsFlat:N.map(({field:I})=>({path:[],field:d(I,E)?ce(I,a):I})),joins:$,where:_,limit:h,offset:p,orderBy:x,setOperators:[]})}else q=this.buildSelectQuery({table:Je(s,a),fields:{},fieldsFlat:u.map(({field:w})=>({path:[],field:d(w,E)?ce(w,a):w})),joins:$,where:_,limit:h,offset:p,orderBy:x,setOperators:[]});return{tableTsKey:n.tsName,sql:q,selection:u}}};var Vt=class{static[l]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var W=class{static[l]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,i=e,s;return this.fields?s=this.fields:d(i,z)?s=Object.fromEntries(Object.keys(i._.selectedFields).map(n=>[n,i[n]])):d(i,Ie)?s=i[F].selectedFields:d(i,b)?s={}:s=hn(i),new Mt({table:i,fields:s,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},us=class extends Vt{static[l]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:n,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ge(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let m of ae(e))this.usedTables.add(m)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(i,s)=>{let n=this.tableName,o=ge(i);for(let a of ae(i))this.usedTables.add(a);if(typeof o=="string"&&this.config.joins?.some(a=>a.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof n=="string"&&(this.config.fields={[n]:this.config.fields}),typeof o=="string"&&!d(i,b))){let a=d(i,z)?i._.selectedFields:d(i,H)?i[F].selectedFields:i[y.Symbol.Columns];this.config.fields[o]=a}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:i,joinType:e,alias:o,lateral:t}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(e,t){return i=>{let s=typeof i=="function"?i(Ya()):i;if(!Ge(this.getSelectedFields(),s.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:e,isAll:t,rightSelect:s}),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(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new O({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new O({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...ae(this.config.table)),this.config.joins)for(let i of this.config.joins)t.push(...ae(i.table));return new Proxy(new z(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new O({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Mt=class extends us{static[l]="PgSelect";_prepare(e){let{session:t,config:i,dialect:s,joinsNotNullableMap:n,authToken:o,cacheConfig:a,usedTables:m}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:f}=i;return A.startActiveSpan("drizzle.prepareQuery",()=>{let u=ie(f),h=t.prepareQuery(s.sqlToQuery(this.getSQL()),u,e,!0,void 0,{type:"select",tables:[...m]},a);return h.joinsNotNullableMap=n,h.setToken(o)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};dn(Mt,[M]);function je(r,e){return(t,i,...s)=>{let n=[i,...s].map(o=>({type:r,isAll:e,rightSelect:o}));for(let o of n)if(!Ge(t.getSelectedFields(),o.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(n)}}var Ya=()=>({union:Ga,unionAll:Za,intersect:Xa,intersectAll:el,except:tl,exceptAll:rl}),Ga=je("union",!1),Za=je("union",!0),Xa=je("intersect",!1),el=je("intersect",!0),tl=je("except",!1),rl=je("except",!0);var ze=class{static[l]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=d(e,_e)?e:void 0,this.dialectConfig=d(e,_e)?void 0:e}$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new qe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function i(o){return new W({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function s(o){return new W({fields:o??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function n(o,a){return new W({fields:a??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:o}})}return{select:i,selectDistinct:s,selectDistinctOn:n}}select(e){return new W({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new W({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new W({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||(this.dialect=new _e(this.dialectConfig)),this.dialect}};function ae(r){return d(r,B)?[r[ve]?`${r[ve]}.${r[y.Symbol.BaseName]}`:r[y.Symbol.BaseName]]:d(r,z)?r._.usedTables??[]:d(r,b)?r.usedTables??[]:[]}var ut=class extends M{constructor(e,t,i,s){super(),this.session=t,this.dialect=i,this.config={table:e,withList:s}}static[l]="PgDelete";config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ie(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"delete",tables:ae(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var mt=class{constructor(e,t,i,s,n){this.table=e,this.session=t,this.dialect=i,this.withList=s,this.overridingSystemValue_=n}static[l]="PgInsertBuilder";authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let t=e.map(i=>{let s={},n=this.table[y.Symbol.Columns];for(let o of Object.keys(i)){let a=i[o];s[o]=d(a,b)?a:new X(a,n[o])}return s});return new Wt(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e=="function"?e(new ze):e;if(!d(t,b)&&!Ge(this.table[qt],t._.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 Wt(this.table,t,this.session,this.dialect,this.withList,!0)}},Wt=class extends M{constructor(e,t,i,s,n,o,a){super(),this.session=i,this.dialect=s,this.config={table:e,values:t,withList:n,select:o,overridingSystemValue_:a}}static[l]="PgInsert";config;cacheConfig;returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ie(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=c`do nothing`;else{let t="";t=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let i=e.where?c` where ${e.where}`:void 0;this.config.onConflict=c`(${c.raw(t)})${i} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.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 t=e.where?c` where ${e.where}`:void 0,i=e.targetWhere?c` where ${e.targetWhere}`:void 0,s=e.setWhere?c` where ${e.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,zt(this.config.table,e.set)),o="";return o=Array.isArray(e.target)?e.target.map(a=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(a))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=c`(${c.raw(o)})${i} do update set ${n}${t}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ae(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Ut=class extends M{constructor(e,t,i){super(),this.session=t,this.dialect=i,this.config={view:e}}static[l]="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:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};var ft=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s}static[l]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new ms(this.table,zt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},ms=class extends M{constructor(e,t,i,s,n){super(),this.session=i,this.dialect=s,this.config={set:t,table:e,withList:n,joins:[]},this.tableName=ge(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}static[l]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,i=ge(t);return typeof i=="string"&&(this.joinsNotNullableMap[i]=!0),this.config.from=t,this}getTableLikeFields(e){return d(e,B)?e[y.Symbol.Columns]:d(e,z)?e._.selectedFields:e[F].selectedFields}createJoin(e){return(t,i)=>{let s=ge(t);if(typeof s=="string"&&this.config.joins.some(n=>n.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){let n=this.config.from&&!d(this.config.from,b)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[y.Symbol.Columns],new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:i,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[y.Symbol.Columns]),this.config.from)){let t=ge(this.config.from);if(typeof t=="string"&&this.config.from&&!d(this.config.from,b)){let i=this.getTableLikeFields(this.config.from);e[t]=i}for(let i of this.config.joins){let s=ge(i.table);if(typeof s=="string"&&!d(i.table,b)){let n=this.getTableLikeFields(i.table);e[s]=n}}}return this.config.returningFields=e,this.config.returning=ie(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ae(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Jt=class r extends b{constructor(e){super(r.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=r.buildCount(e.source,e.filters)}sql;token;static[l]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(e,t){return c`(select count(*) from ${e}${c.raw(" where ").if(t)}${t})`}static buildCount(e,t){return c`select count(*) as count from ${e}${c.raw(" where ").if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};var Ht=class{constructor(e,t,i,s,n,o,a){this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a}static[l]="PgRelationalQueryBuilder";findMany(e){return new Yt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new Yt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Yt=class extends M{constructor(e,t,i,s,n,o,a,m,f){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a,this.config=m,this.mode=f}static[l]="PgRelationalQuery";_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>{let{query:t,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,!0,(s,n)=>{let o=s.map(a=>Bt(this.schema,this.tableConfig,a,t.selection,n));return this.mode==="first"?o[0]:o})})}prepare(e){return this._prepare(e)}_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 e=this._getQuery(),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}};var Gt=class extends M{constructor(e,t,i,s){super(),this.execute=e,this.sql=t,this.query=i,this.mapBatchResult=s}static[l]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Oe=class{constructor(e,t,i){if(this.dialect=e,this.session=t,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[s,n]of Object.entries(this._.schema))this.query[s]=new Ht(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[s],n,e,t);this.$cache={invalidate:async s=>{}}}static[l]="PgDatabase";query;$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(new ze(i.dialect))),new Proxy(new qe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new Jt({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function i(f){return new W({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e})}function s(f){return new W({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(f,u){return new W({fields:u??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:f}})}function o(f){return new ft(f,t.session,t.dialect,e)}function a(f){return new mt(f,t.session,t.dialect,e)}function m(f){return new ut(f,t.session,t.dialect,e)}return{select:i,selectDistinct:s,selectDistinctOn:n,update:o,insert:a,delete:m}}select(e){return new W({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new W({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new W({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new ft(e,this.session,this.dialect)}insert(e){return new mt(e,this.session,this.dialect)}delete(e){return new ut(e,this.session,this.dialect)}refreshMaterializedView(e){return new Ut(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e=="string"?c.raw(e):e.getSQL(),i=this.dialect.sqlToQuery(t),s=this.session.prepareQuery(i,void 0,void 0,!1);return new Gt(()=>s.execute(void 0,this.authToken),t,i,n=>s.mapResult(n,!0))}transaction(e,t){return this.session.transaction(e,t)}};var fs=class{static[l]="Cache"},Qe=class extends fs{strategy(){return"all"}static[l]="NoopCache";async get(e){}async put(e,t,i,s){}async onMutate(e){}};async function ds(r,e){let t=`${r}-${JSON.stringify(e)}`,s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s);return[...new Uint8Array(n)].map(m=>m.toString(16).padStart(2,"0")).join("")}var we=class r extends Error{constructor(e,t,i){super(`Failed query: ${e}
|
|
13
|
-
params: ${t}`),this.query=e,this.params=t,this.cause=i,Error.captureStackTrace(this,r),i&&(this.cause=i)}};var Zt=class{constructor(e,t,i,s){this.query=e,this.cache=t,this.queryMetadata=i,this.cacheConfig=s,t&&t.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[l]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,i){if(this.cache===void 0||d(this.cache,Qe)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new we(e,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new we(e,t,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new we(e,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new we(e,t,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await ds(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let n;try{n=await i()}catch(o){throw new we(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await ds(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return s}try{return await i()}catch(s){throw new we(e,t,s)}}},Xt=class{constructor(e){this.dialect=e}static[l]="PgSession";execute(e,t){return A.startActiveSpan("drizzle.operation",()=>A.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let i=await this.execute(e,t);return Number(i[0].count)}},er=class extends Oe{constructor(e,t,i,s=0){super(e,t,i),this.schema=i,this.nestedIndex=s}static[l]="PgTransaction";rollback(){throw new Lt}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable=="boolean"&&t.push(e.deferrable?"deferrable":"not deferrable"),c.raw(t.join(" "))}setTransaction(e){return this.session.execute(c`set transaction ${this.getTransactionConfigSQL(e)}`)}};var hs=class extends Zt{constructor(e,t,i,s,n,o,a,m,f,u){super({sql:t,params:i},n,o,a),this.client=e,this.queryString=t,this.params=i,this.logger=s,this.fields=m,this._isResponseInArrayMode=f,this.customResultMapper=u}static[l]="PostgresJsPreparedQuery";async execute(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i);let{fields:s,queryString:n,client:o,joinsNotNullableMap:a,customResultMapper:m}=this;if(!s&&!m)return A.startActiveSpan("drizzle.driver.execute",()=>this.queryWithCache(n,i,async()=>await o.unsafe(n,i)));let f=await A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(n,i,async()=>await o.unsafe(n,i).values())));return A.startActiveSpan("drizzle.mapResponse",()=>m?m(f):f.map(u=>fn(s,u,a)))})}all(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);return t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i),A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(this.queryString,i,async()=>this.client.unsafe(this.queryString,i))))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},dt=class r extends Xt{constructor(e,t,i,s={}){super(t),this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new jt,this.cache=s.cache??new Qe}static[l]="PostgresJsSession";logger;cache;prepareQuery(e,t,i,s,n,o,a){return new hs(this.client,e.sql,e.params,this.logger,this.cache,o,a,t,s,n)}query(e,t){return this.logger.logQuery(e,t),this.client.unsafe(e,t).values()}queryObjects(e,t){return this.client.unsafe(e,t)}transaction(e,t){return this.client.begin(async i=>{let s=new r(i,this.dialect,this.schema,this.options),n=new ps(this.dialect,s,this.schema);return t&&await n.setTransaction(t),e(n)})}},ps=class r extends er{constructor(e,t,i,s=0){super(e,t,i,s),this.session=t}static[l]="PostgresJsTransaction";transaction(e){return this.session.client.savepoint(t=>{let i=new dt(t,this.dialect,this.schema,this.session.options),s=new r(this.dialect,i,this.schema);return e(s)})}};var ys=class extends Oe{static[l]="PostgresJsDatabase"};function Re(r,e={}){let t=m=>m;for(let m of["1184","1082","1083","1114","1182","1185","1115","1231"])r.options.parsers[m]=t,r.options.serializers[m]=t;r.options.serializers[114]=t,r.options.serializers[3802]=t;let i=new _e({casing:e.casing}),s;e.logger===!0?s=new It:e.logger!==!1&&(s=e.logger);let n;if(e.schema){let m=xo(e.schema,No);n={fullSchema:e.schema,schema:m.tables,tableNamesMap:m.tableNamesMap}}let o=new dt(r,i,n,{logger:s,cache:e.cache}),a=new ys(i,o,n);return a.$client=r,a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}function tr(...r){if(typeof r[0]=="string"){let e=gs(r[0]);return Re(e,r[1])}if(pn(r[0])){let{connection:e,client:t,...i}=r[0];if(t)return Re(t,i);if(typeof e=="object"&&e.url!==void 0){let{url:n,...o}=e,a=gs(n,o);return Re(a,i)}let s=gs(e);return Re(s,i)}return Re(r[0],r[1])}(r=>{function e(t){return Re({options:{parsers:{},serializers:{}}},t)}r.mock=e})(tr||(tr={}));import{join as al}from"path";var U=V("core_roles",r=>({id:r.serial().primaryKey(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),root:r.boolean().notNull().default(!1),guest:r.boolean().notNull().default(!1),color:r.varchar({length:19})})).enableRLS();var me=V("core_languages",r=>({id:r.serial().primaryKey(),code:r.varchar({length:32}).notNull().unique(),name:r.varchar({length:255}).notNull(),timezone:r.varchar({length:255}).notNull().default("UTC"),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),enabled:r.boolean().notNull().default(!0),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),time24:r.boolean().notNull().default(!1)}),r=>[K("core_languages_code_idx").on(r.code),K("core_languages_name_idx").on(r.name)]).enableRLS(),rr=V("core_languages_words",r=>({id:r.serial().primaryKey(),languageCode:r.varchar().notNull().references(()=>me.code,{onDelete:"cascade"}),pluginCode:r.varchar({length:50}).notNull(),itemId:r.integer().notNull(),value:r.text().notNull(),tableName:r.varchar({length:255}).notNull(),variable:r.varchar({length:255}).notNull()}),r=>[K("core_languages_words_lang_code_idx").on(r.languageCode)]).enableRLS(),eg=Y(rr,({one:r})=>({language:r(me,{fields:[rr.languageCode],references:[me.code]})}));var D=V("core_users",r=>({id:r.serial().primaryKey(),nameCode:r.varchar({length:255}).notNull().unique(),name:r.varchar({length:255}).notNull().unique(),email:r.varchar({length:255}).notNull().unique(),password:r.varchar(),createdAt:r.timestamp().notNull().defaultNow(),newsletter:r.boolean().notNull().default(!1),avatarColor:r.varchar({length:6}).notNull(),emailVerified:r.boolean().notNull().default(!1),roleId:r.integer().references(()=>U.id).notNull(),birthday:r.timestamp(),ipAddress:r.varchar({length:40}).notNull(),language:r.varchar({length:32}).notNull().default("en").references(()=>me.code,{onDelete:"set default"})}),r=>[K("core_users_name_code_idx").on(r.nameCode),K("core_users_name_idx").on(r.name),K("core_users_email_idx").on(r.email)]).enableRLS(),og=Y(D,({one:r,many:e})=>({group:r(U,{fields:[D.roleId],references:[U.id]}),language:r(me,{fields:[D.language],references:[me.code]}),confirm_email:r(ir,{fields:[D.id],references:[ir.userId]}),sso:e(ws),forgot_password:r(sr,{fields:[D.id],references:[sr.userId]})})),ws=V("core_users_sso",r=>({userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),providerId:r.varchar({length:255}).notNull(),providerAccountId:r.varchar({length:255}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date)}),r=>[K("core_users_sso_user_id_idx").on(r.userId)]).enableRLS(),ag=Y(ws,({one:r})=>({user:r(D,{fields:[ws.userId],references:[D.id]})})),ir=V("core_users_confirm_emails",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),token:r.varchar({length:100}).notNull().unique(),createdAt:r.timestamp().notNull().defaultNow(),expires:r.timestamp().notNull()})).enableRLS(),lg=Y(ir,({one:r})=>({user:r(D,{fields:[ir.userId],references:[D.id]})})),sr=V("core_users_forgot_password",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull().unique(),token:r.varchar({length:100}).notNull().unique(),ip_address:r.varchar({length:40}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull()})).enableRLS(),cg=Y(sr,({one:r})=>({user:r(D,{fields:[sr.userId],references:[D.id]})}));var ht=V("core_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_sessions_user_id_idx").on(r.userId)]).enableRLS(),hg=Y(ht,({one:r})=>({user:r(D,{fields:[ht.userId],references:[D.id]}),device:r(be,{fields:[ht.deviceId],references:[be.id]})})),be=V("core_sessions_known_devices",r=>({id:r.serial().primaryKey(),ipAddress:r.varchar({length:40}).notNull(),userAgent:r.text().notNull(),lastSeen:r.timestamp().notNull().defaultNow()}),r=>[K("core_sessions_known_devices_ip_address_idx").on(r.ipAddress)]).enableRLS(),pg=Y(be,({one:r})=>({session:r(ht,{fields:[be.id],references:[ht.deviceId]})}));var pt=V("core_admin_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_admin_permissions_role_id_idx").on(r.roleId),K("core_admin_permissions_user_id_idx").on(r.userId)]).enableRLS(),_g=Y(pt,({one:r})=>({group:r(U,{fields:[pt.roleId],references:[U.id]}),user:r(D,{fields:[pt.userId],references:[D.id]})})),bs=V("core_admin_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),lastSeen:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_admin_sessions_token_idx").on(r.token),K("core_admin_sessions_user_id_idx").on(r.userId)]).enableRLS(),Ng=Y(bs,({one:r})=>({user:r(D,{fields:[bs.userId],references:[D.id]}),device:r(be,{fields:[bs.deviceId],references:[be.id]})}));var gt=V("core_moderators_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_moderators_permissions_role_id_idx").on(r.roleId),K("core_moderators_permissions_user_id_idx").on(r.userId)]).enableRLS(),Dg=Y(gt,({one:r})=>({group:r(U,{fields:[gt.roleId],references:[U.id]}),user:r(D,{fields:[gt.userId],references:[D.id]})}));import{existsSync as vo}from"fs";import{readFile as nl}from"fs/promises";import{join as fe,relative as Po}from"path";import{join as il}from"path";import{pathToFileURL as sl}from"url";var Co=async()=>{let r=il(process.cwd(),"src","vitnode.config.ts");try{return(await import(sl(r).href)).vitNodeConfig}catch(e){console.error("Failed to load config:",e),process.exit(1)}};var To=async()=>{let e=[...(await Co()).plugins.map(n=>n.pluginId),"vitnode"],t=$t(process.cwd()),i=Dt(t),s=Tt(i);await Promise.all(e.map(async n=>{let o=fe(process.cwd(),"node_modules",n),a="";try{let x=fe(o,"package.json");vo(x)&&(a=JSON.parse(await nl(x,"utf-8")).name??"")}catch(x){console.error(`\x1B[31mError reading package.json for ${n}:\x1B[0m`,x);return}let m=n.replace(/\//g,"-").replace(/@/g,""),f=fe(t,"apps","web","src","app","[locale]","(main)",fe("(plugins)",`(${m})`)),u=fe(t,"apps","web","src","app","[locale]","admin","(auth)",fe("(plugins)",`(${m})`)),h=fe(t,"apps","web","src","locales",n),p=[{sourceDir:fe(o,"src","app_admin"),destinationDir:u},{sourceDir:fe(o,"src","app"),destinationDir:f},{sourceDir:fe(o,"src","locales"),destinationDir:h}];for(let{sourceDir:x,destinationDir:_}of p)vo(x)&&!Me(x)&&(console.log(`\x1B[36mCopying ${n}:\x1B[0m ${Po(t,x)} \u2192 ${Po(t,_)}`),Ms(x,_,a,s,i,t,!1))}))};import{spawn as ol}from"child_process";var nr=async(r,e=[])=>new Promise((t,i)=>{let s=ol(r,e,{stdio:"inherit",shell:!0});s.on("error",n=>{i(n)}),s.on("close",n=>{n!==0?i(new Error(`Command failed with exit code ${n}`)):t(!0)})});$o.config({path:al(process.cwd(),"..","..",".env")});var $e=tr({connection:process.env.POSTGRES_URL??"postgresql://root:root@localhost:5432/vitnode",casing:"camelCase"}),ll=async()=>{try{await nr("npm",["run","drizzle-kit","up"]),await nr("npm",["run","drizzle-kit","generate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},cl=async()=>{try{await nr("npm",["run","drizzle-kit","migrate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},ul=async()=>{let[r]=await $e.select({count:as()}).from(U).limit(1),[e]=await $e.select({count:as()}).from(me);if(e.count===0&&await $e.insert(me).values([{code:"en",name:"English (USA)",default:!0,protected:!0,timezone:"America/New_York"}]),r.count===0){let t=await $e.insert(U).values([{protected:!0,guest:!0},{protected:!0,default:!0},{protected:!0,color:"hsl(122, 80%, 45%)"},{protected:!0,root:!0,color:"hsl(0, 100%, 50%)"}]).returning({id:U.id});await $e.insert(rr).values([{languageCode:"en",pluginCode:"core",itemId:t[0].id,value:"Guest",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[1].id,value:"Member",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[2].id,value:"Moderator",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[3].id,value:"Administrator",tableName:"core_roles",variable:"name"}]),await Promise.all([await $e.insert(gt).values({roleId:t[2].id,protected:!0}),await $e.insert(pt).values({roleId:t[3].id,protected:!0})])}},Do=async({initMessage:r})=>{console.log(`${r} [1/4] Prepare plugins files...`),await To(),console.log(`${r} [2/4] Generate migrations...`),await ll(),console.log(`${r} [3/4] Run migrations...`),await cl(),console.log(`
|
|
13
|
+
params: ${t}`),this.query=e,this.params=t,this.cause=i,Error.captureStackTrace(this,r),i&&(this.cause=i)}};var Zt=class{constructor(e,t,i,s){this.query=e,this.cache=t,this.queryMetadata=i,this.cacheConfig=s,t&&t.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[l]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,i){if(this.cache===void 0||d(this.cache,Qe)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new we(e,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new we(e,t,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new we(e,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new we(e,t,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await ds(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let n;try{n=await i()}catch(o){throw new we(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await ds(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return s}try{return await i()}catch(s){throw new we(e,t,s)}}},Xt=class{constructor(e){this.dialect=e}static[l]="PgSession";execute(e,t){return A.startActiveSpan("drizzle.operation",()=>A.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let i=await this.execute(e,t);return Number(i[0].count)}},er=class extends Oe{constructor(e,t,i,s=0){super(e,t,i),this.schema=i,this.nestedIndex=s}static[l]="PgTransaction";rollback(){throw new Lt}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable=="boolean"&&t.push(e.deferrable?"deferrable":"not deferrable"),c.raw(t.join(" "))}setTransaction(e){return this.session.execute(c`set transaction ${this.getTransactionConfigSQL(e)}`)}};var hs=class extends Zt{constructor(e,t,i,s,n,o,a,m,f,u){super({sql:t,params:i},n,o,a),this.client=e,this.queryString=t,this.params=i,this.logger=s,this.fields=m,this._isResponseInArrayMode=f,this.customResultMapper=u}static[l]="PostgresJsPreparedQuery";async execute(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i);let{fields:s,queryString:n,client:o,joinsNotNullableMap:a,customResultMapper:m}=this;if(!s&&!m)return A.startActiveSpan("drizzle.driver.execute",()=>this.queryWithCache(n,i,async()=>await o.unsafe(n,i)));let f=await A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(n,i,async()=>await o.unsafe(n,i).values())));return A.startActiveSpan("drizzle.mapResponse",()=>m?m(f):f.map(u=>fn(s,u,a)))})}all(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);return t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i),A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(this.queryString,i,async()=>this.client.unsafe(this.queryString,i))))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},dt=class r extends Xt{constructor(e,t,i,s={}){super(t),this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new jt,this.cache=s.cache??new Qe}static[l]="PostgresJsSession";logger;cache;prepareQuery(e,t,i,s,n,o,a){return new hs(this.client,e.sql,e.params,this.logger,this.cache,o,a,t,s,n)}query(e,t){return this.logger.logQuery(e,t),this.client.unsafe(e,t).values()}queryObjects(e,t){return this.client.unsafe(e,t)}transaction(e,t){return this.client.begin(async i=>{let s=new r(i,this.dialect,this.schema,this.options),n=new ps(this.dialect,s,this.schema);return t&&await n.setTransaction(t),e(n)})}},ps=class r extends er{constructor(e,t,i,s=0){super(e,t,i,s),this.session=t}static[l]="PostgresJsTransaction";transaction(e){return this.session.client.savepoint(t=>{let i=new dt(t,this.dialect,this.schema,this.session.options),s=new r(this.dialect,i,this.schema);return e(s)})}};var ys=class extends Oe{static[l]="PostgresJsDatabase"};function Re(r,e={}){let t=m=>m;for(let m of["1184","1082","1083","1114","1182","1185","1115","1231"])r.options.parsers[m]=t,r.options.serializers[m]=t;r.options.serializers[114]=t,r.options.serializers[3802]=t;let i=new _e({casing:e.casing}),s;e.logger===!0?s=new It:e.logger!==!1&&(s=e.logger);let n;if(e.schema){let m=xo(e.schema,No);n={fullSchema:e.schema,schema:m.tables,tableNamesMap:m.tableNamesMap}}let o=new dt(r,i,n,{logger:s,cache:e.cache}),a=new ys(i,o,n);return a.$client=r,a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}function tr(...r){if(typeof r[0]=="string"){let e=gs(r[0]);return Re(e,r[1])}if(pn(r[0])){let{connection:e,client:t,...i}=r[0];if(t)return Re(t,i);if(typeof e=="object"&&e.url!==void 0){let{url:n,...o}=e,a=gs(n,o);return Re(a,i)}let s=gs(e);return Re(s,i)}return Re(r[0],r[1])}(r=>{function e(t){return Re({options:{parsers:{},serializers:{}}},t)}r.mock=e})(tr||(tr={}));import{join as al}from"path";var U=V("core_roles",r=>({id:r.serial().primaryKey(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),root:r.boolean().notNull().default(!1),guest:r.boolean().notNull().default(!1),color:r.varchar({length:19})})).enableRLS();var me=V("core_languages",r=>({id:r.serial().primaryKey(),code:r.varchar({length:32}).notNull().unique(),name:r.varchar({length:255}).notNull(),timezone:r.varchar({length:255}).notNull().default("UTC"),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),enabled:r.boolean().notNull().default(!0),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),time24:r.boolean().notNull().default(!1)}),r=>[K("core_languages_code_idx").on(r.code),K("core_languages_name_idx").on(r.name)]).enableRLS(),rr=V("core_languages_words",r=>({id:r.serial().primaryKey(),languageCode:r.varchar().notNull().references(()=>me.code,{onDelete:"cascade"}),pluginCode:r.varchar({length:50}).notNull(),itemId:r.integer().notNull(),value:r.text().notNull(),tableName:r.varchar({length:255}).notNull(),variable:r.varchar({length:255}).notNull()}),r=>[K("core_languages_words_lang_code_idx").on(r.languageCode)]).enableRLS(),eg=Y(rr,({one:r})=>({language:r(me,{fields:[rr.languageCode],references:[me.code]})}));var D=V("core_users",r=>({id:r.serial().primaryKey(),nameCode:r.varchar({length:255}).notNull().unique(),name:r.varchar({length:255}).notNull().unique(),email:r.varchar({length:255}).notNull().unique(),password:r.varchar(),createdAt:r.timestamp().notNull().defaultNow(),newsletter:r.boolean().notNull().default(!1),avatarColor:r.varchar({length:6}).notNull(),emailVerified:r.boolean().notNull().default(!1),roleId:r.integer().references(()=>U.id).notNull(),birthday:r.timestamp(),ipAddress:r.varchar({length:40}).notNull(),language:r.varchar({length:32}).notNull().default("en").references(()=>me.code,{onDelete:"set default"})}),r=>[K("core_users_name_code_idx").on(r.nameCode),K("core_users_name_idx").on(r.name),K("core_users_email_idx").on(r.email)]).enableRLS(),og=Y(D,({one:r,many:e})=>({group:r(U,{fields:[D.roleId],references:[U.id]}),language:r(me,{fields:[D.language],references:[me.code]}),confirm_email:r(ir,{fields:[D.id],references:[ir.userId]}),sso:e(ws),forgot_password:r(sr,{fields:[D.id],references:[sr.userId]})})),ws=V("core_users_sso",r=>({userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),providerId:r.varchar({length:255}).notNull(),providerAccountId:r.varchar({length:255}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date)}),r=>[K("core_users_sso_user_id_idx").on(r.userId)]).enableRLS(),ag=Y(ws,({one:r})=>({user:r(D,{fields:[ws.userId],references:[D.id]})})),ir=V("core_users_confirm_emails",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),token:r.varchar({length:100}).notNull().unique(),createdAt:r.timestamp().notNull().defaultNow(),expires:r.timestamp().notNull()})).enableRLS(),lg=Y(ir,({one:r})=>({user:r(D,{fields:[ir.userId],references:[D.id]})})),sr=V("core_users_forgot_password",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull().unique(),token:r.varchar({length:100}).notNull().unique(),ip_address:r.varchar({length:40}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull()})).enableRLS(),cg=Y(sr,({one:r})=>({user:r(D,{fields:[sr.userId],references:[D.id]})}));var ht=V("core_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_sessions_user_id_idx").on(r.userId)]).enableRLS(),hg=Y(ht,({one:r})=>({user:r(D,{fields:[ht.userId],references:[D.id]}),device:r(be,{fields:[ht.deviceId],references:[be.id]})})),be=V("core_sessions_known_devices",r=>({id:r.serial().primaryKey(),ipAddress:r.varchar({length:40}).notNull(),userAgent:r.text().notNull(),lastSeen:r.timestamp().notNull().defaultNow()}),r=>[K("core_sessions_known_devices_ip_address_idx").on(r.ipAddress)]).enableRLS(),pg=Y(be,({one:r})=>({session:r(ht,{fields:[be.id],references:[ht.deviceId]})}));var pt=V("core_admin_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_admin_permissions_role_id_idx").on(r.roleId),K("core_admin_permissions_user_id_idx").on(r.userId)]).enableRLS(),_g=Y(pt,({one:r})=>({group:r(U,{fields:[pt.roleId],references:[U.id]}),user:r(D,{fields:[pt.userId],references:[D.id]})})),bs=V("core_admin_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),lastSeen:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_admin_sessions_token_idx").on(r.token),K("core_admin_sessions_user_id_idx").on(r.userId)]).enableRLS(),Ng=Y(bs,({one:r})=>({user:r(D,{fields:[bs.userId],references:[D.id]}),device:r(be,{fields:[bs.deviceId],references:[be.id]})}));var gt=V("core_moderators_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_moderators_permissions_role_id_idx").on(r.roleId),K("core_moderators_permissions_user_id_idx").on(r.userId)]).enableRLS(),Dg=Y(gt,({one:r})=>({group:r(U,{fields:[gt.roleId],references:[U.id]}),user:r(D,{fields:[gt.userId],references:[D.id]})}));import{existsSync as vo}from"fs";import{readFile as nl}from"fs/promises";import{join as fe,relative as Po}from"path";import{join as il}from"path";import{pathToFileURL as sl}from"url";var Co=async()=>{let r=il(process.cwd(),"src","vitnode.config.ts");try{return(await import(sl(r).href)).vitNodeConfig}catch(e){console.error("Failed to load config:",e),process.exit(1)}};var To=async()=>{let e=[...(await Co()).plugins.map(n=>n.pluginId),"@vitnode/core"],t=$t(process.cwd()),i=Dt(t),s=Tt(i);await Promise.all(e.map(async n=>{let o=fe(process.cwd(),"node_modules",n),a="";try{let x=fe(o,"package.json");vo(x)&&(a=JSON.parse(await nl(x,"utf-8")).name??"")}catch(x){console.error(`\x1B[31mError reading package.json for ${n}:\x1B[0m`,x);return}let m=n.replace(/\//g,"-").replace(/@/g,""),f=fe(t,"apps","web","src","app","[locale]","(main)",fe("(plugins)",`(${m})`)),u=fe(t,"apps","web","src","app","[locale]","admin","(auth)",fe("(plugins)",`(${m})`)),h=fe(t,"apps","web","src","locales",n),p=[{sourceDir:fe(o,"src","app_admin"),destinationDir:u},{sourceDir:fe(o,"src","app"),destinationDir:f},{sourceDir:fe(o,"src","locales"),destinationDir:h}];for(let{sourceDir:x,destinationDir:_}of p)vo(x)&&!Me(x)&&(console.log(`\x1B[36mCopying ${n}:\x1B[0m ${Po(t,x)} \u2192 ${Po(t,_)}`),Ms(x,_,a,s,i,t,!1))}))};import{spawn as ol}from"child_process";var nr=async(r,e=[])=>new Promise((t,i)=>{let s=ol(r,e,{stdio:"inherit",shell:!0});s.on("error",n=>{i(n)}),s.on("close",n=>{n!==0?i(new Error(`Command failed with exit code ${n}`)):t(!0)})});$o.config({path:al(process.cwd(),"..","..",".env")});var $e=tr({connection:process.env.POSTGRES_URL??"postgresql://root:root@localhost:5432/vitnode",casing:"camelCase"}),ll=async()=>{try{await nr("npm",["run","drizzle-kit","up"]),await nr("npm",["run","drizzle-kit","generate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},cl=async()=>{try{await nr("npm",["run","drizzle-kit","migrate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},ul=async()=>{let[r]=await $e.select({count:as()}).from(U).limit(1),[e]=await $e.select({count:as()}).from(me);if(e.count===0&&await $e.insert(me).values([{code:"en",name:"English (USA)",default:!0,protected:!0,timezone:"America/New_York"}]),r.count===0){let t=await $e.insert(U).values([{protected:!0,guest:!0},{protected:!0,default:!0},{protected:!0,color:"hsl(122, 80%, 45%)"},{protected:!0,root:!0,color:"hsl(0, 100%, 50%)"}]).returning({id:U.id});await $e.insert(rr).values([{languageCode:"en",pluginCode:"core",itemId:t[0].id,value:"Guest",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[1].id,value:"Member",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[2].id,value:"Moderator",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[3].id,value:"Administrator",tableName:"core_roles",variable:"name"}]),await Promise.all([await $e.insert(gt).values({roleId:t[2].id,protected:!0}),await $e.insert(pt).values({roleId:t[3].id,protected:!0})])}},Do=async({initMessage:r})=>{console.log(`${r} [1/4] Prepare plugins files...`),await To(),console.log(`${r} [2/4] Generate migrations...`),await ll(),console.log(`${r} [3/4] Run migrations...`),await cl(),console.log(`
|
|
14
14
|
${r} [4/4] Insert initial data...`),await ul(),console.log(`${r} \x1B[32mDatabase prepared successfully.\x1B[0m`),process.exit(0)};var Ss="\x1B[34m[VitNode]\x1B[0m",Eo=process.argv[2],Ao=process.argv[3];switch(Eo){case"init":Do({initMessage:Ss});break;case"plugin":(Ao==="--w"||Ao==="--watch")&&Js({initMessage:Ss});break;default:console.log(`${Ss} \x1B[31mCommand not found: "${Eo??""}"\x1B[0m`),process.exit(1)}
|
|
15
15
|
/*! Bundled license information:
|
|
16
16
|
|