modelence 0.2.1 → 0.4.2

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/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import {a as a$2}from'./chunk-O2JTQHZP.js';import {a as a$1}from'./chunk-GDI7FXAT.js';import Xe from'dotenv';import _t from'http';import V from'express';import w,{z as z$1}from'zod';import it from'elastic-apm-node';import q from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import M from'process';import {ObjectId,MongoClient,ServerApiVersion}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import Ct from'bcrypt';import {createServer,defineConfig}from'vite';import Mt from'@vitejs/plugin-react';import H from'path';import Dt from'fs';import Ut from'os';function ot(){return typeof window!="object"}function b(){if(!ot())throw new Error("This function can only be called on the server")}var k={},z={},ee=false;function C(t){return z[t]?.value}function te(){if(!ee)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(z).filter(([t])=>k[t]?.isPublic))}function I(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!k[e]||(z[e]={key:e,type:o,value:n});}),ee=true;}function oe(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:r}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(n==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),k=t;}var x=null;function re(t){x=Object.assign({},x,t);}function se(){return x?.deploymentId}function ie(){return x?.appAlias}function ae(){return x?.deploymentAlias}function ce(){return x?.telemetry?.serviceName}function T(){return !!x?.telemetry?.isEnabled}function _(t,e){T()&&J().info(t,e);}function le(t,e){T()&&J().error(t,e);}var p={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},rt=1;function de({elasticCloudId:t,elasticApiKey:e}){let o=M.stdout.write,n=M.stderr.write;M.stdout.write=function(r,...s){return ue(r.toString(),p.stdout),o.call(M.stdout,r,...s)},M.stderr.write=function(r,...s){return ue(r.toString(),p.stderr),n.call(M.stderr,r,...s)},me();}function ue(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let r=e[e.length-1];r.timestamp||(r.timestamp=o,r.sequenceId=rt++),t[n]===`
2
- `?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function st(){let t=p.stdout.slice(0,-1);p.stdout=[p.stdout[p.stdout.length-1]];let e=p.stderr.slice(0,-1);p.stderr=[p.stderr[p.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{_(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{le(o,{timestamp:n,source:"console",sequenceId:r});});}function me(){setTimeout(()=>{st(),me();},1e3);}var pe=false,E=null,B=null,fe=async()=>{if(pe)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');pe=true,T()&&await ct();};async function ct(){let t=C("_system.elastic.apmEndpoint"),e=C("_system.elastic.cloudId"),o=C("_system.elastic.apiKey"),n=ie()??"unknown",r=ae()??"unknown",s=se()??"unknown",i=ce();E=it.start({serviceName:i,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:s,appAlias:n,deploymentAlias:r}});let c=new ElasticsearchTransport({apm:E,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});c.on("error",m=>{console.error("Elasticsearch Transport Error:",m);}),B=q.createLogger({level:"debug",defaultMeta:{serviceName:i},format:q.format.combine(q.format.json()),transports:[c]}),de({elasticCloudId:e,elasticApiKey:o});}function j(t,e,o){if(!T())return {end:()=>{}};if(!E)throw new Error("startTransaction: Elastic APM is not initialized");let n=E.startTransaction(e,t);return o&&E.setCustomContext(o),n}function he(t){if(!E)throw new Error("captureError: Elastic APM is not initialized");E.captureError(t);}function J(){if(!B)throw new Error("Logger is not initialized");return B}var ge=new Map,D={authenticated:null,unauthenticated:null};function ye(t,e){D.authenticated=e.authenticated,D.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ge.set(o,n);}function P(){return D.unauthenticated?[D.unauthenticated]:[]}function we(){return D.authenticated?[D.authenticated]:[]}function be(t,e){let o=e.find(n=>!lt(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function lt(t,e){for(let o of t){let n=ge.get(o);if(n&&n.permissions.includes(e))return true}return false}var F={};function K(t,e){return b(),Se(t),U("query",t,e)}function Ce(t,e){return b(),Se(t),U("mutation",t,e)}function xe(t,e){return b(),Te(t),U("query",t,e)}function Ee(t,e){return b(),Te(t),U("mutation",t,e)}function Se(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Te(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function U(t,e,o){if(b(),F[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];F[e]={type:t,name:e,handler:n,permissions:r};}async function Me(t,e,o){b();let n=F[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:s}=n,i=j("method",`method:${t}`,{type:r,args:e}),c;try{be(o.roles,n.permissions),c=await s(e,o);}catch(m){throw i.end("error"),m}return i.end(),c}var f=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:s=[],cronJobs:i={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=s,this.cronJobs=i,this.configSchema=c;}};var h=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}provision(e){this.collection||(this.collection=e.db().collection(this.name),this.indexes.length>0&&this.collection.createIndexes(this.indexes));}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o){return await this.requireCollection().updateMany(e,o)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}};var ut=z$1.string.bind(z$1),dt=z$1.number.bind(z$1),mt=z$1.date.bind(z$1),pt=z$1.boolean.bind(z$1),ft=z$1.array.bind(z$1),ht=z$1.object.bind(z$1),gt=z$1.enum.bind(z$1),a={string:ut,number:dt,date:mt,boolean:pt,array:ft,object:ht,enum:gt,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var R=new h("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function Re(t){let e=t?await R.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await wt()}async function Ie(t,e){await R.updateOne({authToken:t},{$set:{userId:e}});}async function Oe(t){await R.updateOne({authToken:t},{$set:{userId:null}});}async function wt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await R.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function bt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await R.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ve=new f("_system.session",{stores:[R],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:te()}},heartbeat:async function(t,{session:e}){e&&await bt(e);}}});async function _e(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),r=await g.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(r){let c=r.emails?.find(m=>m.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let s=await Ct.hash(n,10);return (await g.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:s}}})).insertedId}async function Ue(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),r=z$1.string().parse(t.password),s=await g.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),i=s?.authMethods?.password?.hash;if(!s||!i||!await Ct.compare(r,i))throw Pe();return await Ie(o.authToken,s._id),{user:{id:s._id,handle:s.handle}}}async function $e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await Oe(o.authToken);}function Pe(){return new Error("Incorrect email/password combination")}var g=new h("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});var Ne=new f("_system.user",{stores:[g],mutations:{signupWithPassword:_e,loginWithPassword:Ue,logout:$e}});async function Le(t){let e=await Re(t),o=e.userId?await g.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,r=n?we():P();return {user:n,session:e,roles:r}}async function ke(t,e){if(e){console.log("Starting Vite dev server...");let o=await createServer({...defineConfig(await It()),server:{middlewareMode:true},root:"./src/client"});t.use(o.middlewares),t.use("*",async(n,r)=>{try{r.sendFile("index.html",{root:"./src/client"});}catch(s){console.error("Error serving index.html:",s),r.status(500).send("Internal Server Error");}});}else t.use(V.static(".modelence/client")),t.get("*",(o,n)=>{n.sendFile("index.html",{root:".modelence/client"});});}async function It(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Dt.existsSync(H.join(t,n))),o=[Mt(),Ot()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:H.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":H.resolve(t,"src")}}}}function Ot(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}function ze(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([r,s])=>{o.setHeader(r,s);}),o.send(n.data);}catch(n){o.status(500).send(String(n));}}}var y=null;async function Je(){if(y)return y;let t=O();if(!t)throw new Error("MongoDB URI is not set");y=new MongoClient(t,{serverApi:{version:ServerApiVersion.v1,strict:true,deprecationErrors:true},maxPoolSize:20});try{return await y.connect(),await y.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),y}catch(e){throw console.error(e),y=null,e}}function O(){let t=C("_system.mongodbUri");return t?String(t):undefined}function qe(){return y}function jt(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:s}=n;Object.entries(s).forEach(([i,c])=>{t[i](r,ze(c));});}}async function Be({combinedModules:t}){let e=V(),o=process.env.NODE_ENV!=="production";e.use(V.json()),e.use(V.urlencoded({extended:true})),e.post("/api/_internal/method/:methodName",async(s,i)=>{let{methodName:c}=s.params,m=await Pt(s);try{let u=await Me(c,s.body.args,m);i.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let A=u.flatten(),$=Object.entries(A.fieldErrors).map(([et,tt])=>`${et}: ${(tt??[]).join(", ")}`).join("; "),N=A.formErrors.join("; "),L=[$,N].filter(Boolean).join("; ");i.status(400).send(L);}else i.status(500).send(u instanceof Error?u.message:String(u));}}),jt(e,t),await ke(e,o),process.on("unhandledRejection",(s,i)=>{console.error("Unhandled Promise Rejection:"),console.error(s instanceof Error?s.stack:s),console.error("Promise:",i);}),process.on("uncaughtException",s=>{console.error("Uncaught Exception:"),console.error(s.stack),console.trace("Full application stack:");});let n=_t.createServer(e),r=process.env.PORT||3e3;n.listen(r,()=>{_("Application started",{source:"app"}),console.log(`Application started on port ${r}`);});}async function Pt(t){let e=w.string().nullish().transform(s=>s??null).parse(t.body.authToken),o=w.object({screenWidth:w.number(),screenHeight:w.number(),windowWidth:w.number(),windowHeight:w.number(),pixelRatio:w.number(),orientation:w.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!O()){let{session:s,user:i,roles:c}=await Le(e);return {clientInfo:o,connectionInfo:n,session:s,user:i,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:P()}}async function Fe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(i=>({name:i.getName(),schema:i.getSchema(),collections:[i.getName()]})),s=await Z("/api/connect","POST",{hostname:Ut.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),s}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function Ke(){return await Z("/api/configs","GET")}async function We(){return await Z("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Z(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let s=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):undefined});if(!s.ok){let i=await s.text();try{let c=JSON.parse(i);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${i}`)}}return await s.json()}var Q=false,$t=a$1.seconds(10);function He(){setInterval(async()=>{if(!Q){Q=true;try{await We();}catch(t){console.error("Error syncing status",t);}try{await Nt();}catch(t){console.error("Error syncing config",t);}Q=false;}},$t);}async function Nt(){let{configs:t}=await Ke();I(t);}var Lt=a$1.minutes(1),kt=a$1.seconds(10),S={},G,v=new h("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ze(t,{description:e="",interval:o,timeout:n=Lt,handler:r}){if(S[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(G)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);S[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Qe(){if(G)throw new Error("Cron jobs already started");let e={alias:{$in:Object.keys(S)}},o=await v.findOne({...e,"lock.containerId":{$exists:true}});await v.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await zt(kt);let n=await v.fetch(e),r=Date.now();n.forEach(s=>{let i=S[s.alias];i&&(i.state.scheduledRunTs=s.lastStartDate?s.lastStartDate.getTime()+i.params.interval:r);}),Object.values(S).forEach(s=>{s.state.scheduledRunTs||(s.state.scheduledRunTs=r);}),G=setInterval(Jt,a$1.seconds(1));}function zt(t){return new Promise(e=>setTimeout(e,t))}async function Jt(){let t=Date.now();Object.values(S).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await qt(e);});}async function qt(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now();let s=j("cron",`cron:${e}`);n().then(()=>{Ve(r,o),s.end("success");}).catch(i=>{Ve(r,o),he(i),s.end("error"),console.error(`Error in cron job '${e}':`,i);}),await v.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function Ve(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=undefined,t.isRunning=false;}function Ge(){return Object.values(S).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ye=new f("_system.cron",{stores:[v]});async function Bt({modules:t=[],roles:e={},defaultRoles:o={}}={}){Xe.config(),Xe.config({path:".modelence.env"});let n=!!process.env.MODELENCE_SERVICE_ENDPOINT,r=process.env.MODELENCE_CRON_ENABLED==="true",s=[Ne,ve,Ye],i=[...s,...t];Kt(s),Ft(t),ye(e,o);let c=Ht(i);oe(c??{});let m=Wt(i);if(r&&Vt(i),n){let{configs:Y,deploymentId:A,appAlias:$,deploymentAlias:N,telemetry:L}=await Fe({configSchema:c,cronJobsMetadata:r?Ge():undefined,stores:m});I(Y),re({deploymentId:A,appAlias:$,deploymentAlias:N,telemetry:L});}else I(Qt());O()&&(await Je(),Zt(m)),n&&(await fe(),He()),r&&Qe().catch(console.error),await Be({combinedModules:i});}function Ft(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))K(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ce(`${e.name}.${o}`,n);}}function Kt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ee(`${e.name}.${o}`,n);}}function Wt(t){return t.flatMap(e=>e.stores)}function Ht(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let s=`${o.name}.${n}`;if(s in e)throw new Error(`Duplicate config schema key: ${s} (${o.name})`);e[s]=r;}return e}function Vt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ze(`${e.name}.${o}`,n);}async function Zt(t){let e=qe();if(!e)throw new Error("Failed to provision stores: MongoDB client not initialized");for(let o of t)o.provision(e);}function Qt(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}
3
- export{f as Module,h as Store,K as createQuery,g as dbUsers,C as getConfig,a as schema,Bt as startApp};//# sourceMappingURL=server.js.map
1
+ import {a as a$2}from'./chunk-O2JTQHZP.js';import {a as a$3,b as b$1}from'./chunk-D5LNOX64.js';import {a as a$1}from'./chunk-GDI7FXAT.js';import at from'dotenv';import Ot from'http';import G from'express';import w,{z}from'zod';import mt from'elastic-apm-node';import W from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import T from'process';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import Dt from'bcrypt';import jt from'os';import {createServer,defineConfig}from'vite';import Bt from'@vitejs/plugin-react';import te from'path';import Ft from'fs';function ct(){return typeof window!="object"}function b(){if(!ct())throw new Error("This function can only be called on the server")}var B={},F={},se=false;function C(t){return F[t]?.value}function ae(){if(!se)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(F).filter(([t])=>B[t]?.isPublic))}function O(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!B[e]||(F[e]={key:e,type:o,value:n});}),se=true;}function ce(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:i}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(n==="secret"&&i)throw new Error(`Config ${e} with type "secret" cannot be public`)}),B=t;}var x=null;function ue(t){x=Object.assign({},x,t);}function de(){return x?.deploymentId}function me(){return x?.appAlias}function pe(){return x?.deploymentAlias}function fe(){return x?.telemetry?.serviceName}function S(){return !!x?.telemetry?.isEnabled}function P(t,e){S()&&K().info(t,e);}function he(t,e){S()&&K().error(t,e);}var h={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},ut=1;function ye({elasticCloudId:t,elasticApiKey:e}){let o=T.stdout.write,n=T.stderr.write;T.stdout.write=function(i,...r){return ge(i.toString(),h.stdout),o.call(T.stdout,i,...r)},T.stderr.write=function(i,...r){return ge(i.toString(),h.stderr),n.call(T.stderr,i,...r)},we();}function ge(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let i=e[e.length-1];i.timestamp||(i.timestamp=o,i.sequenceId=ut++),t[n]===`
2
+ `?e.push({log:"",timestamp:null}):i.log+=t[n];}}async function dt(){let t=h.stdout.slice(0,-1);h.stdout=[h.stdout[h.stdout.length-1]];let e=h.stderr.slice(0,-1);h.stderr=[h.stderr[h.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:i})=>{P(o,{timestamp:n,source:"console",sequenceId:i});}),e.forEach(({log:o,timestamp:n,sequenceId:i})=>{he(o,{timestamp:n,source:"console",sequenceId:i});});}function we(){setTimeout(()=>{dt(),we();},1e3);}var be=false,E=null,H=null,Ce=async()=>{if(be)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');be=true,S()&&await ft();};async function ft(){let t=C("_system.elastic.apmEndpoint"),e=C("_system.elastic.cloudId"),o=C("_system.elastic.apiKey"),n=me()??"unknown",i=pe()??"unknown",r=de()??"unknown",s=fe();E=mt.start({serviceName:s,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:r,appAlias:n,deploymentAlias:i}});let c=new ElasticsearchTransport({apm:E,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});c.on("error",d=>{console.error("Elasticsearch Transport Error:",d);}),H=W.createLogger({level:"debug",defaultMeta:{serviceName:s},format:W.format.combine(W.format.json()),transports:[c]}),ye({elasticCloudId:e,elasticApiKey:o});}function $(t,e,o){if(!S())return {end:()=>{}};if(!E)throw new Error("startTransaction: Elastic APM is not initialized");let n=E.startTransaction(e,t);return o&&E.setCustomContext(o),n}function xe(t){if(!S()){console.error(t);return}if(!E)throw new Error("captureError: Elastic APM is not initialized");E.captureError(t);}function K(){if(!H)throw new Error("Logger is not initialized");return H}var Se=new Map,D={authenticated:null,unauthenticated:null};function Ee(t,e){D.authenticated=e.authenticated,D.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Se.set(o,n);}function k(){return D.unauthenticated?[D.unauthenticated]:[]}function Me(){return D.authenticated?[D.authenticated]:[]}function Te(t,e){let o=e.find(n=>!ht(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function ht(t,e){for(let o of t){let n=Se.get(o);if(n&&n.permissions.includes(e))return true}return false}var V={};function Z(t,e){return b(),Ie(t),U("query",t,e)}function De(t,e){return b(),Ie(t),U("mutation",t,e)}function Re(t,e){return b(),Oe(t),U("query",t,e)}function ve(t,e){return b(),Oe(t),U("mutation",t,e)}function Ie(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Oe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function U(t,e,o){if(b(),V[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];V[e]={type:t,name:e,handler:n,permissions:i};}async function Ae(t,e,o){b();let n=V[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=$("method",`method:${t}`,{type:i,args:e}),c;try{Te(o.roles,n.permissions),c=await r(e,o);}catch(d){throw s.end("error"),d}return s.end(),c}var p=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var gt=z.string.bind(z),yt=z.number.bind(z),wt=z.date.bind(z),bt=z.boolean.bind(z),Ct=z.array.bind(z),xt=z.object.bind(z),St=z.enum.bind(z),a={string:gt,number:yt,date:wt,boolean:bt,array:Ct,object:xt,enum:St,objectId(){return z.instanceof(ObjectId)},userId(){return z.instanceof(ObjectId)},ref(t){return z.instanceof(ObjectId)},union:z.union.bind(z),infer(t){return {}}};var R=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await R.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Mt()}async function Pe(t,e){await R.updateOne({authToken:t},{$set:{userId:e}});}async function $e(t){await R.updateOne({authToken:t},{$set:{userId:null}});}async function Mt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await R.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function Tt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await R.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ke=new p("_system.session",{stores:[R],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:ae()}},heartbeat:async function(t,{session:e}){e&&await Tt(e);}}});async function Ne(t,{user:e}){let o=z.string().email().parse(t.email),n=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await g.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(d=>d.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await Dt.hash(n,10);return (await g.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function qe(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z.string().email().parse(t.email),i=z.string().parse(t.password),r=await g.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await Dt.compare(i,s))throw ze();return await Pe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Je(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await $e(o.authToken);}function ze(){return new Error("Incorrect email/password combination")}var g=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});var Be=new p("_system.user",{stores:[g],mutations:{signupWithPassword:Ne,loginWithPassword:qe,logout:Je}});async function Fe(t){let e=await je(t),o=e.userId?await g.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?Me():k();return {user:n,session:e,roles:i}}function Ke(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$3||n instanceof b$1?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var y=null;async function We(){if(y)return y;let t=A();if(!t)throw new Error("MongoDB URI is not set");y=new MongoClient(t,{maxPoolSize:20});try{return await y.connect(),await y.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),y}catch(e){throw console.error(e),y=null,e}}function A(){let t=C("_system.mongodbUri");return t?String(t):undefined}function He(){return y}function At(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,Ke(c));});}}async function Ve(t,{combinedModules:e}){let o=G();o.use(G.json()),o.use(G.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,d=await _t(r);try{let u=await Ae(c,r.body.args,d);s.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let v=u.flatten(),I=Object.entries(v.fieldErrors).map(([q,J])=>`${q}: ${(J??[]).join(", ")}`).join("; "),L=v.formErrors.join("; "),z=[I,L].filter(Boolean).join("; ");s.status(400).send(z);}else s.status(500).send(u instanceof Error?u.message:String(u));}}),At(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=Ot.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{P("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function _t(t){let e=w.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=w.object({screenWidth:w.number(),screenHeight:w.number(),windowWidth:w.number(),windowHeight:w.number(),pixelRatio:w.number(),orientation:w.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!A()){let{session:r,user:s,roles:c}=await Fe(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:k()}}async function Ze({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await Y("/api/connect","POST",{hostname:jt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Qe(){return await Y("/api/configs","GET")}async function Ge(){return await Y("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Y(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):undefined});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var X=false,Pt=a$1.seconds(10);function Ye(){setInterval(async()=>{if(!X){X=true;try{await Ge();}catch(t){console.error("Error syncing status",t);}try{await $t();}catch(t){console.error("Error syncing config",t);}X=false;}},Pt);}async function $t(){let{configs:t}=await Qe();O(t);}var N=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function Xe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await N.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await N.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var et=new p("_system.migration",{stores:[N]});var kt=a$1.minutes(1),Ut=a$1.seconds(10),M={},ee,_=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function ot(t,{description:e="",interval:o,timeout:n=kt,handler:i}){if(M[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ee)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);M[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function nt(){if(ee)throw new Error("Cron jobs already started");let t=Object.keys(M);if(t.length>0){let e={alias:{$in:t}},o=await _.findOne({...e,"lock.containerId":{$exists:true}});await _.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await Nt(Ut);let n=await _.fetch(e),i=Date.now();n.forEach(r=>{let s=M[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(M).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),ee=setInterval(Lt,a$1.seconds(1));}}function Nt(t){return new Promise(e=>setTimeout(e,t))}async function Lt(){let t=Date.now();Object.values(M).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await zt(e);});}async function zt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=$("cron",`cron:${e}`);n().then(()=>{tt(i,o),r.end("success");}).catch(s=>{tt(i,o),xe(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await _.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function tt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=undefined,t.isRunning=false;}function rt(){return Object.values(M).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var it=new p("_system.cron",{stores:[_]});var oe=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await Wt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[G.static("./client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Wt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Ft.existsSync(te.join(t,n))),o=[Bt(),Ht()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:te.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":te.resolve(t,"src")}}}}function Ht(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var st=new oe;async function Vt({modules:t=[],roles:e={},defaultRoles:o={},server:n=st,migrations:i=[]}){at.config(),at.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true",c=[Be,ke,it,et],d=[...c,...t];Qt(c),Zt(t),Ee(e,o);let u=Yt(d);ce(u??{});let j=Gt(d);if(s&&Xt(d),r){let{configs:I,deploymentId:L,appAlias:z,deploymentAlias:q,telemetry:J}=await Ze({configSchema:u,cronJobsMetadata:s?rt():undefined,stores:j});O(I),ue({deploymentId:L,appAlias:z,deploymentAlias:q,telemetry:J});}else O(to());let v=A();if(v&&(await We(),eo(j)),s&&await Xe(i),v)for(let I of j)I.createIndexes();r&&(await Ce(),Ye()),s&&nt().catch(console.error),await Ve(n,{combinedModules:d});}function Zt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Z(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))De(`${e.name}.${o}`,n);}}function Qt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Re(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ve(`${e.name}.${o}`,n);}}function Gt(t){return t.flatMap(e=>e.stores)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))ot(`${e.name}.${o}`,n);}function eo(t){let e=He();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function to(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}
3
+ export{p as Module,f as Store,Z as createQuery,g as dbUsers,C as getConfig,a as schema,Vt as startApp};//# sourceMappingURL=server.js.map
4
4
  //# sourceMappingURL=server.js.map