modelence 0.6.17-dev.4 → 0.6.18

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,18 +1,18 @@
1
- import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$1,c as c$1,f,g as g$1,i,a as a$1,h,j as j$1,k}from'./chunk-LQOYD6LG.js';export{a as getConfig}from'./chunk-LQOYD6LG.js';import Pt from'dotenv';import Ho from'fs/promises';import ho from'os';import we from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import T,{z as z$1}from'zod';import ro from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import _o from'@vitejs/plugin-react';import Ro from'fs';import Se,{Router}from'express';import Wo from'cookie-parser';import Bo from'http';var b=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:d=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=d;}};function S(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:S(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=S(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...S(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...S(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(S)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:S(o.schema)}return {type:"custom",typeName:e.typeName}}function J(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?S(r):J(r)):typeof n=="object"&&"_def"in n?e[o]=S(n):e[o]=J(n);return e}var w=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return J(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}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(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}: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 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),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}countDocuments(e){return this.requireCollection().countDocuments(e)}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){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(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);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Lt=z$1.string.bind(z$1),$t=z$1.number.bind(z$1),zt=z$1.date.bind(z$1),Zt=z$1.boolean.bind(z$1),qt=z$1.array.bind(z$1),Wt=z$1.object.bind(z$1),Bt=z$1.enum.bind(z$1),c={string:Lt,number:$t,date:zt,boolean:Zt,array:qt,object:Wt,enum:Bt,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(t){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(t){return {}}};var A=new w("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await A.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ce()}async function Ue(t,e){await A.updateOne({authToken:t},{$set:{userId:e}});}async function Ne(t){await A.updateOne({authToken:t},{$set:{userId:null}});}async function ce(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await A.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Jt(t){let e=Date.now(),o=new Date(e+a.days(7));await A.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Le=new b("_system.session",{stores:[A],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await Jt(e);}}});var p=new w("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),createdAt:c.date(),roles:c.array(c.string()).optional(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional(),github:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),z=new w("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),P=new w("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new w("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var $e=new Map,j={authenticated:null,unauthenticated:null};function ze(t,e){j.authenticated=e.authenticated,j.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))$e.set(o,n);}function H(){return j.unauthenticated?[j.unauthenticated]:[]}function Ze(){return j.authenticated?[j.authenticated]:[]}function qe(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=$e.get(o);if(n&&n.permissions.includes(e))return true}return false}async function D(t){let e=await je(t),o=e.userId?await p.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Ze():H();return {user:n,session:e,roles:r}}var x=null;async function We(){if(x)return x;let t=_();if(!t)throw new Error("MongoDB URI is not set");x=new MongoClient(t,{maxPoolSize:20});try{return await x.connect(),await x.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),x}catch(e){throw console.error(e),x=null,e}}function _(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function V(){return x}var Z=null,Yt="_modelenceSocketio";async function Xt({httpServer:t,channels:e}){let o=V();console.log("Initializing Socket.IO server...");let n=null;if(o){n=o.db().collection(Yt);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}}Z=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),Z.on("error",r=>{console.error("Socket.IO error:",r);}),Z.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await D(s);}finally{i();}}),Z.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),r.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(r.data))&&r.join(i);r.join(i),console.log(`User ${r.id} joined channel ${i}`),r.emit("joinedChannel",i);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function eo({category:t,id:e,data:o}){Z?.to(`${t}:${e}`).emit(t,o);}var Be={init:Xt,broadcast:eo};async function Fe(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await z.findOne({domain:o})}var Je={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
- `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await z.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var le=Object.freeze({});function He(t){le=Object.freeze(Object.assign({},le,t));}function y(){return le}function to(){return typeof window!="object"}function R(){if(!to())throw new Error("This function can only be called on the server")}function G(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function Ve({name:t,email:e,verificationUrl:o}){return `
1
+ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$1,c as c$1,f,g as g$1,j as j$1,a as a$1,i,k as k$1,h,l}from'./chunk-EY7KRL57.js';export{a as getConfig}from'./chunk-EY7KRL57.js';import Zt from'dotenv';import nn from'fs/promises';import To from'os';import Te from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes,randomUUID}from'crypto';import _,{z}from'zod';import fo from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import jo from'@vitejs/plugin-react';import No from'fs';import ke,{Router}from'express';import Xo from'cookie-parser';import en from'http';var b=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:d=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=d;}};function T(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:T(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=T(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...T(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...T(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(T)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:T(o.schema)}return {type:"custom",typeName:e.typeName}}function K(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?T(r):K(r)):typeof n=="object"&&"_def"in n?e[o]=T(n):e[o]=K(n);return e}var y=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return K(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}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(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}: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 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),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}countDocuments(e){return this.requireCollection().countDocuments(e)}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){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(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);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Ht=z.string.bind(z),Vt=z.number.bind(z),Gt=z.date.bind(z),Kt=z.boolean.bind(z),Qt=z.array.bind(z),Yt=z.object.bind(z),Xt=z.enum.bind(z),c={string:Ht,number:Vt,date:Gt,boolean:Kt,array:Qt,object:Yt,enum:Xt,embedding(){return z.array(z.number())},objectId(){return z.instanceof(ObjectId).describe("ObjectId")},userId(){return z.instanceof(ObjectId).describe("UserId")},ref(t){return z.instanceof(ObjectId).describe("Ref")},union:z.union.bind(z),infer(t){return {}}};var U=new y("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function ze(t){let e=t?await U.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await me()}async function qe(t,e){await U.updateOne({authToken:t},{$set:{userId:e}});}async function Ze(t){await U.updateOne({authToken:t},{$set:{userId:null}});}async function me(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await U.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function to(t){let e=Date.now(),o=new Date(e+a.days(7));await U.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var We=new b("_system.session",{stores:[U],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await to(e);}}});var p=new y("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),status:c.enum(["active","disabled","deleted"]).optional(),createdAt:c.date(),disabledAt:c.date().optional(),deletedAt:c.date().optional(),roles:c.array(c.string()).optional(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional(),github:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"authMethods.google.id":1,status:1},sparse:true},{key:{"authMethods.github.id":1,status:1},sparse:true}]}),W=new y("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),v=new y("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),C=new y("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Fe=new Map,L={authenticated:null,unauthenticated:null};function Be(t,e){L.authenticated=e.authenticated,L.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Fe.set(o,n);}function Q(){return L.unauthenticated?[L.unauthenticated]:[]}function Je(){return L.authenticated?[L.authenticated]:[]}function He(t,e){let o=e.find(n=>!oo(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function oo(t,e){for(let o of t){let n=Fe.get(o);if(n&&n.permissions.includes(e))return true}return false}async function k(t){let e=await ze(t),o=e.userId?await p.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Je():Q();return {user:n,session:e,roles:r}}var D=null;async function Ve(){if(D)return D;let t=R();if(!t)throw new Error("MongoDB URI is not set");D=new MongoClient(t,{maxPoolSize:20});try{return await D.connect(),await D.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),D}catch(e){throw console.error(e),D=null,e}}function R(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function Y(){return D}var F=null,ao="_modelenceSocketio";async function co({httpServer:t,channels:e}){let o=Y();console.log("Initializing Socket.IO server...");let n=null;if(o){n=o.db().collection(ao);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}}F=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),F.on("error",r=>{console.error("Socket.IO error:",r);}),F.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await k(s);}finally{i();}}),F.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),r.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(r.data))&&r.join(i);r.join(i),console.log(`User ${r.id} joined channel ${i}`),r.emit("joinedChannel",i);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function lo({category:t,id:e,data:o}){F?.to(`${t}:${e}`).emit(t,o);}var Ge={init:co,broadcast:lo};async function Ke(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await W.findOne({domain:o})}var Qe={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await W.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var pe=Object.freeze({});function Ye(t){pe=Object.freeze(Object.assign({},pe,t));}function w(){return pe}function uo(){return typeof window!="object"}function O(){if(!uo())throw new Error("This function can only be called on the server")}function X(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function Xe({name:t,email:e,verificationUrl:o}){return `
3
3
  <p>Hi${t?` ${t}`:""},</p>
4
4
  <p>Please verify your email address ${e} by clicking the link below:</p>
5
5
  <p><a href="${o}">${o}</a></p>
6
6
  <p>If you did not request this, please ignore this email.</p>
7
- `}async function Ge(t){let e=process.env.MODELENCE_SITE_URL,o=y().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await P.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await p.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await p.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await p.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await P.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function K({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(y().provider){let n=y().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await P.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,l=(y()?.verification?.template||Ve)({name:"",email:e,verificationUrl:s}),d=G(l);await n?.sendEmail({to:e,from:y()?.from||"noreply@modelence.com",subject:y()?.verification?.subject||"Verify your email address",text:d,html:l});}}function Q(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function U(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var de=Object.freeze({});function Qe(t){de=Object.freeze(Object.assign({},de,t));}function g(){return de}async function Xe(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await O({bucket:"signin",type:"ip",value:r});let i=U(t.email),s=z$1.string().parse(t.password),a=await p.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw Ye();if(!a.emails?.find(u=>u.address===i)?.verified&&y()?.provider){if(r)try{await O({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await K({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await ro.compare(s,l))throw Ye();return await Ue(o.authToken,a._id),g().onAfterLogin?.({user:a,session:o,connectionInfo:n}),g().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(g().onLoginError?.({error:r,session:o,connectionInfo:n}),g().login?.onError?.(r)),r}}async function et(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Ne(e.authToken);}function Ye(){return new Error("Incorrect email/password combination")}async function tt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await p.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var q=new w("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var ue=[];function ot(t){if(ue.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");ue=t;}async function O(t){let{bucket:e,type:o,value:n}=t,r=ue.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await so(i,n);}async function so(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),r=await q.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=r?ao(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await q.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function ao(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function nt(t,{user:e,session:o,connectionInfo:n}){try{let r=U(t.email),i=Q(t.password),s=n?.ip;if(s&&await O({bucket:"signupAttempt",type:"ip",value:s}),await Fe(r))throw new Error("Please use a permanent email address");let a=await p.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let u=a.emails?.find(C=>C.address===r);throw new Error(`User with email already exists: ${u?.address}`)}s&&await O({bucket:"signup",type:"ip",value:s});let l=await ro.hash(i,10),d=await p.insertOne({handle:r,emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),E=await p.findOne({_id:d.insertedId},{readPreference:"primary"});if(!E)throw new Error("User not found");return await K({userId:d?.insertedId,email:r,baseUrl:n?.baseUrl}),g().onAfterSignup?.({user:E,session:o,connectionInfo:n}),g().signup?.onSuccess?.(E),d.insertedId}catch(r){throw r instanceof Error&&(g().onSignupError?.({error:r,session:o,connectionInfo:n}),g().signup?.onError?.(r)),r}}function po(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function fo({email:t,resetUrl:e}){return `
7
+ `}async function et(t){let e=process.env.MODELENCE_SITE_URL,o=w().emailVerifiedRedirectUrl||e||"/";try{let n=z.string().parse(t.query.token),r=await v.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await p.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await p.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await p.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await v.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function ee({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(w().provider){let n=w().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await v.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,l=(w()?.verification?.template||Xe)({name:"",email:e,verificationUrl:s}),d=X(l);await n?.sendEmail({to:e,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:d,html:l});}}function te(t){return z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function j(t){return z.string().email({message:"Invalid email address"}).parse(t)}var fe=Object.freeze({});function ot(t){fe=Object.freeze(Object.assign({},fe,t));}function g(){return fe}async function rt(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await M({bucket:"signin",type:"ip",value:r});let i=j(t.email),s=z.string().parse(t.password),a=await p.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw nt();if(!a.emails?.find(u=>u.address===i)?.verified&&w()?.provider){if(r)try{await M({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await ee({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await fo.compare(s,l))throw nt();return await qe(o.authToken,a._id),g().onAfterLogin?.({user:a,session:o,connectionInfo:n}),g().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(g().onLoginError?.({error:r,session:o,connectionInfo:n}),g().login?.onError?.(r)),r}}async function it(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Ze(e.authToken);}function nt(){return new Error("Incorrect email/password combination")}async function st(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await p.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var B=new y("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var he=[];function at(t){if(he.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");he=t;}async function M(t){let{bucket:e,type:o,value:n}=t,r=he.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await go(i,n);}async function go(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),r=await B.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=r?yo(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await B.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function yo(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function ct(t,{user:e,session:o,connectionInfo:n}){try{let r=j(t.email),i=te(t.password),s=n?.ip;if(s&&await M({bucket:"signupAttempt",type:"ip",value:s}),await Ke(r))throw new Error("Please use a permanent email address");let a=await p.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let u=a.emails?.find(S=>S.address===r);throw a.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${u?.address}`)}s&&await M({bucket:"signup",type:"ip",value:s});let l=await fo.hash(i,10),d=await p.insertOne({handle:r,status:"active",emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),E=await p.findOne({_id:d.insertedId},{readPreference:"primary"});if(!E)throw new Error("User not found");return await ee({userId:d?.insertedId,email:r,baseUrl:n?.baseUrl}),g().onAfterSignup?.({user:E,session:o,connectionInfo:n}),g().signup?.onSuccess?.(E),d.insertedId}catch(r){throw r instanceof Error&&(g().onSignupError?.({error:r,session:o,connectionInfo:n}),g().signup?.onError?.(r)),r}}function So(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function xo({email:t,resetUrl:e}){return `
8
8
  <p>Hi,</p>
9
9
  <p>We received a request to reset your password for ${t}.</p>
10
10
  <p>Click the link below to reset your password:</p>
11
11
  <p><a href="${e}">${e}</a></p>
12
12
  <p>This link will expire in 1 hour.</p>
13
13
  <p>If you did not request this password reset, please ignore this email.</p>
14
- `}var me={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function rt(t,{connectionInfo:e}){let o=U(t.email),n=await p.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return me;let r=y().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await v.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,d=`${po(a$1,y().passwordReset?.redirectUrl)}?token=${i}`,u=(y()?.passwordReset?.template||fo)({email:o,resetUrl:d,name:""}),C=G(u);return await r.sendEmail({to:o,from:y()?.from||"noreply@modelence.com",subject:y()?.passwordReset?.subject||"Reset your password",text:C,html:u}),me}async function it(t,{}){let e=z$1.string().parse(t.token),o=Q(t.password),n=await v.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let r=await p.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await ro.hash(o,10);return await p.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var st=new b("_system.user",{stores:[p,z,P,v],queries:{getOwnProfile:tt},mutations:{signupWithPassword:nt,loginWithPassword:Xe,logout:et,sendResetPasswordToken:rt,resetPassword:it},cronJobs:{updateDisposableEmailList:Je},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Ge}}]});async function at({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(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await pe("/api/connect","POST",{hostname:ho.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function ct(){return await pe("/api/configs","GET")}async function lt(){return await pe("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function pe(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 i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var fe=false,go=a.seconds(10);function dt(){setInterval(async()=>{if(!fe){fe=true;try{await lt();}catch(t){console.error("Error syncing status",t);}try{await yo();}catch(t){console.error("Error syncing config",t);}fe=false;}},go);}async function yo(){let{configs:t}=await ct();c$1(t);}var wo=a.minutes(1),bo=a.seconds(10),I={},he,W=new w("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional(),lock:c.object({containerId:c.string(),acquireDate:c.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function mt(t,{description:e="",interval:o,timeout:n=wo,handler:r}){if(I[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(he)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);I[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function pt(){if(he)throw new Error("Cron jobs already started");let t=Object.keys(I);if(t.length>0){let e={alias:{$in:t}},o=await W.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>W.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Eo(bo);let n=await W.fetch(e),r=Date.now();n.forEach(i=>{let s=I[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(I).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),he=setInterval(Co,a.seconds(1));}}function Eo(t){return new Promise(e=>setTimeout(e,t))}async function Co(){let t=Date.now();Object.values(I).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 So(e);});}async function So(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now();let i=j$1("cron",`cron:${e}`);n().then(()=>{ut(r,o),i.end("success");}).catch(s=>{ut(r,o),k(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await W.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function ut(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function ft(){return Object.values(I).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var ht=new b("_system.cron",{stores:[W]});var ge={};function ye(t,e){return R(),bt(t),Y("query",t,e)}function gt(t,e){return R(),bt(t),Y("mutation",t,e)}function yt(t,e){return R(),Et(t),Y("query",t,e)}function wt(t,e){return R(),Et(t),Y("mutation",t,e)}function bt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Et(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function Y(t,e,o){if(R(),ge[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??[];ge[e]={type:t,name:e,handler:n,permissions:r};}async function Ct(t,e,o){R();let n=ge[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=j$1("method",`method:${t}`,{type:r,args:e}),a;try{qe(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var X=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function St(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await X.fetch({version:{$in:e}}),n=new Set(o.map(({version:i})=>i)),r=t.filter(({version:i})=>!n.has(i));if(r.length!==0){console.log(`Running migrations (${r.length})...`);for(let{version:i,description:s,handler:a}of r)console.log(`Running migration v${i}: ${s}`),await X.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var xt=new b("_system.migration",{stores:[X]});var Tt=new b("_system.rateLimit",{stores:[q]});var vt=new b("_system.site",{configSchema:{url:{type:"string",isPublic:true,default:""}}});var be=class{async init(){this.config=await Mo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[Se.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(Se.static(this.config.publicDir)),e}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".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Oo(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function Io(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Mo(){let t=process.cwd(),e=await Oo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Ro.existsSync(we.join(t,i))),n=[_o(),ko()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:we.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":we.resolve(t,"src").replace(/\\/g,"/")}}});return Io(r,e)}function ko(){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}}}var _t=new be;async function Rt(t,e){let{authToken:o}=await ce(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function N(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ee(t,e,o){let n=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await Ee(t);try{if(n){await Rt(e,n._id),g().onAfterLogin?.({user:n,session:r,connectionInfo:i}),g().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(g().login?.onError?.(s),g().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Rt(e,a.insertedId);let l=await p.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(g().onAfterSignup?.({user:l,session:r,connectionInfo:i}),g().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(g().onSignupError?.({error:s,session:r,connectionInfo:i}),g().signup?.onError?.(s)),s}}function te(t){return !t||typeof t!="string"?null:t}async function Po(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function jo(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Uo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=N("google");try{let s=await Po(o,n,r,i),a=await jo(s.access_token),l={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await ee(t,e,l);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function No(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=N("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,Uo),t}var Ot=No;async function $o(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function zo(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Zo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=N("github");try{let s=await $o(o,n,r,i),a=await zo(s.access_token),l=a.email||"";if(!l){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let d={id:String(a.id),email:l,emailVerified:!0,providerName:"github"};await ee(t,e,d);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function qo(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=N("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(d=>d.trim()).join(" "):"user:email",l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",r),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a),n.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,Zo),t}var It=qo;function Mt(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&_())try{let{session:d,user:E}=await D(s);a={session:d,user:E};}catch{}let l=j$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let d=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,req:n,res:r,next:i},a);l.end(),d&&(r.status(d.status||200),d.redirect&&r.redirect(d.redirect),d.headers&&Object.entries(d.headers).forEach(([E,u])=>{r.setHeader(E,u);}),r.send(d.data));}catch(d){l.end("error"),d instanceof a$3?r.status(d.status).send(d.message):(console.error(`Error in route handler: ${n.path}`),console.error(d),r.status(500).send(String(d)));}}}var Ce=Object.freeze({});function kt(t){Ce=Object.freeze(Object.assign({},Ce,t));}function oe(){return Ce}function Fo(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,Mt(s,r,a));});}}async function At(t,{combinedModules:e,channels:o}){let n=Se();n.use(Se.json({limit:"16mb"})),n.use(Se.urlencoded({extended:true,limit:"16mb"})),n.use(Wo()),n.use(Ot()),n.use(It()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:d}=a.params,E=await Ee(a);try{let u=await Ct(d,a.body.args,E);l.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${d}:`,u),u instanceof a$3)l.status(u.status).send(u.message);else if(u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let M=u.flatten(),ne=Object.entries(M.fieldErrors).map(([L,ie])=>`${L}: ${(ie??[]).join(", ")}`).join("; "),re=M.formErrors.join("; "),B=[ne,re].filter(Boolean).join("; ");l.status(400).send(B);}else l.status(500).send(u instanceof Error?u.message:String(u));}}),Fo(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=Bo.createServer(n),i=oe()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h("Application started",{source:"app"}),console.log(`
14
+ `}var ge={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function lt(t,{connectionInfo:e}){let o=j(t.email),n=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ge;let r=w().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await C.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,d=`${So(a$1,w().passwordReset?.redirectUrl)}?token=${i}`,u=(w()?.passwordReset?.template||xo)({email:o,resetUrl:d,name:""}),S=X(u);return await r.sendEmail({to:o,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:S,html:u}),ge}async function dt(t,{}){let e=z.string().parse(t.token),o=te(t.password),n=await C.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await C.deleteOne({token:e}),new Error("Reset token has expired");let r=await p.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await fo.hash(o,10);return await p.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await C.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var ut=new b("_system.user",{stores:[p,W,v,C],queries:{getOwnProfile:st},mutations:{signupWithPassword:ct,loginWithPassword:rt,logout:it,sendResetPasswordToken:lt,resetPassword:dt},cronJobs:{updateDisposableEmailList:Qe},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:et}}]});async function mt({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(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await ye("/api/connect","POST",{hostname:To.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function pt(){return await ye("/api/configs","GET")}async function ft(){return await ye("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ye(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 i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var we=false,vo=a.seconds(10);function ht(){setInterval(async()=>{if(!we){we=true;try{await ft();}catch(t){console.error("Error syncing status",t);}try{await Do();}catch(t){console.error("Error syncing config",t);}we=false;}},vo);}async function Do(){let{configs:t}=await pt();c$1(t);}var J=new y("_modelenceLocks",{schema:{resource:c.string(),instanceId:c.string(),acquiredAt:c.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var N={},gt=a.seconds(10),yt=randomBytes(32).toString("base64url"),ko=a.seconds(30);async function oe(t,{lockDuration:e=ko,successfulLockCacheDuration:o=gt,failedLockCacheDuration:n=gt,instanceId:r=yt}={}){let i=Date.now();if(N[t]&&i<N[t].expiresAt)return N[t].value;let s=new Date(i-e);h(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:r});try{let a=await J.upsertOne({$or:[{resource:t,instanceId:r},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:r,acquiredAt:new Date}}),l=a.upsertedCount>0||a.modifiedCount>0;return N[t]={value:l,expiresAt:i+(l?o:n)},l?h(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:r}):h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),l}catch{return N[t]={value:false,expiresAt:i+n},h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),false}}async function wt(t,{instanceId:e=yt}={}){let o=await J.deleteOne({resource:t,instanceId:e});return delete N[t],o.deletedCount>0}var Ro=a.minutes(1),A={},be=null,Ee=new y("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Et(t,{description:e="",interval:o,timeout:n=Ro,handler:r}){if(A[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(be)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);A[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Ct(){if(be)throw new Error("Cron jobs already started");let t=Object.keys(A);if(t.length>0){let e={alias:{$in:t}},o=await Ee.fetch(e),n=Date.now();o.forEach(r=>{let i=A[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:n);}),Object.values(A).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=n);}),be=setInterval(Oo,a.seconds(1));}}async function Oo(){let t=Date.now();await oe("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(A).forEach(async o=>{let{params:n,state:r}=o;if(r.isRunning){r.startTs&&r.startTs+n.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await Mo(o);});}async function Mo(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now(),await Ee.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});let i=k$1("cron",`cron:${e}`);try{await n(),bt(r,o),i.end("success");}catch(s){bt(r,o);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function bt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function St(){return Object.values(A).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var xt=new b("_system.cron",{stores:[Ee]});var Ce={};function Se(t,e){return O(),_t(t),ne("query",t,e)}function Tt(t,e){return O(),_t(t),ne("mutation",t,e)}function vt(t,e){return O(),kt(t),ne("query",t,e)}function Dt(t,e){return O(),kt(t),ne("mutation",t,e)}function _t(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function kt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function ne(t,e,o){if(O(),Ce[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??[];Ce[e]={type:t,name:e,handler:n,permissions:r};}async function Rt(t,e,o){O();let n=Ce[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=k$1("method",`method:${t}`,{type:r,args:e}),a;try{He(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var xe=new b("_system.lock",{stores:[J]});var H=new y("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function Ao(t){if(t.length===0)return;if(!await oe("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),n=await H.fetch({version:{$in:o}}),r=new Set(n.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!r.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:l}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=await l();await H.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:d||"",appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(d){d instanceof Error&&(await H.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:d.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${d.message}`,{source:"migrations"}));}}await wt("migrations");}}function Ot(t){setTimeout(()=>{Ao(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Mt=new b("_system.migration",{stores:[H]});var At=new b("_system.rateLimit",{stores:[B]});var It=new b("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},"log.level":{type:"string",isPublic:false,default:"info"}}});var ve=class{async init(){this.config=await qo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ke.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ke.static(this.config.publicDir)),e}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".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function $o(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function zo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function qo(){let t=process.cwd(),e=await $o(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>No.existsSync(Te.join(t,i))),n=[jo(),Zo()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Te.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Te.resolve(t,"src").replace(/\\/g,"/")}}});return zo(r,e)}function Zo(){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}}}var Ut=new ve;async function Lt(t,e){let{authToken:o}=await me(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function $(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function re(t,e,o){let n=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await De(t);try{if(n){await Lt(e,n._id),g().onAfterLogin?.({user:n,session:r,connectionInfo:i}),g().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(g().login?.onError?.(s),g().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Lt(e,a.insertedId);let l=await p.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(g().onAfterSignup?.({user:l,session:r,connectionInfo:i}),g().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(g().onSignupError?.({error:s,session:r,connectionInfo:i}),g().signup?.onError?.(s)),s}}function ie(t){return !t||typeof t!="string"?null:t}async function Fo(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Bo(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Jo(t,e){let o=ie(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=$("google");try{let s=await Fo(o,n,r,i),a=await Bo(s.access_token),l={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await re(t,e,l);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function Ho(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=$("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,Jo),t}var jt=Ho;async function Go(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Ko(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Qo(t,e){let o=ie(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=$("github");try{let s=await Go(o,n,r,i),a=await Ko(s.access_token),l=a.email||"";if(!l){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let d={id:String(a.id),email:l,emailVerified:!0,providerName:"github"};await re(t,e,d);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function Yo(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=$("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(d=>d.trim()).join(" "):"user:email",l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",r),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a),n.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,Qo),t}var Nt=Yo;function $t(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&R())try{let{session:d,user:E}=await k(s);a={session:d,user:E};}catch{}let l=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let d=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,req:n,res:r,next:i},a);l.end(),d&&(r.status(d.status||200),d.redirect&&r.redirect(d.redirect),d.headers&&Object.entries(d.headers).forEach(([E,u])=>{r.setHeader(E,u);}),r.send(d.data));}catch(d){l.end("error"),d instanceof a$3?r.status(d.status).send(d.message):(console.error(`Error in route handler: ${n.path}`),console.error(d),r.status(500).send(String(d)));}}}var _e=Object.freeze({});function zt(t){_e=Object.freeze(Object.assign({},_e,t));}function se(){return _e}function tn(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,$t(s,r,a));});}}async function qt(t,{combinedModules:e,channels:o}){let n=ke();n.use(ke.json({limit:"16mb"})),n.use(ke.urlencoded({extended:true,limit:"16mb"})),n.use(Xo()),n.use(jt()),n.use(Nt()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:d}=a.params,E=await De(a);try{let u=await Rt(d,a.body.args,E);l.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${d}:`,u),u instanceof a$3)l.status(u.status).send(u.message);else if(u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let I=u.flatten(),ae=Object.entries(I.fieldErrors).map(([z,le])=>`${z}: ${(le??[]).join(", ")}`).join("; "),ce=I.formErrors.join("; "),V=[ae,ce].filter(Boolean).join("; ");l.status(400).send(V);}else l.status(500).send(u instanceof Error?u.message:String(u));}}),tn(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=en.createServer(n),i$1=se()?.provider;i$1&&i$1.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{i("Application started",{source:"app"}),console.log(`
15
15
  Application started on http://localhost:${s}
16
- `);});}async function Ee(t){let e=T.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=T.object({screenWidth:T.number(),screenHeight:T.number(),windowWidth:T.number(),windowHeight:T.number(),pixelRatio:T.number(),orientation:T.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:Jo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!_()){let{session:i,user:s,roles:a}=await D(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:H()}}function Jo(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function Ko({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=_t,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Pt.config(),Pt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";ln().then(()=>{}).catch(()=>{});let E=[st,Le,ht,xt,Tt,vt],u=[...E,...t];e(),Yo(E),Qo(t),ze(e$1,o);let C=on(u);d$1(C);let M=Xo(u),ne=en(u);d&&nn(u);let re=tn(u);if(ot(re),l){let{configs:L,environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt}=await at({configSchema:C,cronJobsMetadata:d?ft():void 0,stores:M});c$1(L),f({environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt});}else c$1(cn(C));He(i),Qe(s),kt({...a,provider:a.provider||Be});let B=_();if(B&&(await We(),rn(M)),d&&await St(r),B)for(let L of M)L.createIndexes();l&&(await g$1(),dt()),d&&pt().catch(console.error),await At(n,{combinedModules:u,channels:ne});}function Qo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ye(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))gt(`${e.name}.${o}`,n);}}function Yo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))yt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))wt(`${e.name}.${o}`,n);}}function Xo(t){return t.flatMap(e=>e.stores)}function en(t){return t.flatMap(e=>e.channels)}function tn(t){return t.flatMap(e=>e.rateLimits)}function on(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function nn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))mt(`${e.name}.${o}`,n);}function rn(t){let e=V();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var sn={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function an(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function cn(t){let e=[];for(let[o,n]of Object.entries(sn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:an(r,s)});}}return e}async function ln(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await dn(),r=await import('./package-MU4LIHI3.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:ho.hostname(),environmentId:o})});}}async function dn(){try{let t=we.join(process.cwd(),"package.json"),e=await Ho.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var xe=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=oe().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function un(t){if(!y().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return y().provider?.sendEmail(t)}
17
- export{b as Module,xe as ServerChannel,w as Store,D as authenticate,O as consumeRateLimit,ye as createQuery,p as dbUsers,c as schema,un as sendEmail,Ko as startApp};//# sourceMappingURL=server.js.map
16
+ `);});}async function De(t){let e=_.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=_.object({screenWidth:_.number(),screenHeight:_.number(),windowWidth:_.number(),windowHeight:_.number(),pixelRatio:_.number(),orientation:_.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:on(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!R()){let{session:i,user:s,roles:a}=await k(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:Q()}}function on(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function an({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ut,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Zt.config(),Zt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";bn().then(()=>{}).catch(()=>{});let E=[ut,We,xt,Mt,At,It,xe],u=[...E,...t];e(),ln(E),cn(t),Be(e$1,o);let S=pn(u);d$1(S);let I=dn(u),ae=un(u);d&&fn(u);let ce=mn(u);if(at(ce),l){let{configs:z,environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt}=await mt({configSchema:S,cronJobsMetadata:d?St():void 0,stores:I});c$1(z),f({environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt});}else c$1(wn(S));Ye(i),ot(s),zt({...a,provider:a.provider||Ge});let V=R();if(V&&(await Ve(),hn(I)),d&&Ot(r),V)for(let z of I)z.createIndexes();l&&(await g$1(),ht()),d&&Ct().catch(console.error),await qt(n,{combinedModules:u,channels:ae});}function cn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Se(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Tt(`${e.name}.${o}`,n);}}function ln(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))vt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Dt(`${e.name}.${o}`,n);}}function dn(t){return t.flatMap(e=>e.stores)}function un(t){return t.flatMap(e=>e.channels)}function mn(t){return t.flatMap(e=>e.rateLimits)}function pn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function fn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Et(`${e.name}.${o}`,n);}function hn(t){let e=Y();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var gn={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_LOG_LEVEL:"_system.log.level",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function yn(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function wn(t){let e=[];for(let[o,n]of Object.entries(gn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:yn(r,s)});}}return e}async function bn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await En(),r=await import('./package-DSL4EF4B.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:To.hostname(),environmentId:o})});}}async function En(){try{let t=Te.join(process.cwd(),"package.json"),e=await nn.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Wt(t){await v.deleteMany({userId:t}),await C.deleteMany({userId:t});}async function Sn(t){await Wt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function xn(t){await Wt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Re=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=se().provider;if(!n){j$1("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Tn(t){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(t)}
17
+ export{b as Module,Re as ServerChannel,y as Store,k as authenticate,M as consumeRateLimit,Se as createQuery,p as dbUsers,xn as deleteUser,Sn as disableUser,c as schema,Tn as sendEmail,an as startApp};//# sourceMappingURL=server.js.map
18
18
  //# sourceMappingURL=server.js.map