@modelence/react-query 1.2.1 → 1.2.3

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.
Files changed (30) hide show
  1. package/.yalc/modelence/dist/bin/modelence.js +2 -2
  2. package/.yalc/modelence/dist/bin/modelence.js.map +1 -1
  3. package/.yalc/modelence/dist/chunk-KTGXKFME.js +3 -0
  4. package/.yalc/modelence/dist/chunk-KTGXKFME.js.map +1 -0
  5. package/.yalc/modelence/dist/chunk-PB6WQQ4L.js +3 -0
  6. package/.yalc/modelence/dist/chunk-PB6WQQ4L.js.map +1 -0
  7. package/.yalc/modelence/dist/client.d.ts +1 -1
  8. package/.yalc/modelence/dist/client.js +1 -1
  9. package/.yalc/modelence/dist/client.js.map +1 -1
  10. package/.yalc/modelence/dist/index.d.ts +1 -1
  11. package/.yalc/modelence/dist/{package-3YQBVIVQ.js → package-46B3WEOU.js} +2 -2
  12. package/.yalc/modelence/dist/{package-3YQBVIVQ.js.map → package-46B3WEOU.js.map} +1 -1
  13. package/.yalc/modelence/dist/server.d.ts +60 -30
  14. package/.yalc/modelence/dist/server.js +7 -7
  15. package/.yalc/modelence/dist/server.js.map +1 -1
  16. package/.yalc/modelence/dist/telemetry.js +1 -1
  17. package/.yalc/modelence/dist/{types-Ds1ESQSs.d.ts → types-BOFsm7A2.d.ts} +50 -1
  18. package/.yalc/modelence/dist/{types-WgRbQ-tj.d.ts → types-V9eDnP35.d.ts} +41 -40
  19. package/.yalc/modelence/dist/types.d.ts +3 -3
  20. package/.yalc/modelence/package.json +5 -2
  21. package/.yalc/modelence/yalc.sig +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/package.json +2 -2
  25. package/src/index.ts +14 -4
  26. package/yalc.lock +2 -2
  27. package/.yalc/modelence/dist/chunk-3YAV3UUU.js +0 -3
  28. package/.yalc/modelence/dist/chunk-3YAV3UUU.js.map +0 -1
  29. package/.yalc/modelence/dist/chunk-DVECB2TP.js +0 -3
  30. package/.yalc/modelence/dist/chunk-DVECB2TP.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { A as AppServer } from './index-CwdohC5n.js';
2
- import { C as ConfigSchema, S as ServerChannel, U as User, d as Session, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, A as AppConfig, e as UserInfo, f as Role } from './types-Ds1ESQSs.js';
3
- import { S as Store, M as MethodDefinition, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, b as ConnectionInfo, I as InferDocumentType, c as RateLimitType, d as EmailPayload } from './types-WgRbQ-tj.js';
4
- export { H as HttpMethod, e as RouteHandler, f as RouteParams, g as RouteResponse, s as schema } from './types-WgRbQ-tj.js';
2
+ import { M as MethodDefinition, C as ConfigSchema, S as ServerChannel, A as AuthSuccessProps, d as AuthErrorProps, U as User, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, e as AppConfig, f as Session, g as UserInfo, h as Role } from './types-BOFsm7A2.js';
3
+ import { S as Store, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, I as InferDocumentType, b as RateLimitType, c as EmailPayload } from './types-V9eDnP35.js';
4
+ export { H as HttpMethod, d as RouteHandler, e as RouteParams, f as RouteResponse, s as schema } from './types-V9eDnP35.js';
5
5
  import { ObjectId as ObjectId$1 } from 'mongodb';
6
6
  export { ObjectId } from 'mongodb';
7
7
  import * as zod from 'zod';
@@ -145,26 +145,12 @@ type AuthOption = {
145
145
  * ```
146
146
  */
147
147
  type AuthConfig = {
148
- onAfterLogin?: (props: {
149
- user: User;
150
- session: Session | null;
151
- connectionInfo: ConnectionInfo;
152
- }) => void;
153
- onLoginError?: (props: {
154
- error: Error;
155
- session: Session | null;
156
- connectionInfo: ConnectionInfo;
157
- }) => void;
158
- onAfterSignup?: (props: {
159
- user: User;
160
- session: Session | null;
161
- connectionInfo: ConnectionInfo;
162
- }) => void;
163
- onSignupError?: (props: {
164
- error: Error;
165
- session: Session | null;
166
- connectionInfo: ConnectionInfo;
167
- }) => void;
148
+ onAfterLogin?: (props: AuthSuccessProps) => void;
149
+ onLoginError?: (props: AuthErrorProps) => void;
150
+ onAfterSignup?: (props: AuthSuccessProps) => void;
151
+ onSignupError?: (props: AuthErrorProps) => void;
152
+ onAfterEmailVerification?: (props: AuthSuccessProps) => void;
153
+ onEmailVerificationError?: (props: AuthErrorProps) => void;
168
154
  /** deprecated: use onAfterLogin and onLoginError */
169
155
  login?: AuthOption;
170
156
  /** deprecated: user onAfterSignup and onSignupError */
@@ -188,21 +174,65 @@ type AppOptions = {
188
174
  declare function startApp({ modules, roles, defaultRoles, server, migrations, email, auth, websocket, }: AppOptions): Promise<void>;
189
175
 
190
176
  /**
191
- * Publish function provided to live query handlers.
192
- * Call this to send data to the subscribed client.
177
+ * Publish function provided to watch handlers.
178
+ * Call this to trigger a re-fetch and send updated data to the client.
193
179
  */
194
- type LiveQueryPublish<T = unknown> = (data: T) => void;
180
+ type LiveQueryPublish = () => void;
195
181
  /**
196
- * Cleanup function returned by live query handlers.
182
+ * Cleanup function returned by watch handlers.
197
183
  * Called when the client unsubscribes.
198
184
  */
199
185
  type LiveQueryCleanup = () => void;
200
186
  /**
201
- * Context provided to live query handlers.
187
+ * Context passed to watch handlers.
202
188
  */
203
- interface LiveQueryContext {
189
+ interface WatchContext {
204
190
  publish: LiveQueryPublish;
205
191
  }
192
+ /**
193
+ * Watch function that sets up real-time monitoring.
194
+ * Receives a context with publish callback to trigger re-fetches.
195
+ * Returns a cleanup function.
196
+ */
197
+ type LiveQueryWatch = (context: WatchContext) => LiveQueryCleanup | void;
198
+ /**
199
+ * Configuration for creating LiveData.
200
+ */
201
+ interface LiveDataConfig<T = unknown> {
202
+ /**
203
+ * Fetches the current data. Called initially and whenever watch triggers publish.
204
+ */
205
+ fetch: () => Promise<T> | T;
206
+ /**
207
+ * Sets up watching for changes. Receives publish callback and returns cleanup.
208
+ */
209
+ watch: LiveQueryWatch;
210
+ }
211
+ /**
212
+ * LiveData object returned by live query handlers.
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * getTodos({ userId }, context) {
217
+ * return new LiveData({
218
+ * fetch: async () => await dbTodos.fetch({ userId }),
219
+ * watch: ({ publish }) => {
220
+ * // Subscribe to changes and call publish when data changes
221
+ * listener.onChange(publish);
222
+ *
223
+ * return () => {
224
+ * // Cleanup function to unsubscribe from changes
225
+ * };
226
+ * }
227
+ * });
228
+ * }
229
+ * ```
230
+ */
231
+ declare class LiveData<T = unknown> {
232
+ readonly fetch: () => Promise<T> | T;
233
+ readonly watch: LiveQueryWatch;
234
+ constructor(config: LiveDataConfig<T>);
235
+ }
206
236
 
207
237
  declare function createQuery<T extends unknown[]>(name: string, methodDef: MethodDefinition<T>): void;
208
238
 
@@ -566,4 +596,4 @@ declare function authenticate(authToken: string | null): Promise<{
566
596
 
567
597
  declare function sendEmail(payload: EmailPayload): Promise<void> | undefined;
568
598
 
569
- export { type AppOptions, type AuthConfig, type AuthOption, type CloudBackendConnectResponse, CronJobInputParams, type LiveQueryCleanup, type LiveQueryContext, type LiveQueryPublish, Module, RateLimitRule, RateLimitType, RouteDefinition, ServerChannel, Store, UserInfo, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteUser, disableUser, getConfig, sendEmail, startApp };
599
+ export { type AppOptions, type AuthConfig, type AuthOption, type CloudBackendConnectResponse, CronJobInputParams, LiveData, type LiveDataConfig, type LiveQueryCleanup, type LiveQueryPublish, type LiveQueryWatch, Module, RateLimitRule, RateLimitType, RouteDefinition, ServerChannel, Store, UserInfo, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteUser, disableUser, getConfig, sendEmail, startApp };
@@ -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,g,j as j$1,a as a$1,i,k as k$1,h,l}from'./chunk-DVECB2TP.js';export{a as getConfig}from'./chunk-DVECB2TP.js';import Jt from'dotenv';import hn from'fs/promises';import Io from'os';import Re 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 k,{z as z$1}from'zod';import xo from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Jo from'@vitejs/plugin-react';import Ho from'fs';import R,{Router}from'express';import ln from'cookie-parser';import dn from'http';var S=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:c=[],channels:l=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=c,this.channels=l;}};function T(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:T(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=T(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...T(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...T(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(T)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:T(o.schema)}return {type:"custom",typeName:e.typeName}}function Y(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?T(r):Y(r)):typeof n=="object"&&"_def"in n?e[o]=T(n):e[o]=Y(n);return e}var w=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return Y(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===86&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Xt=z$1.string.bind(z$1),eo=z$1.number.bind(z$1),to=z$1.date.bind(z$1),oo=z$1.boolean.bind(z$1),no=z$1.array.bind(z$1),ro=z$1.object.bind(z$1),io=z$1.enum.bind(z$1),d={string:Xt,number:eo,date:to,boolean:oo,array:no,object:ro,enum:io,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 j=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 We(t){let e=t?await j.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await fe()}async function Be(t,e){await j.updateOne({authToken:t},{$set:{userId:e}});}async function Je(t){await j.updateOne({authToken:t},{$set:{userId:null}});}async function fe(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await j.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function ao(t){let e=Date.now(),o=new Date(e+a.days(7));await j.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var He=new S("_system.session",{stores:[j],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 ao(e);}}});var m=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}]}),W=new w("_modelenceDisposableEmailDomains",{schema:{domain:d.string(),addedAt:d.date()},indexes:[{key:{domain:1},unique:true}]}),v=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}]}),E=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 Ve=new Map,$={authenticated:null,unauthenticated:null};function Qe(t,e){$.authenticated=e.authenticated,$.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Ve.set(o,n);}function X(){return $.unauthenticated?[$.unauthenticated]:[]}function Ge(){return $.authenticated?[$.authenticated]:[]}function he(t,e){let o=e.find(n=>!co(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function co(t,e){for(let o of t){let n=Ve.get(o);if(n&&n.permissions.includes(e))return true}return false}async function M(t){let e=await We(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Ge():X();return {user:n,session:e,roles:r}}var D=null;async function Ke(){if(D)return D;let t=A();if(!t)throw new Error("MongoDB URI is not set");D=new MongoClient(t,{maxPoolSize:20});try{return await D.connect(),await D.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),D}catch(e){throw console.error(e),D=null,e}}function A(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function ee(){return D}function mo(){return typeof window!="object"}function _(){if(!mo())throw new Error("This function can only be called on the server")}function te(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var oe={};function ge(t,e){return _(),tt(t),ne("query",t,e)}function Ye(t,e){return _(),tt(t),ne("mutation",t,e)}function Xe(t,e){return _(),ot(t),ne("query",t,e)}function et(t,e){return _(),ot(t),ne("mutation",t,e)}function tt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ot(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function ne(t,e,o){if(_(),oe[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];oe[e]={type:t,name:e,handler:n,permissions:r};}async function nt(t,e,o){_();let n=oe[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=k$1("method",`method:${t}`,{type:r,args:e}),a;try{he(o.roles,n.permissions),a=await i(e,o);}catch(c){throw s.end("error"),c}return s.end(),a}async function rt(t,e,o,n){_();let r=oe[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:s}=r;if(i!=="query")throw new Error("Live methods are only supported for queries");let a=k$1("method",`method:${t}:live`,{type:i,args:e});try{he(o.roles,r.permissions);let c={...o,...n},l=await s(e,c);if(a.end(),l!==void 0&&typeof l!="function")throw new Error(`Live query handler for '${t}' must return a cleanup function or undefined, not data. Use publish() to send data to the client.`);return l||null}catch(c){throw a.end("error"),c}}var po=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({})}),fo=z$1.object({subscriptionId:z$1.string().min(1)}),B=new Map;function ho(t){let e=B.get(t.id);return e||(e=new Map,B.set(t.id,e)),e}async function ye(t,e){let o=po.safeParse(e);if(!o.success){t.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${o.error.message}`});return}let{subscriptionId:n,method:r,args:i}=o.data;try{let s=p=>{t.emit("liveQueryData",{subscriptionId:n,data:p,typeMap:a$2(p)});},a=await rt(r,i,t.data,{publish:s}),c=ho(t),l=c.get(n);if(l?.cleanup)try{l.cleanup();}catch(p){console.error("[LiveQuery] Error cleaning up existing subscription:",p);}c.set(n,{cleanup:a});}catch(s){console.error(`[LiveQuery] Error in ${r}:`,s),t.emit("liveQueryError",{subscriptionId:n,error:s instanceof Error?s.message:String(s)});}}function we(t,e){let o=fo.safeParse(e);if(!o.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${o.error.message}`);return}let{subscriptionId:n}=o.data,r=B.get(t.id);if(!r)return;let i=r.get(n);if(i){if(i.cleanup)try{i.cleanup();}catch(s){console.error("[LiveQuery] Error in cleanup:",s);}r.delete(n);}}function be(t){let e=B.get(t.id);if(e){for(let o of e.values())if(o.cleanup)try{o.cleanup();}catch(n){console.error("[LiveQuery] Error in cleanup on disconnect:",n);}B.delete(t.id);}}var J=null,wo="_modelenceSocketio";async function bo({httpServer:t,channels:e}){let o=ee();console.log("Initializing Socket.IO server...");let n=null;if(o){n=o.db().collection(wo);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}}J=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),J.on("error",r=>{console.error("Socket.IO error:",r);}),J.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await M(s);}finally{i();}}),J.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected"),be(r);}),r.on("joinChannel",async i=>{let[s,...a]=i.split(":"),c=a.join(":");for(let l of e)if(l.category===s){!l.canAccessChannel||await l.canAccessChannel({id:c,...r.data})?(r.join(i),r.emit("joinedChannel",i)):r.emit("channelAccessDenied",i);return}console.warn(`Unknown channel: ${s}`);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);}),r.on("subscribeLiveQuery",i=>ye(r,i)),r.on("unsubscribeLiveQuery",i=>we(r,i));}),console.log("Socket.IO server initialized");}function So({category:t,id:e,data:o}){J?.to(`${t}:${e}`).emit(t,o);}var it={init:bo,broadcast:So};async function st(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await W.findOne({domain:o})}var at={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
- `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await W.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Se=Object.freeze({});function ct(t){Se=Object.freeze(Object.assign({},Se,t));}function b(){return Se}function lt({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,g,j as j$1,a as a$1,i,k as k$1,h as h$1,l}from'./chunk-PB6WQQ4L.js';export{a as getConfig}from'./chunk-PB6WQQ4L.js';import Jt from'dotenv';import yr from'fs/promises';import Lo from'os';import Oe from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes,randomUUID}from'crypto';import _,{z as z$1}from'zod';import vo from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Jo from'@vitejs/plugin-react';import Go from'fs';import A,{Router}from'express';import ur from'cookie-parser';import pr from'http';var S=class{constructor(e,{stores:o=[],queries:r={},mutations:n={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:c=[]}){this.name=e,this.stores=o,this.queries=r,this.mutations=n,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=c;}};function v(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:v(e.type)};if(e.typeName==="ZodObject"){let r=e.shape(),n={};for(let[i,s]of Object.entries(r))n[i]=v(s);return {type:"object",items:n}}if(e.typeName==="ZodOptional")return {...v(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...v(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(v)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:v(o.schema)}return {type:"custom",typeName:e.typeName}}function X(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?v(n):X(n)):typeof r=="object"&&"_def"in r?e[o]=v(r):e[o]=X(r);return e}var b=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 X(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(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===86&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let 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 eo=z$1.string.bind(z$1),to=z$1.number.bind(z$1),oo=z$1.date.bind(z$1),ro=z$1.boolean.bind(z$1),no=z$1.array.bind(z$1),io=z$1.object.bind(z$1),so=z$1.enum.bind(z$1),d={string:eo,number:to,date:oo,boolean:ro,array:no,object:io,enum:so,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 j=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 Be(t){let e=t?await j.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await he()}async function Ve(t,e){await j.updateOne({authToken:t},{$set:{userId:e}});}async function Je(t){await j.updateOne({authToken:t},{$set:{userId:null}});}async function he(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),r=new Date(o+a.days(7));return await j.insertOne({authToken:e,createdAt:new Date(o),expiresAt:r,userId:t}),{authToken:e,expiresAt:r,userId:t}}async function co(t){let e=Date.now(),o=new Date(e+a.days(7));await j.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Ge=new S("_system.session",{stores:[j],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 co(e);}}});var p=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}]}),B=new b("_modelenceDisposableEmailDomains",{schema:{domain:d.string(),addedAt:d.date()},indexes:[{key:{domain:1},unique:true}]}),T=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}]}),C=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 Qe=new Map,$={authenticated:null,unauthenticated:null};function He(t,e){$.authenticated=e.authenticated,$.unauthenticated=e.unauthenticated;for(let[o,r]of Object.entries(t))Qe.set(o,r);}function ee(){return $.unauthenticated?[$.unauthenticated]:[]}function Ke(){return $.authenticated?[$.authenticated]:[]}function ge(t,e){let o=e.find(r=>!lo(t,r));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function lo(t,e){for(let o of t){let r=Qe.get(o);if(r&&r.permissions.includes(e))return true}return false}async function R(t){let e=await Be(t),o=e.userId?await p.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?Ke():ee();return {user:r,session:e,roles:n}}var D=null;async function Ye(){if(D)return D;let t=M();if(!t)throw new Error("MongoDB URI is not set");D=new MongoClient(t,{maxPoolSize:20});try{return await D.connect(),await D.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),D}catch(e){throw console.error(e),D=null,e}}function M(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function te(){return D}var N=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function mo(){return typeof window!="object"}function k(){if(!mo())throw new Error("This function can only be called on the server")}function oe(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var re={};function ye(t,e){return k(),ot(t),ne("query",t,e)}function Xe(t,e){return k(),ot(t),ne("mutation",t,e)}function et(t,e){return k(),rt(t),ne("query",t,e)}function tt(t,e){return k(),rt(t),ne("mutation",t,e)}function ot(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function rt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function ne(t,e,o){if(k(),re[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??[];re[e]={type:t,name:e,handler:r,permissions:n};}async function nt(t,e,o){k();let r=re[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=r,s=k$1("method",`method:${t}`,{type:n,args:e}),a;try{ge(o.roles,r.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}async function it(t,e,o){k();let r=re[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$1("method",`method:${t}:live`,{type:n,args:e}),a;try{if(ge(o.roles,r.permissions),a=await i(e,o),!(a instanceof N))throw new Error(`Live query handler for '${t}' must return a LiveData object with fetch and watch functions.`)}catch(l){throw s.end("error"),l}return s.end(),a}var fo=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({})}),ho=z$1.object({subscriptionId:z$1.string().min(1)}),V=new Map;function go(t){let e=V.get(t.id);return e||(e=new Map,V.set(t.id,e)),e}async function we(t,e){let o=fo.safeParse(e);if(!o.success){t.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${o.error.message}`});return}let{subscriptionId:r,method:n,args:i}=o.data,s=go(t),a=s.get(r);if(a)if(a.cleanup)try{a.cleanup();}catch(c){console.error("[LiveQuery] Error cleaning up existing subscription:",c);}else a.aborted=true;let l={cleanup:null};s.set(r,l);try{let c=await it(n,i,t.data),m=async()=>{let w=await c.fetch();t.emit("liveQueryData",{subscriptionId:r,data:w,typeMap:a$2(w)});};await m();let f=c.watch({publish:()=>{m().catch(w=>{console.error(`[LiveQuery] Error re-fetching ${n}:`,w),t.emit("liveQueryError",{subscriptionId:r,error:w instanceof Error?w.message:String(w)});});}});if(l.aborted){if(f)try{f();}catch(w){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",w);}return}l.cleanup=f||null;}catch(c){s.delete(r),console.error(`[LiveQuery] Error in ${n}:`,c),t.emit("liveQueryError",{subscriptionId:r,error:c instanceof Error?c.message:String(c)});}}function be(t,e){let o=ho.safeParse(e);if(!o.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${o.error.message}`);return}let{subscriptionId:r}=o.data,n=V.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 Ee(t){let e=V.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;V.delete(t.id);}}var J=null,bo="_modelenceSocketio";async function Eo({httpServer:t,channels:e}){let o=te();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);}}J=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:r?createAdapter(r):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),J.on("error",n=>{console.error("Socket.IO error:",n);}),J.use(async(n,i)=>{let s=n.handshake.auth.token;try{n.data=await R(s);}finally{i();}}),J.on("connection",n=>{console.log("Socket.IO client connected"),n.on("disconnect",()=>{console.log("Socket.IO client disconnected"),Ee(n);}),n.on("joinChannel",async i=>{let[s]=i.split(":"),a=false;for(let l of e)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=>we(n,i)),n.on("unsubscribeLiveQuery",i=>be(n,i));}),console.log("Socket.IO server initialized");}function So({category:t,id:e,data:o}){J?.to(`${t}:${e}`).emit(t,o);}var st={init:Eo,broadcast:So};async function at(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await B.findOne({domain:o})}var ct={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 B.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Se=Object.freeze({});function lt(t){Se=Object.freeze(Object.assign({},Se,t));}function E(){return Se}function dt({name:t,email:e,verificationUrl:o}){return `
3
3
  <p>Hi${t?` ${t}`:""},</p>
4
4
  <p>Please verify your email address ${e} by clicking the link below:</p>
5
5
  <p><a href="${o}">${o}</a></p>
6
6
  <p>If you did not request this, please ignore this email.</p>
7
- `}async function dt(t){let e=process.env.MODELENCE_SITE_URL,o=b().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await v.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await m.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await m.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await m.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await v.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function re({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(b().provider){let n=b().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await v.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,c=(b()?.verification?.template||lt)({name:"",email:e,verificationUrl:s}),l=te(c);await n?.sendEmail({to:e,from:b()?.from||"noreply@modelence.com",subject:b()?.verification?.subject||"Verify your email address",text:l,html:c});}}function ie(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function N(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var Ee=Object.freeze({});function mt(t){Ee=Object.freeze(Object.assign({},Ee,t));}function y(){return Ee}async function ft(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await L({bucket:"signin",type:"ip",value:r});let i=N(t.email),s=z$1.string().parse(t.password),a=await m.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),c=a?.authMethods?.password?.hash;if(!c)throw pt();if(!a.emails?.find(f=>f.address===i)?.verified&&b()?.provider){if(r)try{await L({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 re({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await xo.compare(s,c))throw pt();return await Be(o.authToken,a._id),y().onAfterLogin?.({user:a,session:o,connectionInfo:n}),y().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(y().onLoginError?.({error:r,session:o,connectionInfo:n}),y().login?.onError?.(r)),r}}async function ht(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Je(e.authToken);}function pt(){return new Error("Incorrect email/password combination")}async function gt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var H=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 Ce=[];function yt(t){if(Ce.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Ce=t;}async function L(t){let{bucket:e,type:o,value:n}=t,r=Ce.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await vo(i,n);}async function vo(t,e,o){let n=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),r=await H.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}=r?Do(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await H.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},c);}function Do(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function wt(t,{user:e,session:o,connectionInfo:n}){try{let r=N(t.email),i=ie(t.password),s=n?.ip;if(s&&await L({bucket:"signupAttempt",type:"ip",value:s}),await st(r))throw new Error("Please use a permanent email address");let a=await m.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let f=a.emails?.find(C=>C.address===r);throw a.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${f?.address}`)}s&&await L({bucket:"signup",type:"ip",value:s});let c=await xo.hash(i,10),l=await m.insertOne({handle:r,status:"active",emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:c}}}),p=await m.findOne({_id:l.insertedId},{readPreference:"primary"});if(!p)throw new Error("User not found");return await re({userId:l?.insertedId,email:r,baseUrl:n?.baseUrl}),y().onAfterSignup?.({user:p,session:o,connectionInfo:n}),y().signup?.onSuccess?.(p),l.insertedId}catch(r){throw r instanceof Error&&(y().onSignupError?.({error:r,session:o,connectionInfo:n}),y().signup?.onError?.(r)),r}}function Mo(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function Ao({email:t,resetUrl:e}){return `
7
+ `}var Ce=Object.freeze({});function ut(t){Ce=Object.freeze(Object.assign({},Ce,t));}function h(){return Ce}async function pt(t){let e=process.env.MODELENCE_SITE_URL,o=E().emailVerifiedRedirectUrl||e||"/";try{let r=z$1.string().parse(t.query.token),n=await T.findOne({token:r,expiresAt:{$gt:new Date}});if(!n)throw new Error("Invalid or expired verification token");if(!await p.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 p.updateOne({_id:n.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await p.findOne({_id:n.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await T.deleteOne({_id:n._id}),h().onAfterEmailVerification?.({provider:"email",user:await p.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 ie({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(E().provider){let r=E().provider,n=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await T.insertOne({userId:t,email:e,token:n,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${n}`,l=(E()?.verification?.template||dt)({name:"",email:e,verificationUrl:s}),c=oe(l);await r?.sendEmail({to:e,from:E()?.from||"noreply@modelence.com",subject:E()?.verification?.subject||"Verify your email address",text:c,html:l});}}function se(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function z(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}async function ht(t,{user:e,session:o,connectionInfo:r}){try{if(!o)throw new Error("Session is not initialized");let n=r?.ip;n&&await L({bucket:"signin",type:"ip",value:n});let i=z(t.email),s=z$1.string().parse(t.password),a=await p.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw ft();if(!a.emails?.find(f=>f.address===i)?.verified&&E()?.provider){if(n)try{await L({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 ie({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,l))throw ft();return await Ve(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}}}catch(n){throw n instanceof Error&&(h().onLoginError?.({provider:"email",error:n,session:o,connectionInfo:r}),h().login?.onError?.(n)),n}}async function gt(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Je(e.authToken);}function ft(){return new Error("Incorrect email/password combination")}async function yt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await p.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var G=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 xe=[];function wt(t){if(xe.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");xe=t;}async function L(t){let{bucket:e,type:o,value:r}=t,n=xe.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 G.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=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 G.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}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 bt(t,{user:e,session:o,connectionInfo:r}){try{let n=z(t.email),i=se(t.password),s=r?.ip;if(s&&await L({bucket:"signupAttempt",type:"ip",value:s}),await at(n))throw new Error("Please use a permanent email address");let a=await p.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(a){let f=a.emails?.find(w=>w.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: ${f?.address}`)}s&&await L({bucket:"signup",type:"ip",value:s});let l=await vo.hash(i,10),c=await p.insertOne({handle:n,status:"active",emails:[{address:n,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),m=await p.findOne({_id:c.insertedId},{readPreference:"primary"});if(!m)throw new Error("User not found");return await ie({userId:c?.insertedId,email:n,baseUrl:r?.baseUrl}),h().onAfterSignup?.({provider:"email",user:m,session:o,connectionInfo:r}),h().signup?.onSuccess?.(m),c.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 `
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 xe={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function bt(t,{connectionInfo:e}){let o=N(t.email),n=await m.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return xe;let r=b().provider;if(!r)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 E.insertOne({userId:n._id,token:i,createdAt:a$1,expiresAt:c});let l=process.env.MODELENCE_SITE_URL||e?.baseUrl,f=`${Mo(l,b().passwordReset?.redirectUrl)}?token=${i}`,U=(b()?.passwordReset?.template||Ao)({email:o,resetUrl:f,name:""}),de=te(U);return await r.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:de,html:U}),xe}async function St(t,{}){let e=z$1.string().parse(t.token),o=ie(t.password),n=await E.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await E.deleteOne({token:e}),new Error("Reset token has expired");let r=await m.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await xo.hash(o,10);return await m.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await E.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Et=new S("_system.user",{stores:[m,W,v,E],queries:{getOwnProfile:gt},mutations:{signupWithPassword:wt,loginWithPassword:ft,logout:ht,sendResetPasswordToken:bt,resetPassword:St},cronJobs:{updateDisposableEmailList:at},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:dt}}]});async function Ct({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await Te("/api/connect","POST",{hostname:Io.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function xt(){return await Te("/api/configs","GET")}async function Tt(){return await Te("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Te(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var ve=false,Lo=a.seconds(10);function vt(){setInterval(async()=>{if(!ve){ve=true;try{await Tt();}catch(t){console.error("Error syncing status",t);}try{await Po();}catch(t){console.error("Error syncing config",t);}ve=false;}},Lo);}async function Po(){let{configs:t}=await xt();c(t);}var V=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 z={},Dt=a.seconds(10),_t=randomBytes(32).toString("base64url"),jo=a.seconds(30);async function se(t,{lockDuration:e=jo,successfulLockCacheDuration:o=Dt,failedLockCacheDuration:n=Dt,instanceId:r=_t}={}){let i=Date.now();if(z[t]&&i<z[t].expiresAt)return z[t].value;let s=new Date(i-e);h(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:r});try{let a=await V.upsertOne({$or:[{resource:t,instanceId:r},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:r,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return z[t]={value:c,expiresAt:i+(c?o:n)},c?h(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:r}):h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),c}catch{return z[t]={value:false,expiresAt:i+n},h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),false}}async function kt(t,{instanceId:e=_t}={}){let o=await V.deleteOne({resource:t,instanceId:e});return delete z[t],o.deletedCount>0}var $o=a.minutes(1),P={},De=null,_e=new w("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ot(t,{description:e="",interval:o,timeout:n=$o,handler:r}){if(P[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(De)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);P[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Mt(){if(De)throw new Error("Cron jobs already started");let t=Object.keys(P);if(t.length>0){let e={alias:{$in:t}},o=await _e.fetch(e),n=Date.now();o.forEach(r=>{let i=P[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:n);}),Object.values(P).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=n);}),De=setInterval(No,a.seconds(1));}}async function No(){let t=Date.now();await se("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(P).forEach(async o=>{let{params:n,state:r}=o;if(r.isRunning){r.startTs&&r.startTs+n.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await zo(o);});}async function zo(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now(),await _e.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});let i=k$1("cron",`cron:${e}`);try{await n(),Rt(r,o),i.end("success");}catch(s){Rt(r,o);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function Rt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function At(){return Object.values(P).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var It=new S("_system.cron",{stores:[_e]});var ke=new S("_system.lock",{stores:[V]});var Q=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 se("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),n=await Q.fetch({version:{$in:o}}),r=new Set(n.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!r.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let p=(await c()||"").toString().trim(),f=15*1024*1024,C=p.length>f?p.slice(0,f)+`
15
- [Output truncated - exceeded size limit]`:p;await Q.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:C,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await Q.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 kt("migrations");}}function Lt(t){setTimeout(()=>{qo(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Pt=new S("_system.migration",{stores:[Q]});var Ut=new S("_system.rateLimit",{stores:[H]});var jt=new S("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var Oe=class{async init(){this.config=await Go(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[R.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(R.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Vo(){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 n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Go(){let t=process.cwd(),e=await Vo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Ho.existsSync(Re.join(t,i))),n=[Jo(),Ko()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Re.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Re.resolve(t,"src").replace(/\\/g,"/")}}});return Qo(r,e)}function Ko(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t}}}var Nt=new Oe;async function zt(t,e){let{authToken:o}=await fe(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function q(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ae(t,e,o){let n=await m.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await Me(t);try{if(n){await zt(e,n._id),y().onAfterLogin?.({user:n,session:r,connectionInfo:i}),y().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(y().login?.onError?.(s),y().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await m.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 m.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await zt(e,a.insertedId);let c=await m.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(y().onAfterSignup?.({user:c,session:r,connectionInfo:i}),y().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(y().onSignupError?.({error:s,session:r,connectionInfo:i}),y().signup?.onError?.(s)),s}}function ce(t){return !t||typeof t!="string"?null:t}async function Xo(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function en(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 tn(t,e){let o=ce(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=q("google");try{let s=await Xo(o,n,r,i),a=await en(s.access_token),c={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await ae(t,e,c);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function on(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=q("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,tn),t}var qt=on;async function rn(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function sn(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 an(t,e){let o=ce(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=q("github");try{let s=await rn(o,n,r,i),a=await sn(s.access_token),c=a.email||"";if(!c){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let l={id:String(a.id),email:c,emailVerified:!0,providerName:"github"};await ae(t,e,l);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function cn(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=q("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(l=>l.trim()).join(" "):"user:email",c=new URL("https://github.com/login/oauth/authorize");c.searchParams.append("client_id",r),c.searchParams.append("redirect_uri",i),c.searchParams.append("scope",a),n.redirect(c.toString());}),t.get("/api/_internal/auth/github/callback",e,an),t}var Ft=cn;function Zt(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&A())try{let{session:l,user:p}=await M(s);a={session:l,user:p};}catch{}let c=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let l=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,rawBody:Buffer.isBuffer(n.body)?n.body:void 0,req:n,res:r,next:i},a);c.end(),l&&(r.status(l.status||200),l.redirect&&r.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([p,f])=>{r.setHeader(p,f);}),r.send(l.data));}catch(l){c.end("error"),l instanceof a$3?r.status(l.status).send(l.message):(console.error(`Error in route handler: ${n.path}`),console.error(l),r.status(500).send(String(l)));}}}var Ae=Object.freeze({});function Wt(t){Ae=Object.freeze(Object.assign({},Ae,t));}function le(){return Ae}function un(t){let e=[];if(!t)return e.push(R.json({limit:"16mb"})),e.push(R.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(R.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(R.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},n={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(R.raw(n));}return e}function mn(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i,body:s}=n,a=un(s);Object.entries(i).forEach(([c,l])=>{t[c](r,...a,Zt(c,r,l));});}}async function Bt(t,{combinedModules:e,channels:o}){let n=R();n.use(ln()),mn(n,e),n.use(R.json({limit:"16mb"})),n.use(R.urlencoded({extended:true,limit:"16mb"})),n.use(qt()),n.use(Ft()),n.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:l}=a.params,p=await Me(a);try{let f=await nt(l,a.body.args,p);c.json({data:f,typeMap:a$2(f)});}catch(f){pn(c,l,f);}}),await t.init(),t.middlewares&&n.use(t.middlewares()),n.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 r=dn.createServer(n),i$1=le()?.provider;i$1&&i$1.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
14
+ `}var ve={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Et(t,{connectionInfo:e}){let o=z(t.email),r=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r||!r.authMethods?.password)return ve;let n=E().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 C.insertOne({userId:r._id,token:i,createdAt:a$1,expiresAt:l});let c=process.env.MODELENCE_SITE_URL||e?.baseUrl,f=`${Mo(c,E().passwordReset?.redirectUrl)}?token=${i}`,U=(E()?.passwordReset?.template||Io)({email:o,resetUrl:f,name:""}),ue=oe(U);return await n.sendEmail({to:o,from:E()?.from||"noreply@modelence.com",subject:E()?.passwordReset?.subject||"Reset your password",text:ue,html:U}),ve}async function St(t,{}){let e=z$1.string().parse(t.token),o=se(t.password),r=await C.findOne({token:e});if(!r)throw new Error("Invalid or expired reset token");if(r.expiresAt<new Date)throw await C.deleteOne({token:e}),new Error("Reset token has expired");let n=await p.findOne({_id:r.userId});if(!n)throw new Error("User not found");let i=await vo.hash(o,10);return await p.updateOne({_id:n._id},{$set:{"authMethods.password.hash":i}}),await C.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Ct=new S("_system.user",{stores:[p,B,T,C],queries:{getOwnProfile:yt},mutations:{signupWithPassword:bt,loginWithPassword:ht,logout:gt,sendResetPasswordToken:Et,resetPassword:St},cronJobs:{updateDisposableEmailList:ct},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:pt}}]});async function xt({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 Te("/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 vt(){return await Te("/api/configs","GET")}async function Tt(){return await Te("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Te(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 De=false,Po=a.seconds(10);function Dt(){setInterval(async()=>{if(!De){De=true;try{await Tt();}catch(t){console.error("Error syncing status",t);}try{await Uo();}catch(t){console.error("Error syncing config",t);}De=false;}},Po);}async function Uo(){let{configs:t}=await vt();c(t);}var Q=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 F={},kt=a.seconds(10),_t=randomBytes(32).toString("base64url"),$o=a.seconds(30);async function ae(t,{lockDuration:e=$o,successfulLockCacheDuration:o=kt,failedLockCacheDuration:r=kt,instanceId:n=_t}={}){let i=Date.now();if(F[t]&&i<F[t].expiresAt)return F[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 Q.upsertOne({$or:[{resource:t,instanceId:n},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:n,acquiredAt:new Date}}),l=a.upsertedCount>0||a.modifiedCount>0;return F[t]={value:l,expiresAt:i+(l?o:r)},l?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}),l}catch{return F[t]={value:false,expiresAt:i+r},h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),false}}async function At(t,{instanceId:e=_t}={}){let o=await Q.deleteOne({resource:t,instanceId:e});return delete F[t],o.deletedCount>0}var No=a.minutes(1),P={},ke=null,_e=new b("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Rt(t,{description:e="",interval:o,timeout:r=No,handler:n}){if(P[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ke)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}]`);P[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function Mt(){if(ke)throw new Error("Cron jobs already started");let t=Object.keys(P);if(t.length>0){let e={alias:{$in:t}},o=await _e.fetch(e),r=Date.now();o.forEach(n=>{let i=P[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(P).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),ke=setInterval(zo,a.seconds(1));}}async function zo(){let t=Date.now();await ae("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(P).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 _e.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});let i=k$1("cron",`cron:${e}`);try{await r(),Ot(n,o),i.end("success");}catch(s){Ot(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 Ot(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function It(){return Object.values(P).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Lt=new S("_system.cron",{stores:[_e]});var Ae=new S("_system.lock",{stores:[Q]});var H=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 qo(t){if(t.length===0)return;if(!await ae("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),r=await H.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:l}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let m=(await l()||"").toString().trim(),f=15*1024*1024,w=m.length>f?m.slice(0,f)+`
15
+ [Output truncated - exceeded size limit]`:m;await H.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:w,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(c){c instanceof Error&&(await H.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:c.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${c.message}`,{source:"migrations"}));}}await At("migrations");}}function Pt(t){setTimeout(()=>{qo(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Ut=new S("_system.migration",{stores:[H]});var jt=new S("_system.rateLimit",{stores:[G]});var $t=new S("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var Re=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=[A.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(A.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 Qo(){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 Ho(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 Qo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Go.existsSync(Oe.join(t,i))),r=[Jo(),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:Oe.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:{"@":Oe.resolve(t,"src").replace(/\\/g,"/")}}});return Ho(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 zt=new Re;async function Ft(t,e){let{authToken:o}=await he(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function q(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ce(t,e,o){let r=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await Me(t);try{if(r){await Ft(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 p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Ft(e,a.insertedId);let l=await p.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(h().onAfterSignup?.({provider:o.providerName,user:l,session:n,connectionInfo:i}),h().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(h().onSignupError?.({provider:o.providerName,error:s,session:n,connectionInfo:i}),h().signup?.onError?.(s)),s}}function le(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=le(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=q("google");try{let l=await tr(o,i,s,a),c=await or(l.access_token),m={id:c.id,email:c.email,emailVerified:c.verified_email,providerName:"google"};await ce(t,e,m);}catch(l){console.error("Google OAuth error:",l),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=q("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 qt=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=le(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=q("github");try{let l=await ar(o,i,s,a),c=await cr(l.access_token),m=c.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 f={id:String(c.id),email:m,emailVerified:!0,providerName:"github"};await ce(t,e,f);}catch(l){console.error("GitHub OAuth error:",l),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=q("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");r.cookie("authStateGithub",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let c=new URL("https://github.com/login/oauth/authorize");c.searchParams.append("client_id",n),c.searchParams.append("redirect_uri",i),c.searchParams.append("scope",a$2),c.searchParams.append("state",l),r.redirect(c.toString());}),t.get("/api/_internal/auth/github/callback",e,lr),t}var Wt=dr;function Zt(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"&&M())try{let{session:c,user:m}=await R(s);a={session:c,user:m};}catch{}let l=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:r.query,body:r.body,params:r.params});try{let c=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);l.end(),c&&(n.status(c.status||200),c.redirect&&n.redirect(c.redirect),c.headers&&Object.entries(c.headers).forEach(([m,f])=>{n.setHeader(m,f);}),n.send(c.data));}catch(c){l.end("error"),c instanceof a$3?n.status(c.status).send(c.message):(console.error(`Error in route handler: ${r.path}`),console.error(c),n.status(500).send(String(c)));}}}var Ie=Object.freeze({});function Bt(t){Ie=Object.freeze(Object.assign({},Ie,t));}function de(){return Ie}function mr(t){let e=[];if(!t)return e.push(A.json({limit:"16mb"})),e.push(A.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(A.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(A.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(A.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(([l,c])=>{t[l](n,...a,Zt(l,n,c));});}}async function Vt(t,{combinedModules:e,channels:o}){let r=A();r.use(ur()),fr(r,e),r.use(A.json({limit:"16mb"})),r.use(A.urlencoded({extended:true,limit:"16mb"})),r.use(qt()),r.use(Wt()),r.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:c}=a.params,m=await Me(a);try{let f=await nt(c,a.body.args,m);l.json({data:f,typeMap:a$2(f)});}catch(f){hr(l,c,f);}}),await t.init(),t.middlewares&&r.use(t.middlewares()),r.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=pr.createServer(r),i$1=de()?.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(`
16
16
  Application started on ${a}
17
- `);});}async function Me(t){let e=k.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=k.object({screenWidth:k.number(),screenHeight:k.number(),windowWidth:k.number(),windowHeight:k.number(),pixelRatio:k.number(),orientation:k.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:fn(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!A()){let{session:i,user:s,roles:a}=await M(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:X()}}function pn(t,e,o){if(console.error(`Error in method ${e}:`,o),o instanceof a$3)t.status(o.status).send(o.message);else if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r=o.flatten(),i=Object.entries(r.fieldErrors).map(([c,l])=>`${c}: ${(l??[]).join(", ")}`).join("; "),s=r.formErrors.join("; "),a=[i,s].filter(Boolean).join("; ");t.status(400).send(a);}else t.status(500).send(o instanceof Error?o.message:String(o));}function fn(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 wn({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Nt,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Jt.config(),Jt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";On().then(()=>{}).catch(()=>{});let p=[Et,He,It,Pt,Ut,jt,ke],f$1=[...p,...t];e(),Sn(p),bn(t),Qe(e$1,o);let C=Tn(f$1);d$2(C);let U=En(f$1),de=Cn(f$1);l&&vn(f$1);let Vt=xn(f$1);if(yt(Vt),c$1){let{configs:ue,environmentId:Qt,appAlias:Gt,environmentAlias:Kt,telemetry:Yt}=await Ct({configSchema:C,cronJobsMetadata:l?At():void 0,stores:U});c(ue),f({environmentId:Qt,appAlias:Gt,environmentAlias:Kt,telemetry:Yt});}else c(Rn(C));ct(i),mt(s),Wt({...a,provider:a.provider||it});let Le=A();if(Le&&(await Ke(),Dn(U)),l&&Lt(r),Le)for(let ue of U)ue.createIndexes();c$1&&(await g(),vt()),l&&Mt().catch(console.error),await Bt(n,{combinedModules:f$1,channels:de});}function bn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ge(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ye(`${e.name}.${o}`,n);}}function Sn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))et(`${e.name}.${o}`,n);}}function En(t){return t.flatMap(e=>e.stores)}function Cn(t){return t.flatMap(e=>e.channels)}function xn(t){return t.flatMap(e=>e.rateLimits)}function Tn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function vn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ot(`${e.name}.${o}`,n);}function Dn(t){let e=ee();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var _n={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 kn(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 Rn(t){let e=[];for(let[o,n]of Object.entries(_n)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:kn(r,s)});}}return e}async function On(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Mn(),r=await import('./package-3YQBVIVQ.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:Io.hostname(),environmentId:o})});}}async function Mn(){try{let t=Re.join(process.cwd(),"package.json"),e=await hn.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Ht(t){await v.deleteMany({userId:t}),await E.deleteMany({userId:t});}async function In(t){await Ht(t),await m.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function Ln(t){await Ht(t),await m.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Ie=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=le().provider;if(!n){j$1("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Pn(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{S as Module,Ie as ServerChannel,w as Store,M as authenticate,L as consumeRateLimit,ge as createQuery,m as dbUsers,Ln as deleteUser,In as disableUser,d as schema,Pn as sendEmail,wn as startApp};//# sourceMappingURL=server.js.map
17
+ `);});}async function Me(t){let e=_.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=_.object({screenWidth:_.number(),screenHeight:_.number(),windowWidth:_.number(),windowHeight:_.number(),pixelRatio:_.number(),orientation:_.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},r={ip:gr(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!M()){let{session:i,user:s,roles:a}=await R(e);return {clientInfo:o,connectionInfo:r,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:ee()}}function hr(t,e,o){if(console.error(`Error in method ${e}:`,o),o instanceof a$3)t.status(o.status).send(o.message);else if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let n=o.flatten(),i=Object.entries(n.fieldErrors).map(([l,c])=>`${l}: ${(c??[]).join(", ")}`).join("; "),s=n.formErrors.join("; "),a=[i,s].filter(Boolean).join("; ");t.status(400).send(a);}else t.status(500).send(o instanceof Error?o.message:String(o));}function gr(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 Er({modules:t=[],roles:e$1={},defaultRoles:o={},server:r=zt,migrations:n=[],email:i={},auth:s={},websocket:a={}}){Jt.config(),Jt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,c$1=process.env.MODELENCE_CRON_ENABLED==="true";Mr().then(()=>{}).catch(()=>{});let m=[Ct,Ge,Lt,Ut,jt,$t,Ae],f$1=[...m,...t];e(),Cr(m),Sr(t),He(e$1,o);let w=Dr(f$1);d$2(w);let U=xr(f$1),ue=vr(f$1);c$1&&kr(f$1);let Qt=Tr(f$1);if(wt(Qt),l){let{configs:pe,environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt}=await xt({configSchema:w,cronJobsMetadata:c$1?It():void 0,stores:U});c(pe),f({environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt});}else c(Rr(w));lt(i),ut(s),Bt({...a,provider:a.provider||st});let Pe=M();if(Pe&&(await Ye(),_r(U)),c$1&&Pt(n),Pe)for(let pe of U)pe.createIndexes();l&&(await g(),Dt()),c$1&&Mt().catch(console.error),await Vt(r,{combinedModules:f$1,channels:ue});}function Sr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))ye(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))Xe(`${e.name}.${o}`,r);}}function Cr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))et(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))tt(`${e.name}.${o}`,r);}}function xr(t){return t.flatMap(e=>e.stores)}function vr(t){return t.flatMap(e=>e.channels)}function Tr(t){return t.flatMap(e=>e.rateLimits)}function Dr(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 kr(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))Rt(`${e.name}.${o}`,r);}function _r(t){let e=te();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ar={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 Or(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 Rr(t){let e=[];for(let[o,r]of Object.entries(Ar)){let n=process.env[o],i=t[r];if(n){let s=i?.type??"string";e.push({key:r,type:s,value:Or(n,s)});}}return e}async function Mr(){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 Ir(),n=await import('./package-46B3WEOU.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 Ir(){try{let t=Oe.join(process.cwd(),"package.json"),e=await yr.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Gt(t){await T.deleteMany({userId:t}),await C.deleteMany({userId:t});}async function Pr(t){await Gt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function Ur(t){await Gt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Le=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let r=de().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(!E().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return E().provider?.sendEmail(t)}
18
+ export{N as LiveData,S as Module,Le as ServerChannel,b as Store,R as authenticate,L as consumeRateLimit,ye as createQuery,p as dbUsers,Ur as deleteUser,Pr as disableUser,d as schema,jr as sendEmail,Er as startApp};//# sourceMappingURL=server.js.map
19
19
  //# sourceMappingURL=server.js.map