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