modelence 0.4.10 → 0.4.12
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/bin/modelence.js +3 -10
- package/dist/bin/modelence.js.map +1 -1
- package/dist/client.d.ts +18 -11
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/package-DF3VLPXG.js +3 -0
- package/dist/package-DF3VLPXG.js.map +1 -0
- package/dist/server.d.ts +42 -0
- package/dist/server.js +3 -3
- package/dist/server.js.map +1 -1
- package/package.json +2 -1
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-DN5SVAO2.js';import {a as a$3,b as b$1}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import at from'dotenv';import
|
|
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):void 0}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):void 0});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=void 0,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("./.modelence/build/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:"./.modelence/build/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():void 0,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{
|
|
1
|
+
import {a as a$2}from'./chunk-DN5SVAO2.js';import {a as a$3,b as b$1}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import at from'dotenv';import It from'http';import G from'express';import w,{z}from'zod';import pt 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 I(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 E=null;function de(t){E=Object.assign({},E,t);}function ue(){return E?.deploymentId}function pe(){return E?.appAlias}function me(){return E?.deploymentAlias}function fe(){return E?.telemetry?.serviceName}function S(){return !!E?.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}]},dt=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=dt++),t[n]===`
|
|
2
|
+
`?e.push({log:"",timestamp:null}):i.log+=t[n];}}async function ut(){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(()=>{ut(),we();},1e3);}var be=false,x=null,V=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=pe()??"unknown",i=me()??"unknown",r=ue()??"unknown",s=fe();x=pt.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:x,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});c.on("error",u=>{console.error("Elasticsearch Transport Error:",u);}),V=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(!x)throw new Error("startTransaction: Elastic APM is not initialized");let n=x.startTransaction(e,t);return o&&x.setCustomContext(o),n}function Ee(t){if(!S()){console.error(t);return}if(!x)throw new Error("captureError: Elastic APM is not initialized");x.captureError(t);}function K(){if(!V)throw new Error("Logger is not initialized");return V}var Se=new Map,D={authenticated:null,unauthenticated:null};function xe(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 H={};function Z(t,e){return b(),Oe(t),N("query",t,e)}function De(t,e){return b(),Oe(t),N("mutation",t,e)}function ve(t,e){return b(),Ie(t),N("query",t,e)}function Re(t,e){return b(),Ie(t),N("mutation",t,e)}function Oe(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Ie(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function N(t,e,o){if(b(),H[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??[];H[e]={type:t,name:e,handler:n,permissions:i};}async function Ae(t,e,o){b();let n=H[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(u){throw s.end("error"),u}return s.end(),c}var m=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),Et=z.object.bind(z),St=z.enum.bind(z),a={string:gt,number:yt,date:wt,boolean:bt,array:Ct,object:Et,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 v=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 v.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 v.updateOne({authToken:t},{$set:{userId:e}});}async function $e(t){await v.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 v.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 v.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ke=new m("_system.session",{stores:[v],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 Ue(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(u=>u.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 Je(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 qe(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 m("_system.user",{stores:[g],mutations:{signupWithPassword:Ue,loginWithPassword:Je,logout:qe}});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):void 0}function Ve(){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 He(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,u=await _t(r);try{let d=await Ae(c,r.body.args,u);s.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let R=d.flatten(),O=Object.entries(R.fieldErrors).map(([J,q])=>`${J}: ${(q??[]).join(", ")}`).join("; "),L=R.formErrors.join("; "),z=[O,L].filter(Boolean).join("; ");s.status(400).send(z);}else s.status(500).send(d instanceof Error?d.message:String(d));}}),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=It.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):void 0});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();I(t);}var U=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 U.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 U.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var et=new m("_system.migration",{stores:[U]});var kt=a$1.minutes(1),Nt=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 Ut(Nt);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 Ut(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),Ee(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=void 0,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 m("_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("./.modelence/build/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:"./.modelence/build/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(),Vt()];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 Vt(){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 Ht({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";oo().then(()=>{}).catch(()=>{});let c=[Be,ke,it,et],u=[...c,...t];Qt(c),Zt(t),xe(e,o);let d=Yt(u);ce(d??{});let j=Gt(u);if(s&&Xt(u),r){let{configs:O,deploymentId:L,appAlias:z,deploymentAlias:J,telemetry:q}=await Ze({configSchema:d,cronJobsMetadata:s?rt():void 0,stores:j});I(O),de({deploymentId:L,appAlias:z,deploymentAlias:J,telemetry:q});}else I(to());let R=A();if(R&&(await We(),eo(j)),s&&await Xe(i),R)for(let O of j)O.createIndexes();r&&(await Ce(),Ye()),s&&nt().catch(console.error),await He(n,{combinedModules:u});}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))ve(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Re(`${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=Ve();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}async function oo(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=await import('./package-DF3VLPXG.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:o.default.version})});}}
|
|
3
|
+
export{m as Module,f as Store,Z as createQuery,g as dbUsers,C as getConfig,a as schema,Ht as startApp};//# sourceMappingURL=server.js.map
|
|
4
4
|
//# sourceMappingURL=server.js.map
|