modelence 0.10.12 → 0.11.0-dev.7

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,19 +1,19 @@
1
- import {a as a$2}from'./chunk-3S2FFBNS.js';import {d as d$1,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$2,c,f as f$1,g,j as j$1,a as a$1,i,k,h as h$1,l}from'./chunk-PB6WQQ4L.js';export{a as getConfig}from'./chunk-PB6WQQ4L.js';import {s}from'./chunk-UGJXO42W.js';import Xt from'dotenv';import wr from'fs/promises';import Lo from'os';import Ue 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 M,{z as z$1}from'zod';import vo from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Ho from'@vitejs/plugin-react';import Jo from'fs';import I,{Router}from'express';import ur from'cookie-parser';import pr from'http';var E=class{constructor(e,{stores:o=[],queries:r={},mutations:n={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:c=[],channels:l=[]}){this.name=e,this.stores=o,this.queries=r,this.mutations=n,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=c,this.channels=l;}};function _(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:_(e.type)};if(e.typeName==="ZodObject"){let r=e.shape(),n={};for(let[i,s]of Object.entries(r))n[i]=_(s);return {type:"object",items:n}}if(e.typeName==="ZodOptional")return {..._(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {..._(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(_)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:_(o.schema)}return {type:"custom",typeName:e.typeName}}function ae(t){let e={};for(let[o,r]of Object.entries(t))Array.isArray(r)?e[o]=r.map(n=>typeof n=="object"&&"_def"in n?_(n):ae(n)):typeof r=="object"&&"_def"in r?e[o]=_(r):e[o]=ae(r);return e}var to=t=>{let e=t,o=[e.message,e.errorResponse?.errmsg,e.errorResponse?.message].filter(r=>typeof r=="string");for(let r of o){let n=r.match(/existing index:.*?name:\s*"([^"]+)"/i);if(n?.[1])return n[1];let i=r.match(/requested index:.*?name:\s*"([^"]+)"/i);if(i?.[1])return i[1];let s=r.match(/Index already exists with a different name:\s*([^\s]+)/i);if(s?.[1])return s[1]}},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 ae(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},r=[...this.indexes,...e.indexes||[]],n=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:r,searchIndexes:n});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(){let e=this.requireCollection();if(this.indexes.length>0)for(let o of this.indexes)try{await e.createIndexes([o]);}catch(r){if(r instanceof MongoError&&(r.code===86||r.code===85)){let n=to(r);if(!n)throw r;await e.dropIndex(n),await e.createIndexes([o]);}else throw r}if(this.searchIndexes.length>0)for(let o of this.searchIndexes)try{await e.createSearchIndexes([o]);}catch(r){if(r instanceof MongoError&&r.code===68&&o.name)await e.dropSearchIndex(o.name),await e.createSearchIndexes([o]);else throw r}}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 r=await this.requireCollection().findOne(e,o);return r?this.wrapDocument(r):null}async requireOne(e,o,r){let n=await this.findOne(e,o);if(!n)throw r?r():new Error(`Record not found in ${this.name}`);return n}find(e,o){let r=this.requireCollection().find(e);return o?.sort&&r.sort(o.sort),o?.limit&&r.limit(o.limit),o?.skip&&r.skip(o.skip),r}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let r=await this.findById(e);if(!r)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return r}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,r){return await this.requireCollection().updateMany(e,o,r)}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 r=this.getDatabase();if(!this.collection||!r)throw new Error(`Store ${this.name} is not provisioned`);if((await r.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await r.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await r.collection(e).rename(this.name,o);}async vectorSearch({field:e,embedding:o,numCandidates:r,limit:n,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:r||100,limit:n||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:r="cosine",indexName:n}){return {type:"vectorSearch",name:n||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:r}]}}}};var oo=z$1.string.bind(z$1),ro=z$1.number.bind(z$1),no=z$1.date.bind(z$1),io=z$1.boolean.bind(z$1),so=z$1.array.bind(z$1),ao=z$1.object.bind(z$1),co=z$1.enum.bind(z$1),d={string:oo,number:ro,date:no,boolean:io,array:so,object:ao,enum:co,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 N=new w("_modelenceSessions",{schema:{authToken:d.string(),createdAt:d.date(),expiresAt:d.date(),userId:d.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function Ke(t){let e=t?await N.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Se()}async function Ye(t,e){await N.updateOne({authToken:t},{$set:{userId:e}});}async function Xe(t){await N.updateOne({authToken:t},{$set:{userId:null}});}async function Se(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),r=new Date(o+a.days(7));return await N.insertOne({authToken:e,createdAt:new Date(o),expiresAt:r,userId:t}),{authToken:e,expiresAt:r,userId:t}}async function uo(t){let e=Date.now(),o=new Date(e+a.days(7));await N.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var et=new E("_system.session",{stores:[N],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 uo(e);}}});var f=new w("_modelenceUsers",{schema:{handle:d.string(),emails:d.array(d.object({address:d.string(),verified:d.boolean()})).optional(),status:d.enum(["active","disabled","deleted"]).optional(),createdAt:d.date(),disabledAt:d.date().optional(),deletedAt:d.date().optional(),roles:d.array(d.string()).optional(),authMethods:d.object({password:d.object({hash:d.string()}).optional(),google:d.object({id:d.string()}).optional(),github:d.object({id:d.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}]}),K=new w("_modelenceDisposableEmailDomains",{schema:{domain:d.string(),addedAt:d.date()},indexes:[{key:{domain:1},unique:true}]}),A=new w("_modelenceEmailVerificationTokens",{schema:{userId:d.objectId(),email:d.string().optional(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new w("_modelenceResetPasswordTokens",{schema:{userId:d.objectId(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var tt=new Map,z={authenticated:null,unauthenticated:null};function ot(t,e){z.authenticated=e.authenticated,z.unauthenticated=e.unauthenticated;for(let[o,r]of Object.entries(t))tt.set(o,r);}function ce(){return z.unauthenticated?[z.unauthenticated]:[]}function rt(){return z.authenticated?[z.authenticated]:[]}function Ce(t,e){let o=e.find(r=>!po(t,r));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function po(t,e){for(let o of t){let r=tt.get(o);if(r&&r.permissions.includes(e))return true}return false}async function T(t){let e=await Ke(t),o=e.userId?await f.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,r=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,n=r?rt():ce();return {user:r,session:e,roles:n}}var O=null;async function nt(){if(O)return O;let t=U();if(!t)throw new Error("MongoDB URI is not set");O=new MongoClient(t,{maxPoolSize:20,driverInfo:{name:"Modelence",version:s.version},ignoreUndefined:true});try{return await O.connect(),await O.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),O}catch(e){throw console.error(e),O=null,e}}function U(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function le(){return O}var F=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function ho(){return typeof window!="object"}function R(){if(!ho())throw new Error("This function can only be called on the server")}function de(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var ue={};function xe(t,e){return R(),ct(t),pe("query",t,e)}function it(t,e){return R(),ct(t),pe("mutation",t,e)}function st(t,e){return R(),lt(t),pe("query",t,e)}function at(t,e){return R(),lt(t),pe("mutation",t,e)}function ct(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function lt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function pe(t,e,o){if(R(),ue[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof o=="function"?o:o.handler,n=typeof o=="function"?[]:o.permissions??[];ue[e]={type:t,name:e,handler:r,permissions:n};}async function dt(t,e,o){R();let r=ue[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=r,s=k("method",`method:${t}`,{type:n,args:e}),a;try{Ce(o.roles,r.permissions),a=await i(e,o);}catch(c){throw s.end("error"),c}return s.end(),a}async function ut(t,e,o){R();let r=ue[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=r;if(n!=="query")throw new Error("Live methods are only supported for queries");let s=k("method",`method:${t}:live`,{type:n,args:e}),a;try{if(Ce(o.roles,r.permissions),a=await i(e,o),!(a instanceof F))throw new Error(`Live query handler for '${t}' must return a LiveData object with fetch and watch functions.`)}catch(c){throw s.end("error"),c}return s.end(),a}var Y=new Map;function go(t){let e=Y.get(t.id);return e||(e=new Map,Y.set(t.id,e)),e}async function ve(t,e){let o=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({}),authToken:z$1.string().nullish(),clientInfo:z$1.object({screenWidth:z$1.number(),screenHeight:z$1.number(),windowWidth:z$1.number(),windowHeight:z$1.number(),pixelRatio:z$1.number(),orientation:z$1.string().nullable()}).optional()}).safeParse(e);if(!o.success){t.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${o.error.message}`});return}let{subscriptionId:r,method:n,args:i,authToken:s,clientInfo:a}=o.data,c=go(t),l=c.get(r);if(l)if(l.cleanup)try{l.cleanup();}catch(p){console.error("[LiveQuery] Error cleaning up existing subscription:",p);}else l.aborted=true;let m={cleanup:null};c.set(r,m);try{let{session:p,user:x,roles:D}=await T(s??null),B={session:p,user:x,roles:D,clientInfo:a??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:t.handshake.address,userAgent:t.handshake.headers["user-agent"]}},re=await ut(n,i,B),ne=async()=>{let C=await re.fetch();m.aborted||t.emit("liveQueryData",{subscriptionId:r,data:C,typeMap:a$2(C)});},L=!0,V=!1,H=()=>{m.aborted||!L||V||(L=!1,V=!0,ne().catch(C=>{m.aborted||(console.error(`[LiveQuery] Error fetching data for ${n}:`,C),t.emit("liveQueryError",{subscriptionId:r,error:C instanceof Error?C.message:String(C)}));}).finally(()=>{V=!1,H();}));},J=re.watch({publish:()=>{L=!0,H();}});if(m.aborted){if(J)try{J();}catch(C){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",C);}return}m.cleanup=J||null,H();}catch(p){c.delete(r),console.error(`[LiveQuery] Error in ${n}:`,p),t.emit("liveQueryError",{subscriptionId:r,error:p instanceof Error?p.message:String(p)});}}function Te(t,e){let o=z$1.object({subscriptionId:z$1.string().min(1)}).safeParse(e);if(!o.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${o.error.message}`);return}let{subscriptionId:r}=o.data,n=Y.get(t.id);if(!n)return;let i=n.get(r);if(i){if(i.cleanup)try{i.cleanup();}catch(s){console.error("[LiveQuery] Error in cleanup:",s);}else i.aborted=true;n.delete(r);}}function De(t){let e=Y.get(t.id);if(e){for(let o of e.values())if(o.cleanup)try{o.cleanup();}catch(r){console.error("[LiveQuery] Error in cleanup on disconnect:",r);}else o.aborted=true;Y.delete(t.id);}}var X=null,bo="_modelenceSocketio";async function Eo({httpServer:t,channels:e}){let o=le();console.log("Initializing Socket.IO server...");let r=null;if(o){r=o.db().collection(bo);try{await r.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(n){console.error("Failed to create index on MongoDB collection for Socket.IO:",n);}}X=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:r?createAdapter(r):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),X.on("error",n=>{console.error("Socket.IO error:",n);}),X.use(async(n,i)=>{let s=n.handshake.auth.token;try{n.data=await T(s);}finally{i();}}),X.on("connection",n=>{n.on("disconnect",()=>{De(n);}),n.on("joinChannel",async i=>{let[s]=i.split(":"),a=false;for(let c of e)if(c.category===s){(!c.canAccessChannel||await c.canAccessChannel(n.data))&&(n.join(i),a=true,n.emit("joinedChannel",i));break}a||n.emit("joinError",{channel:i,error:"Access denied"});}),n.on("leaveChannel",i=>{n.leave(i),console.log(`User ${n.id} left channel ${i}`),n.emit("leftChannel",i);}),n.on("subscribeLiveQuery",i=>ve(n,i)),n.on("unsubscribeLiveQuery",i=>Te(n,i));}),console.log("Socket.IO server initialized");}function So({category:t,id:e,data:o}){X?.to(`${t}:${e}`).emit(t,o);}var pt={init:Eo,broadcast:So};async function mt(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await K.findOne({domain:o})}var ft={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),r=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await K.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var ke=Object.freeze({});function ht(t){ke=Object.freeze(Object.assign({},ke,t));}function b(){return ke}function gt({name:t,email:e,verificationUrl:o}){return `
1
+ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d as d$1,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$2,c,f as f$1,g,j as j$1,a as a$1,i,k,h as h$1,l}from'./chunk-PB6WQQ4L.js';export{a as getConfig}from'./chunk-PB6WQQ4L.js';import {t}from'./chunk-JBVRKV7T.js';import tr from'dotenv';import Eo from'fs/promises';import Pr from'os';import je 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 L,{z as z$1}from'zod';import kr from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Jr from'@vitejs/plugin-react';import Gr from'fs';import P,{Router}from'express';import po from'cookie-parser';import fo from'http';var E=class{constructor(e,{stores:r=[],queries:o={},mutations:n={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:c=[],channels:l=[]}){this.name=e,this.stores=r,this.queries=o,this.mutations=n,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=c,this.channels=l;}};function A(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:A(e.type)};if(e.typeName==="ZodObject"){let o=e.shape(),n={};for(let[i,s]of Object.entries(o))n[i]=A(s);return {type:"object",items:n}}if(e.typeName==="ZodOptional")return {...A(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...A(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(A)};if(e.typeName==="ZodEffects"){let r=e;return r.description?{type:"custom",typeName:r.description}:A(r.schema)}return {type:"custom",typeName:e.typeName}}function ce(t){let e={};for(let[r,o]of Object.entries(t))Array.isArray(o)?e[r]=o.map(n=>typeof n=="object"&&"_def"in n?A(n):ce(n)):typeof o=="object"&&"_def"in o?e[r]=A(o):e[r]=ce(o);return e}var or=t=>{let e=t,r=[e.message,e.errorResponse?.errmsg,e.errorResponse?.message].filter(o=>typeof o=="string");for(let o of r){let n=o.match(/existing index:.*?name:\s*"([^"]+)"/i);if(n?.[1])return n[1];let i=o.match(/requested index:.*?name:\s*"([^"]+)"/i);if(i?.[1])return i[1];let s=o.match(/Index already exists with a different name:\s*([^\s]+)/i);if(s?.[1])return s[1]}},b=class t{constructor(e,r){this.name=e,this.schema=r.schema,this.methods=r.methods,this.indexes=r.indexes,this.searchIndexes=r.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return ce(this.schema)}extend(e){let r={...this.schema,...e.schema||{}},o=[...this.indexes,...e.indexes||[]],n=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:r,methods:i,indexes:o,searchIndexes:n});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(){let e=this.requireCollection();if(this.indexes.length>0)for(let r of this.indexes)try{await e.createIndexes([r]);}catch(o){if(o instanceof MongoError&&(o.code===86||o.code===85)){let n=or(o);if(!n)throw o;await e.dropIndex(n),await e.createIndexes([r]);}else throw o}if(this.searchIndexes.length>0)for(let r of this.searchIndexes)try{await e.createSearchIndexes([r]);}catch(o){if(o instanceof MongoError&&o.code===68&&r.name)await e.dropSearchIndex(r.name),await e.createSearchIndexes([r]);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,r){let o=await this.requireCollection().findOne(e,r);return o?this.wrapDocument(o):null}async requireOne(e,r,o){let n=await this.findOne(e,r);if(!n)throw o?o():new Error(`Record not found in ${this.name}`);return n}find(e,r){let o=this.requireCollection().find(e);return r?.sort&&o.sort(r.sort),r?.limit&&o.limit(r.limit),r?.skip&&o.skip(r.skip),o}async findById(e){let r=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(r)}async requireById(e,r){let o=await this.findById(e);if(!o)throw r?r():new Error(`Record with id ${e} not found in ${this.name}`);return o}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,r){return (await this.find(e,r).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,r){return await this.requireCollection().updateOne(this.getSelector(e),r)}async upsertOne(e,r){return await this.requireCollection().updateOne(this.getSelector(e),r,{upsert:true})}async updateMany(e,r,o){return await this.requireCollection().updateMany(e,r,o)}async upsertMany(e,r){return await this.requireCollection().updateMany(e,r,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,r){return this.requireCollection().aggregate(e,r)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,r){let o=this.getDatabase();if(!this.collection||!o)throw new Error(`Store ${this.name} is not provisioned`);if((await o.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await o.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await o.collection(e).rename(this.name,r);}async vectorSearch({field:e,embedding:r,numCandidates:o,limit:n,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:r,numCandidates:o||100,limit:n||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:r,similarity:o="cosine",indexName:n}){return {type:"vectorSearch",name:n||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:r,similarity:o}]}}}};var nr=z$1.string.bind(z$1),ir=z$1.number.bind(z$1),sr=z$1.date.bind(z$1),ar=z$1.boolean.bind(z$1),cr=z$1.array.bind(z$1),lr=z$1.object.bind(z$1),dr=z$1.enum.bind(z$1),d={string:nr,number:ir,date:sr,boolean:ar,array:cr,object:lr,enum:dr,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 z=new b("_modelenceSessions",{schema:{authToken:d.string(),createdAt:d.date(),expiresAt:d.date(),userId:d.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function Ye(t){let e=t?await z.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Ce()}async function Xe(t,e){await z.updateOne({authToken:t},{$set:{userId:e}});}async function et(t){await z.updateOne({authToken:t},{$set:{userId:null}});}async function Ce(t=null){let e=randomBytes(32).toString("base64url"),r=Date.now(),o=new Date(r+a.days(7));return await z.insertOne({authToken:e,createdAt:new Date(r),expiresAt:o,userId:t}),{authToken:e,expiresAt:o,userId:t}}async function mr(t){let e=Date.now(),r=new Date(e+a.days(7));await z.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:r}});}var tt=new E("_system.session",{stores:[z],mutations:{init:async function(t,{session:e,user:r}){return {session:e,user:r,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await mr(e);}}});var f=new b("_modelenceUsers",{schema:{handle:d.string(),emails:d.array(d.object({address:d.string(),verified:d.boolean()})).optional(),status:d.enum(["active","disabled","deleted"]).optional(),createdAt:d.date(),disabledAt:d.date().optional(),deletedAt:d.date().optional(),roles:d.array(d.string()).optional(),authMethods:d.object({password:d.object({hash:d.string()}).optional(),google:d.object({id:d.string()}).optional(),github:d.object({id:d.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}]}),K=new b("_modelenceDisposableEmailDomains",{schema:{domain:d.string(),addedAt:d.date()},indexes:[{key:{domain:1},unique:true}]}),O=new b("_modelenceEmailVerificationTokens",{schema:{userId:d.objectId(),email:d.string().optional(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new b("_modelenceResetPasswordTokens",{schema:{userId:d.objectId(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var rt=new Map,F={authenticated:null,unauthenticated:null};function ot(t,e){F.authenticated=e.authenticated,F.unauthenticated=e.unauthenticated;for(let[r,o]of Object.entries(t))rt.set(r,o);}function le(){return F.unauthenticated?[F.unauthenticated]:[]}function nt(){return F.authenticated?[F.authenticated]:[]}function xe(t,e){let r=e.find(o=>!pr(t,o));if(r)throw new Error(`Access denied - missing permission: '${r}'`)}function pr(t,e){for(let r of t){let o=rt.get(r);if(o&&o.permissions.includes(e))return true}return false}async function T(t){let e=await Ye(t),r=e.userId?await f.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,o=r?{id:r._id.toString(),handle:r.handle,roles:r.roles||[],hasRole:i=>(r.roles||[]).includes(i),requireRole:i=>{if(!(r.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,n=o?nt():le();return {user:o,session:e,roles:n}}var R=null;async function it(){if(R)return R;let t$1=j();if(!t$1)throw new Error("MongoDB URI is not set");R=new MongoClient(t$1,{maxPoolSize:20,driverInfo:{name:"Modelence",version:t.version},ignoreUndefined:true});try{return await R.connect(),await R.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),R}catch(e){throw console.error(e),R=null,e}}function j(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function de(){return R}var q=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function gr(){return typeof window!="object"}function M(){if(!gr())throw new Error("This function can only be called on the server")}function ue(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var me={};function ve(t,e){return M(),lt(t),pe("query",t,e)}function st(t,e){return M(),lt(t),pe("mutation",t,e)}function at(t,e){return M(),dt(t),pe("query",t,e)}function ct(t,e){return M(),dt(t),pe("mutation",t,e)}function lt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function dt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function pe(t,e,r){if(M(),me[e])throw new Error(`Method with name '${e}' is already defined.`);let o=typeof r=="function"?r:r.handler,n=typeof r=="function"?[]:r.permissions??[];me[e]={type:t,name:e,handler:o,permissions:n};}async function ut(t,e,r){M();let o=me[t];if(!o)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=o,s=k("method",`method:${t}`,{type:n,args:e}),a;try{xe(r.roles,o.permissions),a=await i(e,r);}catch(c){throw s.end("error"),c}return s.end(),a}async function mt(t,e,r){M();let o=me[t];if(!o)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=o;if(n!=="query")throw new Error("Live methods are only supported for queries");let s=k("method",`method:${t}:live`,{type:n,args:e}),a;try{if(xe(r.roles,o.permissions),a=await i(e,r),!(a instanceof q))throw new Error(`Live query handler for '${t}' must return a LiveData object with fetch and watch functions.`)}catch(c){throw s.end("error"),c}return s.end(),a}var Y=new Map;function yr(t){let e=Y.get(t.id);return e||(e=new Map,Y.set(t.id,e)),e}async function Te(t,e){let r=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({}),authToken:z$1.string().nullish(),clientInfo:z$1.object({screenWidth:z$1.number(),screenHeight:z$1.number(),windowWidth:z$1.number(),windowHeight:z$1.number(),pixelRatio:z$1.number(),orientation:z$1.string().nullable()}).optional()}).safeParse(e);if(!r.success){t.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${r.error.message}`});return}let{subscriptionId:o,method:n,args:i,authToken:s,clientInfo:a}=r.data,c=yr(t),l=c.get(o);if(l)if(l.cleanup)try{l.cleanup();}catch(m){console.error("[LiveQuery] Error cleaning up existing subscription:",m);}else l.aborted=true;let p={cleanup:null};c.set(o,p);try{let{session:m,user:x,roles:k}=await T(s??null),B={session:m,user:x,roles:k,clientInfo:a??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:t.handshake.address,userAgent:t.handshake.headers["user-agent"]}},ne=await mt(n,i,B),ie=async()=>{let C=await ne.fetch();p.aborted||t.emit("liveQueryData",{subscriptionId:o,data:C,typeMap:a$2(C)});},U=!0,V=!1,H=()=>{p.aborted||!U||V||(U=!1,V=!0,ie().catch(C=>{p.aborted||(console.error(`[LiveQuery] Error fetching data for ${n}:`,C),t.emit("liveQueryError",{subscriptionId:o,error:C instanceof Error?C.message:String(C)}));}).finally(()=>{V=!1,H();}));},J=ne.watch({publish:()=>{U=!0,H();}});if(p.aborted){if(J)try{J();}catch(C){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",C);}return}p.cleanup=J||null,H();}catch(m){c.delete(o),console.error(`[LiveQuery] Error in ${n}:`,m),t.emit("liveQueryError",{subscriptionId:o,error:m instanceof Error?m.message:String(m)});}}function De(t,e){let r=z$1.object({subscriptionId:z$1.string().min(1)}).safeParse(e);if(!r.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${r.error.message}`);return}let{subscriptionId:o}=r.data,n=Y.get(t.id);if(!n)return;let i=n.get(o);if(i){if(i.cleanup)try{i.cleanup();}catch(s){console.error("[LiveQuery] Error in cleanup:",s);}else i.aborted=true;n.delete(o);}}function ke(t){let e=Y.get(t.id);if(e){for(let r of e.values())if(r.cleanup)try{r.cleanup();}catch(o){console.error("[LiveQuery] Error in cleanup on disconnect:",o);}else r.aborted=true;Y.delete(t.id);}}var X=null,Er="_modelenceSocketio";async function Sr({httpServer:t,channels:e}){let r=de();console.log("Initializing Socket.IO server...");let o=null;if(r){o=r.db().collection(Er);try{await o.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(n){console.error("Failed to create index on MongoDB collection for Socket.IO:",n);}}X=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:o?createAdapter(o):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),X.on("error",n=>{console.error("Socket.IO error:",n);}),X.use(async(n,i)=>{let s=n.handshake.auth.token;try{n.data=await T(s);}finally{i();}}),X.on("connection",n=>{n.on("disconnect",()=>{ke(n);}),n.on("joinChannel",async i=>{let[s]=i.split(":"),a=false;for(let c of e)if(c.category===s){(!c.canAccessChannel||await c.canAccessChannel(n.data))&&(n.join(i),a=true,n.emit("joinedChannel",i));break}a||n.emit("joinError",{channel:i,error:"Access denied"});}),n.on("leaveChannel",i=>{n.leave(i),console.log(`User ${n.id} left channel ${i}`),n.emit("leftChannel",i);}),n.on("subscribeLiveQuery",i=>Te(n,i)),n.on("unsubscribeLiveQuery",i=>De(n,i));}),console.log("Socket.IO server initialized");}function Cr({category:t,id:e,data:r}){X?.to(`${t}:${e}`).emit(t,r);}var pt={init:Sr,broadcast:Cr};async function ft(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let r=e[1];return !!await K.findOne({domain:r})}var ht={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 r=(await t.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),o=new Date,n=500;for(let i=0;i<r.length;i+=n){let s=r.slice(i,i+n);try{await K.insertMany(s.map(a=>({domain:a,addedAt:o})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var _e=Object.freeze({});function gt(t){_e=Object.freeze(Object.assign({},_e,t));}function w(){return _e}function yt({name:t,email:e,verificationUrl:r}){return `
3
3
  <p>Hi${t?` ${t}`:""},</p>
4
4
  <p>Please verify your email address ${e} by clicking the link below:</p>
5
- <p><a href="${o}">${o}</a></p>
5
+ <p><a href="${r}">${r}</a></p>
6
6
  <p>If you did not request this, please ignore this email.</p>
7
- `}var _e=Object.freeze({});function yt(t){_e=Object.freeze(Object.assign({},_e,t));}function h(){return _e}async function wt(t){let e=process.env.MODELENCE_SITE_URL,o=b().emailVerifiedRedirectUrl||e||"/";try{let r=z$1.string().parse(t.query.token),n=await A.findOne({token:r,expiresAt:{$gt:new Date}});if(!n)throw new Error("Invalid or expired verification token");if(!await f.findOne({_id:n.userId}))throw new Error("User not found");let s=n.email;if(!s)throw new Error("Email not found in token");if((await f.updateOne({_id:n.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await f.findOne({_id:n.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await A.deleteOne({_id:n._id}),h().onAfterEmailVerification?.({provider:"email",user:await f.findOne({"emails.address":n?.email}),session:null,connectionInfo:{baseUrl:e,ip:t.req.ip||t.req.socket.remoteAddress,userAgent:t.headers["user-agent"],acceptLanguage:t.headers["accept-language"],referrer:t.headers.referer}});}catch(r){if(r instanceof Error)return h().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:e,ip:t.req.ip||t.req.socket.remoteAddress,userAgent:t.headers["user-agent"],acceptLanguage:t.headers["accept-language"],referrer:t.headers.referer}}),console.error("Error verifying email:",r),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(r.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function me({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(b().provider){let r=b().provider,n=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await A.insertOne({userId:t,email:e,token:n,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${n}`,c=(b()?.verification?.template||gt)({name:"",email:e,verificationUrl:s}),l=de(c);await r?.sendEmail({to:e,from:b()?.from||"noreply@modelence.com",subject:b()?.verification?.subject||"Verify your email address",text:l,html:c});}}function fe(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function q(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}async function St(t,{user:e,session:o,connectionInfo:r}){try{if(!o)throw new Error("Session is not initialized");let n=r?.ip;n&&await $({bucket:"signin",type:"ip",value:n});let i=q(t.email),s=z$1.string().parse(t.password),a=await f.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),c=a?.authMethods?.password?.hash;if(!c)throw Et();if(!a.emails?.find(p=>p.address===i)?.verified&&b()?.provider){if(n)try{await $({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 me({userId:a?._id,email:i,baseUrl:r?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await vo.compare(s,c))throw Et();return await Ye(o.authToken,a._id),h().onAfterLogin?.({provider:"email",user:a,session:o,connectionInfo:r}),h().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle,roles:a.roles||[]}}}catch(n){throw n instanceof Error&&(h().onLoginError?.({provider:"email",error:n,session:o,connectionInfo:r}),h().login?.onError?.(n)),n}}async function Ct(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Xe(e.authToken);}function Et(){return new Error("Incorrect email/password combination")}async function xt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await f.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var ee=new w("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Ae=[];function vt(t){if(Ae.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Ae=t;}async function $(t){let{bucket:e,type:o,value:r}=t,n=Ae.filter(i=>i.bucket===e&&i.type===o);for(let i of n)await Do(i,r);}async function Do(t,e,o){let r=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),n=await ee.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:c}=n?ko(n,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 r();await ee.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},c);}function ko(t,e,o){let r=e-t.windowMs;if(t.windowStart.getTime()===e){let n=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(n+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()===r){let n=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*n),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 Tt(t,{user:e,session:o,connectionInfo:r}){try{let n=q(t.email),i=fe(t.password),s=r?.ip;if(s&&await $({bucket:"signupAttempt",type:"ip",value:s}),await mt(n))throw new Error("Please use a permanent email address");let a=await f.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(a){let p=a.emails?.find(x=>x.address===n);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: ${p?.address}`)}s&&await $({bucket:"signup",type:"ip",value:s});let c=await vo.hash(i,10),l=await f.insertOne({handle:n,status:"active",emails:[{address:n,verified:!1}],createdAt:new Date,authMethods:{password:{hash:c}}}),m=await f.findOne({_id:l.insertedId},{readPreference:"primary"});if(!m)throw new Error("User not found");return await me({userId:l?.insertedId,email:n,baseUrl:r?.baseUrl}),h().onAfterSignup?.({provider:"email",user:m,session:o,connectionInfo:r}),h().signup?.onSuccess?.(m),l.insertedId}catch(n){throw n instanceof Error&&(h().onSignupError?.({provider:"email",error:n,session:o,connectionInfo:r}),h().signup?.onError?.(n)),n}}function Mo(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function Io({email:t,resetUrl:e}){return `
7
+ `}var Ae=Object.freeze({});function wt(t){Ae=Object.freeze(Object.assign({},Ae,t));}function h(){return Ae}function fe(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function I(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var ee=new b("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Oe=[];function Et(t){if(Oe.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Oe=t;}async function D(t){let{bucket:e,type:r,value:o,message:n}=t,i=Oe.filter(a=>a.bucket===e&&a.type===r),s=n?()=>new d$1(n):void 0;for(let a of i)await xr(a,o,s);}async function xr(t,e,r){let o=()=>r?r():new d$1(`Rate limit exceeded for ${t.bucket}`),n=await ee.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:c}=n?vr(n,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 o();await ee.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},c);}function vr(t,e,r){let o=e-t.windowMs;if(t.windowStart.getTime()===e){let n=t.windowCount,i=t.prevWindowCount,s=1-(r-e)/t.windowMs;return {count:Math.round(n+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()===o){let n=1-(r-e)/t.windowMs;return {count:Math.round(t.windowCount*n),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 St(t){let e=process.env.MODELENCE_SITE_URL,r=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||e||"/";try{let o=z$1.string().parse(t.query.token),n=await O.findOne({token:o,expiresAt:{$gt:new Date}});if(!n)throw new Error("Invalid or expired verification token");if(!await f.findOne({_id:n.userId}))throw new Error("User not found");let s=n.email;if(!s)throw new Error("Email not found in token");if((await f.updateOne({_id:n.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await f.findOne({_id:n.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await O.deleteOne({_id:n._id}),h().onAfterEmailVerification?.({provider:"email",user:await f.findOne({"emails.address":n?.email}),session:null,connectionInfo:{baseUrl:e,ip:t.req.ip||t.req.socket.remoteAddress,userAgent:t.headers["user-agent"],acceptLanguage:t.headers["accept-language"],referrer:t.headers.referer}});}catch(o){if(o instanceof Error)return h().onEmailVerificationError?.({provider:"email",error:o,session:null,connectionInfo:{baseUrl:e,ip:t.req.ip||t.req.socket.remoteAddress,userAgent:t.headers["user-agent"],acceptLanguage:t.headers["accept-language"],referrer:t.headers.referer}}),console.error("Error verifying email:",o),{status:301,redirect:`${r}?status=error&message=${encodeURIComponent(o.message)}`}}return {status:301,redirect:`${r}?status=verified`}}async function te({userId:t,email:e,baseUrl:r=process.env.MODELENCE_SITE_URL}){if(w().provider){let o=w().provider,n=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await O.insertOne({userId:t,email:e,token:n,createdAt:new Date,expiresAt:i});let s=`${r}/api/_internal/auth/verify-email?token=${n}`,c=(w()?.verification?.template||yt)({name:"",email:e,verificationUrl:s}),l=ue(c);await o?.sendEmail({to:e,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:l,html:c});}}var Re={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function Ct(t,{connectionInfo:e}){let r=I(t.email),o=await f.findOne({"emails.address":r,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!o)return Re;let n=o.emails?.find(i=>i.address===r);if(!n||n.verified)return Re;if(!w().provider)throw new Error("Email provider is not configured");return await D({bucket:"verification",type:"user",value:o._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await te({userId:o._id,email:r,baseUrl:e?.baseUrl}),Re}async function vt(t,{user:e,session:r,connectionInfo:o}){try{if(!r)throw new Error("Session is not initialized");let n=o?.ip;n&&await D({bucket:"signin",type:"ip",value:n});let i=I(t.email),s=z$1.string().parse(t.password),a=await f.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),c=a?.authMethods?.password?.hash;if(!c)throw xt();if(!a.emails?.find(m=>m.address===i)?.verified&&w()?.provider){if(n)try{await D({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 te({userId:a?._id,email:i,baseUrl:o?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await kr.compare(s,c))throw xt();return await Xe(r.authToken,a._id),h().onAfterLogin?.({provider:"email",user:a,session:r,connectionInfo:o}),h().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle,roles:a.roles||[]}}}catch(n){throw n instanceof Error&&(h().onLoginError?.({provider:"email",error:n,session:r,connectionInfo:o}),h().login?.onError?.(n)),n}}async function Tt(t,{session:e}){if(!e)throw new Error("Session is not initialized");await et(e.authToken);}function xt(){return new Error("Incorrect email/password combination")}async function Dt(t,{user:e}){if(!e)throw new Error("Not authenticated");let r=await f.requireById(e.id);return {handle:r.handle,emails:r.emails,authMethods:Object.keys(r.authMethods||{})}}async function kt(t,{user:e,session:r,connectionInfo:o}){try{let n=I(t.email),i=fe(t.password),s=o?.ip;if(s&&await D({bucket:"signupAttempt",type:"ip",value:s}),await ft(n))throw new Error("Please use a permanent email address");let a=await f.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(a){let m=a.emails?.find(x=>x.address===n);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: ${m?.address}`)}s&&await D({bucket:"signup",type:"ip",value:s});let c=await kr.hash(i,10),l=await f.insertOne({handle:n,status:"active",emails:[{address:n,verified:!1}],createdAt:new Date,authMethods:{password:{hash:c}}}),p=await f.findOne({_id:l.insertedId},{readPreference:"primary"});if(!p)throw new Error("User not found");return await te({userId:l?.insertedId,email:n,baseUrl:o?.baseUrl}),h().onAfterSignup?.({provider:"email",user:p,session:r,connectionInfo:o}),h().signup?.onSuccess?.(p),l.insertedId}catch(n){throw n instanceof Error&&(h().onSignupError?.({provider:"email",error:n,session:r,connectionInfo:o}),h().signup?.onError?.(n)),n}}function Ir(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function Lr({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 Oe={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Dt(t,{connectionInfo:e}){let o=q(t.email),r=await f.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r||!r.authMethods?.password)return Oe;let n=b().provider;if(!n)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=Date.now(),a$1=new Date(s),c=new Date(s+a.hours(1));await v.insertOne({userId:r._id,token:i,createdAt:a$1,expiresAt:c});let l=process.env.MODELENCE_SITE_URL||e?.baseUrl,p=`${Mo(l,b().passwordReset?.redirectUrl)}?token=${i}`,D=(b()?.passwordReset?.template||Io)({email:o,resetUrl:p,name:""}),B=de(D);return await n.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:B,html:D}),Oe}async function kt(t,{}){let e=z$1.string().parse(t.token),o=fe(t.password),r=await v.findOne({token:e});if(!r)throw new Error("Invalid or expired reset token");if(r.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let n=await f.findOne({_id:r.userId});if(!n)throw new Error("User not found");let i=await vo.hash(o,10);return await f.updateOne({_id:n._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var _t=new E("_system.user",{stores:[f,K,A,v],queries:{getOwnProfile:xt},mutations:{signupWithPassword:Tt,loginWithPassword:St,logout:Ct,sendResetPasswordToken:Dt,resetPassword:kt},cronJobs:{updateDisposableEmailList:ft},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:wt}}]});async function At({configSchema:t,cronJobsMetadata:e,stores:o}){let r=process.env.MODELENCE_CONTAINER_ID;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await Re("/api/connect","POST",{hostname:Lo.hostname(),containerId:r,dataModels:n,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function Ot(){return await Re("/api/configs","GET")}async function Rt(){return await Re("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Re(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...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 Me=false,Po=a.seconds(10);function Mt(){setInterval(async()=>{if(!Me){Me=true;try{await Rt();}catch(t){console.error("Error syncing status",t);}try{await Uo();}catch(t){console.error("Error syncing config",t);}Me=false;}},Po);}async function Uo(){let{configs:t}=await Ot();c(t);}var te=new w("_modelenceLocks",{schema:{resource:d.string(),instanceId:d.string(),acquiredAt:d.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var W={},It=a.seconds(10),Lt=randomBytes(32).toString("base64url"),jo=a.seconds(30);async function he(t,{lockDuration:e=jo,successfulLockCacheDuration:o=It,failedLockCacheDuration:r=It,instanceId:n=Lt}={}){let i=Date.now();if(W[t]&&i<W[t].expiresAt)return W[t].value;let s=new Date(i-e);h$1(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:n});try{let a=await te.upsertOne({$or:[{resource:t,instanceId:n},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:n,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return W[t]={value:c,expiresAt:i+(c?o:r)},c?h$1(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:n}):h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),c}catch{return W[t]={value:false,expiresAt:i+r},h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),false}}async function Pt(t,{instanceId:e=Lt}={}){let o=await te.deleteOne({resource:t,instanceId:e});return delete W[t],o.deletedCount>0}var No=a.minutes(1),j={},Ie=null,Le=new w("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function $t(t,{description:e="",interval:o,timeout:r=No,handler:n}){if(j[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(Ie)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(r>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);j[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function jt(){if(Ie)throw new Error("Cron jobs already started");let t=Object.keys(j);if(t.length>0){let e={alias:{$in:t}},o=await Le.fetch(e),r=Date.now();o.forEach(n=>{let i=j[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(j).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),Ie=setInterval(zo,a.seconds(1));}}async function zo(){let t=Date.now();await he("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(j).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Fo(o);});}async function Fo(t){let{alias:e,params:o,handler:r,state:n}=t;n.isRunning=true,n.startTs=Date.now(),await Le.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});let i=k("cron",`cron:${e}`);try{await r(),Ut(n,o),i.end("success");}catch(s){Ut(n,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 Ut(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Nt(){return Object.values(j).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var zt=new E("_system.cron",{stores:[Le]});var Pe=new E("_system.lock",{stores:[te]});var oe=new w("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function qo(t){if(t.length===0)return;if(!await he("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),r=await oe.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!n.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let m=(await c()||"").toString().trim(),p=15*1024*1024,x=m.length>p?m.slice(0,p)+`
15
- [Output truncated - exceeded size limit]`:m;await oe.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:x,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await oe.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}await Pt("migrations");}}function Ft(t){setTimeout(()=>{qo(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var qt=new E("_system.migration",{stores:[oe]});var Wt=new E("_system.rateLimit",{stores:[ee]});var Zt=new E("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var $e=class{async init(){this.config=await Ko(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[I.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(I.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(r){console.error("Error serving index.html:",r),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 Go(){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 Qo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Ko(){let t=process.cwd(),e=await Go(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Jo.existsSync(Ue.join(t,i))),r=[Ho(),Yo()];if(o){let i=(await import('vite-plugin-eslint')).default;r.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Ue.resolve(t,o)}));}let n=defineConfig({plugins:r,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Ue.resolve(t,"src").replace(/\\/g,"/")}}});return Qo(n,e)}function Yo(){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 Vt=new $e;async function Ht(t,e){let{authToken:o}=await Se(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function Z(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ge(t,e,o){let r=await f.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await je(t);try{if(r){await Ht(e,r._id),h().onAfterLogin?.({provider:o.providerName,user:r,session:n,connectionInfo:i}),h().login?.onSuccess?.(r);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({provider:o.providerName,error:s,session:n,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await f.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 f.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Ht(e,a.insertedId);let c=await f.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(h().onAfterSignup?.({provider:o.providerName,user:c,session:n,connectionInfo:i}),h().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(h().onSignupError?.({provider:o.providerName,error:s,session:n,connectionInfo:i}),h().signup?.onError?.(s)),s}}function ye(t){return !t||typeof t!="string"?null:t}async function tr(t,e,o,r){let n=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:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function or(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 rr(t,e){let o=ye(t.query.code),r=t.query.state,n=t.cookies.authStateGoogle;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!r||!n||r!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGoogle");let i=String(a$1("_system.user.auth.google.clientId")),s=String(a$1("_system.user.auth.google.clientSecret")),a=Z("google");try{let c=await tr(o,i,s,a),l=await or(c.access_token),m={id:l.id,email:l.email,emailVerified:l.verified_email,providerName:"google"};await ge(t,e,m);}catch(c){console.error("Google OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function nr(){let t=Router(),e=(o,r,n)=>{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){r.status(503).json({error:"Google authentication is not configured"});return}n();};return t.get("/api/_internal/auth/google",e,(o,r)=>{let n=String(a$1("_system.user.auth.google.clientId")),i=Z("google"),s=randomBytes(32).toString("hex");r.cookie("authStateGoogle",s,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let a$2=new URL("https://accounts.google.com/o/oauth2/v2/auth");a$2.searchParams.append("client_id",n),a$2.searchParams.append("redirect_uri",i),a$2.searchParams.append("response_type","code"),a$2.searchParams.append("scope","profile email"),a$2.searchParams.append("access_type","online"),a$2.searchParams.append("state",s),r.redirect(a$2.toString());}),t.get("/api/_internal/auth/google/callback",e,rr),t}var Jt=nr;async function ar(t,e,o,r){let n=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:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function cr(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 lr(t,e){let o=ye(t.query.code),r=t.query.state,n=t.cookies.authStateGithub;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!r||!n||r!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGithub");let i=String(a$1("_system.user.auth.github.clientId")),s=String(a$1("_system.user.auth.github.clientSecret")),a=Z("github");try{let c=await ar(o,i,s,a),l=await cr(c.access_token),m=l.email||"";if(!m){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let p={id:String(l.id),email:m,emailVerified:!0,providerName:"github"};await ge(t,e,p);}catch(c){console.error("GitHub OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function dr(){let t=Router(),e=(o,r,n)=>{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){r.status(503).json({error:"GitHub authentication is not configured"});return}n();};return t.get("/api/_internal/auth/github",e,(o,r)=>{let n=String(a$1("_system.user.auth.github.clientId")),i=Z("github"),s=a$1("_system.user.auth.github.scopes"),a$2=s?String(s).split(",").map(m=>m.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex");r.cookie("authStateGithub",c,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",n),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a$2),l.searchParams.append("state",c),r.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,lr),t}var Gt=dr;function Qt(t,e,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&U())try{let{session:l,user:m}=await T(s);a={session:l,user:m};}catch{}let c=k("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:r.query,body:r.body,params:r.params});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.redirect&&n.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([m,p])=>{n.setHeader(m,p);}),n.send(l.data));}catch(l){c.end("error"),l instanceof a$3?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}var Ne=Object.freeze({});function Kt(t){Ne=Object.freeze(Object.assign({},Ne,t));}function we(){return Ne}function mr(t){let e=[];if(!t)return e.push(I.json({limit:"16mb"})),e.push(I.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(I.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(I.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(I.raw(r));}return e}function fr(t,e){for(let o of e)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=mr(s);Object.entries(i).forEach(([c,l])=>{t[c](n,...a,Qt(c,n,l));});}}async function Yt(t,{combinedModules:e,channels:o}){let r=I();r.use(ur()),fr(r,e),r.use(I.json({limit:"16mb"})),r.use(I.urlencoded({extended:true,limit:"16mb"})),r.use(Jt()),r.use(Gt()),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:l}=a.params,m=await je(a);try{let p=await dt(l,a.body.args,m);c.json({data:p,typeMap:a$2(p)});}catch(p){hr(c,l,p);}}),await t.init(),t.middlewares&&r.use(t.middlewares()),r.all("*",(a,c)=>t.handler(a,c)),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=pr.createServer(r),i$1=we()?.provider;i$1&&i$1.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
14
+ `}var Me={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function _t(t,{connectionInfo:e}){let r=I(t.email),o=await f.findOne({"emails.address":r,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!o||!o.authMethods?.password)return Me;let n=w().provider;if(!n)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=Date.now(),a$1=new Date(s),c=new Date(s+a.hours(1));await v.insertOne({userId:o._id,token:i,createdAt:a$1,expiresAt:c});let l=process.env.MODELENCE_SITE_URL||e?.baseUrl,m=`${Ir(l,w().passwordReset?.redirectUrl)}?token=${i}`,k=(w()?.passwordReset?.template||Lr)({email:r,resetUrl:m,name:""}),B=ue(k);return await n.sendEmail({to:r,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:B,html:k}),Me}async function At(t,{}){let e=z$1.string().parse(t.token),r=fe(t.password),o=await v.findOne({token:e});if(!o)throw new Error("Invalid or expired reset token");if(o.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let n=await f.findOne({_id:o.userId});if(!n)throw new Error("User not found");let i=await kr.hash(r,10);return await f.updateOne({_id:n._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Ot=new E("_system.user",{stores:[f,K,O,v],queries:{getOwnProfile:Dt},mutations:{signupWithPassword:kt,loginWithPassword:vt,logout:Tt,resendEmailVerification:Ct,sendResetPasswordToken:_t,resetPassword:At},cronJobs:{updateDisposableEmailList:ht},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.seconds(60),limit:1},{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:St}}]});async function Rt({configSchema:t,cronJobsMetadata:e,stores:r}){let o=process.env.MODELENCE_CONTAINER_ID;if(!o)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(r).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await Ie("/api/connect","POST",{hostname:Pr.hostname(),containerId:o,dataModels:n,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function Mt(){return await Ie("/api/configs","GET")}async function It(){return await Ie("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Ie(t,e,r){let{MODELENCE_SERVICE_ENDPOINT:o,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!o)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${o}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...r?{"Content-Type":"application/json"}:{}},body:r?JSON.stringify(r):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 Le=false,Ur=a.seconds(10);function Lt(){setInterval(async()=>{if(!Le){Le=true;try{await It();}catch(t){console.error("Error syncing status",t);}try{await $r();}catch(t){console.error("Error syncing config",t);}Le=false;}},Ur);}async function $r(){let{configs:t}=await Mt();c(t);}var re=new b("_modelenceLocks",{schema:{resource:d.string(),instanceId:d.string(),acquiredAt:d.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var W={},Pt=a.seconds(10),Ut=randomBytes(32).toString("base64url"),Nr=a.seconds(30);async function he(t,{lockDuration:e=Nr,successfulLockCacheDuration:r=Pt,failedLockCacheDuration:o=Pt,instanceId:n=Ut}={}){let i=Date.now();if(W[t]&&i<W[t].expiresAt)return W[t].value;let s=new Date(i-e);h$1(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:n});try{let a=await re.upsertOne({$or:[{resource:t,instanceId:n},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:n,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return W[t]={value:c,expiresAt:i+(c?r:o)},c?h$1(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:n}):h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),c}catch{return W[t]={value:false,expiresAt:i+o},h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),false}}async function $t(t,{instanceId:e=Ut}={}){let r=await re.deleteOne({resource:t,instanceId:e});return delete W[t],r.deletedCount>0}var zr=a.minutes(1),N={},Pe=null,Ue=new b("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Nt(t,{description:e="",interval:r,timeout:o=zr,handler:n}){if(N[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(Pe)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(r<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(o>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);N[t]={alias:t,params:{description:e,interval:r,timeout:o},handler:n,state:{isRunning:false}};}async function zt(){if(Pe)throw new Error("Cron jobs already started");let t=Object.keys(N);if(t.length>0){let e={alias:{$in:t}},r=await Ue.fetch(e),o=Date.now();r.forEach(n=>{let i=N[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:o);}),Object.values(N).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=o);}),Pe=setInterval(Fr,a.seconds(1));}}async function Fr(){let t=Date.now();await he("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(N).forEach(async r=>{let{params:o,state:n}=r;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await qr(r);});}async function qr(t){let{alias:e,params:r,handler:o,state:n}=t;n.isRunning=true,n.startTs=Date.now(),await Ue.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});let i=k("cron",`cron:${e}`);try{await o(),jt(n,r),i.end("success");}catch(s){jt(n,r);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function jt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Ft(){return Object.values(N).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qt=new E("_system.cron",{stores:[Ue]});var $e=new E("_system.lock",{stores:[re]});var oe=new b("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function Wr(t){if(t.length===0)return;if(!await he("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let r=t.map(({version:s})=>s),o=await oe.fetch({version:{$in:r}}),n=new Set(o.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!n.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let p=(await c()||"").toString().trim(),m=15*1024*1024,x=p.length>m?p.slice(0,m)+`
15
+ [Output truncated - exceeded size limit]`:p;await oe.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:x,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await oe.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}await $t("migrations");}}function Wt(t){setTimeout(()=>{Wr(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Zt=new E("_system.migration",{stores:[oe]});var Bt=new E("_system.rateLimit",{stores:[ee]});var Vt=new E("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var Ne=class{async init(){this.config=await Yr(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[P.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(P.static(this.config.publicDir)),e}handler(e,r){if(this.isDev())try{r.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),r.status(500).send("Internal Server Error");}else r.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Qr(){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 Kr(t,e){let r=mergeConfig(t,e);if(r.plugins&&Array.isArray(r.plugins)){let o=new Set;r.plugins=r.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||o.has(i)?false:(o.add(i),true)}).reverse(),r.plugins.reverse();}return r}async function Yr(){let t=process.cwd(),e=await Qr(),r=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Gr.existsSync(je.join(t,i))),o=[Jr(),Xr()];if(r){let i=(await import('vite-plugin-eslint')).default;o.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:je.resolve(t,r)}));}let n=defineConfig({plugins:o,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":je.resolve(t,"src").replace(/\\/g,"/")}}});return Kr(n,e)}function Xr(){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 Jt=new Ne;async function Gt(t,e){let{authToken:r}=await Ce(e);t.cookie("authToken",r,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function Z(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ge(t,e,r){let o=await f.findOne({[`authMethods.${r.providerName}.id`]:r.id}),{session:n,connectionInfo:i}=await ze(t);try{if(o){await Gt(e,o._id),h().onAfterLogin?.({provider:r.providerName,user:o,session:n,connectionInfo:i}),h().login?.onSuccess?.(o);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({provider:r.providerName,error:s,session:n,connectionInfo:i})),s}try{if(!r.email){e.status(400).json({error:`Email address is required for ${r.providerName} authentication.`});return}if(await f.findOne({"emails.address":r.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 f.insertOne({handle:r.email,status:"active",emails:[{address:r.email,verified:r.emailVerified}],createdAt:new Date,authMethods:{[r.providerName]:{id:r.id}}});await Gt(e,a.insertedId);let c=await f.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(h().onAfterSignup?.({provider:r.providerName,user:c,session:n,connectionInfo:i}),h().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(h().onSignupError?.({provider:r.providerName,error:s,session:n,connectionInfo:i}),h().signup?.onError?.(s)),s}}function ye(t){return !t||typeof t!="string"?null:t}async function ro(t,e,r,o){let n=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:r,redirect_uri:o,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function oo(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 no(t,e){let r=ye(t.query.code),o=t.query.state,n=t.cookies.authStateGoogle;if(!r){e.status(400).json({error:"Missing authorization code"});return}if(!o||!n||o!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGoogle");let i=String(a$1("_system.user.auth.google.clientId")),s=String(a$1("_system.user.auth.google.clientSecret")),a=Z("google");try{let c=await ro(r,i,s,a),l=await oo(c.access_token),p={id:l.id,email:l.email,emailVerified:l.verified_email,providerName:"google"};await ge(t,e,p);}catch(c){console.error("Google OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function io(){let t=Router(),e=(r,o,n)=>{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){o.status(503).json({error:"Google authentication is not configured"});return}n();};return t.get("/api/_internal/auth/google",e,(r,o)=>{let n=String(a$1("_system.user.auth.google.clientId")),i=Z("google"),s=randomBytes(32).toString("hex");o.cookie("authStateGoogle",s,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let a$2=new URL("https://accounts.google.com/o/oauth2/v2/auth");a$2.searchParams.append("client_id",n),a$2.searchParams.append("redirect_uri",i),a$2.searchParams.append("response_type","code"),a$2.searchParams.append("scope","profile email"),a$2.searchParams.append("access_type","online"),a$2.searchParams.append("state",s),o.redirect(a$2.toString());}),t.get("/api/_internal/auth/google/callback",e,no),t}var Qt=io;async function co(t,e,r,o){let n=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:r,code:t,redirect_uri:o})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function lo(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 uo(t,e){let r=ye(t.query.code),o=t.query.state,n=t.cookies.authStateGithub;if(!r){e.status(400).json({error:"Missing authorization code"});return}if(!o||!n||o!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGithub");let i=String(a$1("_system.user.auth.github.clientId")),s=String(a$1("_system.user.auth.github.clientSecret")),a=Z("github");try{let c=await co(r,i,s,a),l=await lo(c.access_token),p=l.email||"";if(!p){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let m={id:String(l.id),email:p,emailVerified:!0,providerName:"github"};await ge(t,e,m);}catch(c){console.error("GitHub OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function mo(){let t=Router(),e=(r,o,n)=>{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){o.status(503).json({error:"GitHub authentication is not configured"});return}n();};return t.get("/api/_internal/auth/github",e,(r,o)=>{let n=String(a$1("_system.user.auth.github.clientId")),i=Z("github"),s=a$1("_system.user.auth.github.scopes"),a$2=s?String(s).split(",").map(p=>p.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex");o.cookie("authStateGithub",c,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",n),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a$2),l.searchParams.append("state",c),o.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,uo),t}var Kt=mo;function Yt(t,e,r){return async(o,n,i)=>{let s=o.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&j())try{let{session:l,user:p}=await T(s);a={session:l,user:p};}catch{}let c=k("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:o.query,body:o.body,params:o.params});try{let l=await r({query:o.query,body:o.body,params:o.params,headers:o.headers,cookies:o.cookies,rawBody:Buffer.isBuffer(o.body)?o.body:void 0,req:o,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.redirect&&n.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([p,m])=>{n.setHeader(p,m);}),n.send(l.data));}catch(l){c.end("error"),l instanceof a$3?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${o.path}`),console.error(l),n.status(500).send(String(l)));}}}var Fe=Object.freeze({});function Xt(t){Fe=Object.freeze(Object.assign({},Fe,t));}function we(){return Fe}function ho(t){let e=[];if(!t)return e.push(P.json({limit:"16mb"})),e.push(P.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let r=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(P.json(r));}if(t.urlencoded!==false){let r=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(P.urlencoded(r));}if(t.raw){let r=typeof t.raw=="object"?t.raw:{},o={limit:r.limit||"16mb",type:r.type||"*/*"};e.push(P.raw(o));}return e}function go(t,e){for(let r of e)for(let o of r.routes){let{path:n,handlers:i,body:s}=o,a=ho(s);Object.entries(i).forEach(([c,l])=>{t[c](n,...a,Yt(c,n,l));});}}async function er(t,{combinedModules:e,channels:r}){let o=P();o.use(po()),go(o,e),o.use(P.json({limit:"16mb"})),o.use(P.urlencoded({extended:true,limit:"16mb"})),o.use(Qt()),o.use(Kt()),o.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:l}=a.params,p=await ze(a);try{let m=await ut(l,a.body.args,p);c.json({data:m,typeMap:a$2(m)});}catch(m){yo(c,l,m);}}),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(a,c)=>t.handler(a,c)),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=fo.createServer(o),i$1=we()?.provider;i$1&&i$1.init({httpServer:n,channels:r});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
16
16
  Application started on ${a}
17
- `);});}async function je(t){let e=M.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=M.object({screenWidth:M.number(),screenHeight:M.number(),windowWidth:M.number(),windowHeight:M.number(),pixelRatio:M.number(),orientation:M.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},r={ip:yr(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!U()){let{session:i,user:s,roles:a}=await T(e);return {clientInfo:o,connectionInfo:r,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:ce()}}function hr(t,e,o){if(o instanceof a$3){o.status>=500&&o.status<600&&console.error(`Error calling ${e}:`,o),t.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=gr(o);}catch(n){console.error(`Error parsing Zod error in ${e}:`,n),r="Validation failed";}t.status(400).send(r);return}console.error(`Error calling ${e}:`,o),t.status(500).send(o instanceof Error?o.message:String(o));}function gr(t){let e=t.flatten(),o=Object.entries(e.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=e.formErrors;return [...o,...r].filter(Boolean).join("; ")}function yr(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 Sr({modules:t=[],roles:e$1={},defaultRoles:o={},server:r=Vt,migrations:n=[],email:i={},auth:s={},websocket:a={}}){Xt.config(),Xt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";Ir().then(()=>{}).catch(()=>{});let m=[_t,et,zt,qt,Wt,Zt,Pe],p=[...m,...t];e(),xr(m),Cr(t),ot(e$1,o);let x=kr(p);d$2(x);let D=vr(p),B=Tr(p);l&&_r(p);let re=Dr(p);if(vt(re),c$1){let{configs:L,environmentId:V,appAlias:H,environmentAlias:J,telemetry:C}=await At({configSchema:x,cronJobsMetadata:l?Nt():void 0,stores:D});c(L),f$1({environmentId:V,appAlias:H,environmentAlias:J,telemetry:C});}else c(Mr(x));ht(i),yt(s),Kt({...a,provider:a.provider||pt});let ne=U();if(ne&&(await nt(),Ar(D)),l&&Ft(n),ne)for(let L of D)L.createIndexes();c$1&&(await g(),Mt()),l&&jt().catch(console.error),await Yt(r,{combinedModules:p,channels:B});}function Cr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))xe(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))it(`${e.name}.${o}`,r);}}function xr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))st(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))at(`${e.name}.${o}`,r);}}function vr(t){return t.flatMap(e=>e.stores)}function Tr(t){return t.flatMap(e=>e.channels)}function Dr(t){return t.flatMap(e=>e.rateLimits)}function kr(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=n;}return e}function _r(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))$t(`${e.name}.${o}`,r);}function Ar(t){let e=le();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Or={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",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 Rr(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 Mr(t){let e=[];for(let[o,r]of Object.entries(Or)){let n=process.env[o],i=t[r];if(n){let s=i?.type??"string";e.push({key:r,type:s,value:Rr(n,s)});}}return e}async function Ir(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Lr(),n=await import('./package-HU7WQD3O.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Lo.hostname(),environmentId:o})});}}async function Lr(){try{let t=Ue.join(process.cwd(),"package.json"),e=await wr.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function eo(t){await A.deleteMany({userId:t}),await v.deleteMany({userId:t});}async function Ur(t){await eo(t),await f.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function $r(t){await eo(t),await f.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var ze=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let r=we().provider;if(!r){j$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:e,data:o});}};function jr(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
18
- export{F as LiveData,E as Module,ze as ServerChannel,w as Store,T as authenticate,$ as consumeRateLimit,xe as createQuery,f as dbUsers,$r as deleteUser,Ur as disableUser,d as schema,jr as sendEmail,Sr as startApp};//# sourceMappingURL=server.js.map
17
+ `);});}async function ze(t){let e=L.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),r=L.object({screenWidth:L.number(),screenHeight:L.number(),windowWidth:L.number(),windowHeight:L.number(),pixelRatio:L.number(),orientation:L.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},o={ip:bo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!j()){let{session:i,user:s,roles:a}=await T(e);return {clientInfo:r,connectionInfo:o,session:i,user:s,roles:a}}return {clientInfo:r,connectionInfo:o,session:null,user:null,roles:le()}}function yo(t,e,r){if(r instanceof a$3){r.status>=500&&r.status<600&&console.error(`Error calling ${e}:`,r),t.status(r.status).send(r.message);return}if(r instanceof Error&&r?.constructor?.name==="ZodError"&&"errors"in r){let o="";try{o=wo(r);}catch(n){console.error(`Error parsing Zod error in ${e}:`,n),o="Validation failed";}t.status(400).send(o);return}console.error(`Error calling ${e}:`,r),t.status(500).send(r instanceof Error?r.message:String(r));}function wo(t){let e=t.flatten(),r=Object.entries(e.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),o=e.formErrors;return [...r,...o].filter(Boolean).join("; ")}function bo(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let r=t.ip||t.socket?.remoteAddress;if(r)return r.startsWith("::ffff:")?r.substring(7):r}async function xo({modules:t=[],roles:e$1={},defaultRoles:r={},server:o=Jt,migrations:n=[],email:i={},auth:s={},websocket:a={}}){tr.config(),tr.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";Po().then(()=>{}).catch(()=>{});let p=[Ot,tt,qt,Zt,Bt,Vt,$e],m=[...p,...t];e(),To(p),vo(t),ot(e$1,r);let x=Ao(m);d$2(x);let k=Do(m),B=ko(m);l&&Oo(m);let ne=_o(m);if(Et(ne),c$1){let{configs:U,environmentId:V,appAlias:H,environmentAlias:J,telemetry:C}=await Rt({configSchema:x,cronJobsMetadata:l?Ft():void 0,stores:k});c(U),f$1({environmentId:V,appAlias:H,environmentAlias:J,telemetry:C});}else c(Lo(x));gt(i),wt(s),Xt({...a,provider:a.provider||pt});let ie=j();if(ie&&(await it(),Ro(k)),l&&Wt(n),ie)for(let U of k)U.createIndexes();c$1&&(await g(),Lt()),l&&zt().catch(console.error),await er(o,{combinedModules:m,channels:B});}function vo(t){for(let e of t){for(let[r,o]of Object.entries(e.queries))ve(`${e.name}.${r}`,o);for(let[r,o]of Object.entries(e.mutations))st(`${e.name}.${r}`,o);}}function To(t){for(let e of t){for(let[r,o]of Object.entries(e.queries))at(`${e.name}.${r}`,o);for(let[r,o]of Object.entries(e.mutations))ct(`${e.name}.${r}`,o);}}function Do(t){return t.flatMap(e=>e.stores)}function ko(t){return t.flatMap(e=>e.channels)}function _o(t){return t.flatMap(e=>e.rateLimits)}function Ao(t){let e={};for(let r of t)for(let[o,n]of Object.entries(r.configSchema)){let i=`${r.name}.${o}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${r.name})`);e[i]=n;}return e}function Oo(t){for(let e of t)for(let[r,o]of Object.entries(e.cronJobs))Nt(`${e.name}.${r}`,o);}function Ro(t){let e=de();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let r of t)r.init(e);}var Mo={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",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 Io(t,e){if(e==="number"){let r=Number(t);if(isNaN(r))throw new Error(`Invalid number value for config: ${t}`);return r}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 Lo(t){let e=[];for(let[r,o]of Object.entries(Mo)){let n=process.env[r],i=t[o];if(n){let s=i?.type??"string";e.push({key:o,type:s,value:Io(n,s)});}}return e}async function Po(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",r=process.env.MODELENCE_ENVIRONMENT_ID,o=await Uo(),n=await import('./package-AQK4I5AP.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:o.name,version:n.default.version,localHostname:Pr.hostname(),environmentId:r})});}}async function Uo(){try{let t=je.join(process.cwd(),"package.json"),e=await Eo.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function rr(t){await O.deleteMany({userId:t}),await v.deleteMany({userId:t});}async function jo(t){await rr(t),await f.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function No(t){await rr(t),await f.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var qe=class{constructor(e,r){this.category=e,this.canAccessChannel=r||null;}broadcast(e,r){let o=we().provider;if(!o){j$1("Websockets provider should be added to startApp",{});return}o.broadcast({category:this.category,id:e,data:r});}};function zo(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)}
18
+ export{q as LiveData,E as Module,qe as ServerChannel,b as Store,T as authenticate,D as consumeRateLimit,ve as createQuery,f as dbUsers,No as deleteUser,jo as disableUser,d as schema,zo as sendEmail,xo as startApp};//# sourceMappingURL=server.js.map
19
19
  //# sourceMappingURL=server.js.map