modelence 0.5.3-dev.1 → 0.5.3-dev.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var s="module",i="modelence",n="0.5.3-dev.12",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:m,repository:a,author:u,license:y,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-CHE6QRB4.js.map
|
|
3
|
+
//# sourceMappingURL=package-CHE6QRB4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,cAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,CAAS,CACP,MACA,CAAA,UACF,EACAC,CAAO,CAAA,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,OACT,GAAO,CAAA,cAAA,CACP,eAAkB,eAClB,CAAA,IAAA,CAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CACAC,CAAAA,CAAAA,CAAc,CACZ,IAAQ,CAAA,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WACVC,CAAAA,CAAAA,CAAW,yBACXC,CAAQ,CAAA,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBACZC,CAAAA,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,SACnB,eAAiB,CAAA,QAAA,CACjB,iBAAkB,QAClB,CAAA,iBAAA,CAAmB,UACnB,aAAe,CAAA,SAAA,CACf,eAAgB,SAChB,CAAA,kBAAA,CAAoB,UACpB,kCAAoC,CAAA,SAAA,CACpC,4BAA6B,SAC7B,CAAA,KAAA,CAAS,UACT,WAAa,CAAA,SAAA,CACb,UAAc,CAAA,QAChB,EACAC,CAAgB,CAAA,CACd,gBAAiB,SACjB,CAAA,sBAAA,CAAwB,SACxB,QAAY,CAAA,QAAA,CACZ,OAAU,QACV,CAAA,SAAA,CAAa,UACb,MAAU,CAAA,SAAA,CACV,mBAAoB,QACpB,CAAA,OAAA,CAAW,UACX,UAAY,CAAA,SAAA,CACZ,IAAQ,CAAA,QAAA,CACR,QAAW,QACX,CAAA,IAAA,CAAQ,UACR,IAAQ,CAAA,QAAA,CACR,IAAO,SACP,CAAA,IAAA,CAAQ,SACR,oBAAsB,CAAA,QAAA,CACtB,QAAW,SACX,CAAA,uBAAA,CAAyB,UACzB,GAAO,CAAA,SAAA,CACP,QAAW,QACb,CAAA,CACAC,CAAoB,CAAA,CAClB,MAAS,UACT,CAAA,WAAA,CAAa,UACf,CA7EFC,CAAAA,CAAAA,CAAA,CACE,IAAAlB,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,OAAA,CAAAC,EACA,WAAAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAOA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAsBA,iBAAAC,CAIF","file":"package-CHE6QRB4.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.3-dev.12\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -137,6 +137,13 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
137
137
|
* @returns The document
|
|
138
138
|
*/
|
|
139
139
|
requireById(id: string | ObjectId$1, errorHandler?: () => Error): Promise<this['_doc']>;
|
|
140
|
+
/**
|
|
141
|
+
* Counts the number of documents that match a query
|
|
142
|
+
*
|
|
143
|
+
* @param query - The query to filter documents
|
|
144
|
+
* @returns The number of documents that match the query
|
|
145
|
+
*/
|
|
146
|
+
countDocuments(query: Filter<this['_type']>): Promise<number>;
|
|
140
147
|
/**
|
|
141
148
|
* Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.
|
|
142
149
|
*
|
|
@@ -315,6 +322,18 @@ type RouteDefinition = {
|
|
|
315
322
|
errorHandler?: RouteHandler;
|
|
316
323
|
};
|
|
317
324
|
|
|
325
|
+
type RateLimitType = 'ip' | 'user';
|
|
326
|
+
type RateLimitRule = {
|
|
327
|
+
/** Logical action being limited, e.g. "signup" */
|
|
328
|
+
bucket: string;
|
|
329
|
+
/** Identifier type of the actor this rule applies to */
|
|
330
|
+
type: RateLimitType;
|
|
331
|
+
/** Time window size in milliseconds */
|
|
332
|
+
window: number;
|
|
333
|
+
/** Maximum allowed hits within the window */
|
|
334
|
+
limit: number;
|
|
335
|
+
};
|
|
336
|
+
|
|
318
337
|
/** Array of Store instances that will be provisioned when the module is loaded */
|
|
319
338
|
type Stores = Store<any, any>[];
|
|
320
339
|
/** Record of query methods that can be called from the client */
|
|
@@ -359,6 +378,8 @@ declare class Module {
|
|
|
359
378
|
readonly cronJobs: Record<string, CronJobInputParams>;
|
|
360
379
|
/** @internal */
|
|
361
380
|
readonly configSchema: ConfigSchema;
|
|
381
|
+
/** @internal */
|
|
382
|
+
readonly rateLimits: RateLimitRule[];
|
|
362
383
|
/**
|
|
363
384
|
* Creates a new Module instance
|
|
364
385
|
*
|
|
@@ -368,13 +389,14 @@ declare class Module {
|
|
|
368
389
|
*
|
|
369
390
|
* @param options - Module configuration options
|
|
370
391
|
*/
|
|
371
|
-
constructor(name: string, { stores, queries, mutations, routes, cronJobs, configSchema }: {
|
|
392
|
+
constructor(name: string, { stores, queries, mutations, routes, cronJobs, configSchema, rateLimits }: {
|
|
372
393
|
stores?: Store<any, any>[];
|
|
373
394
|
queries?: Queries;
|
|
374
395
|
mutations?: Mutations;
|
|
375
396
|
routes?: RouteDefinition[];
|
|
376
397
|
cronJobs?: Record<string, CronJobInputParams>;
|
|
377
398
|
configSchema?: ConfigSchema;
|
|
399
|
+
rateLimits?: RateLimitRule[];
|
|
378
400
|
});
|
|
379
401
|
}
|
|
380
402
|
|
|
@@ -677,4 +699,4 @@ type CloudBackendConnectErrorResponse = {
|
|
|
677
699
|
};
|
|
678
700
|
type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;
|
|
679
701
|
|
|
680
|
-
export { type AppOptions, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
|
|
702
|
+
export { type AppOptions, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RateLimitRule, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g as g$1,a as a$2,h,j,k}from'./chunk-F5MTZMFH.js';export{a as getConfig}from'./chunk-F5MTZMFH.js';import Fe from'dotenv';import st from'http';import B from'express';import y,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import lt from'os';import mt from'bcrypt';import {createServer,defineConfig}from'vite';import xt from'@vitejs/plugin-react';import W from'path';import Et from'fs';function We(){return typeof window!="object"}function w(){if(!We())throw new Error("This function can only be called on the server")}var ne=new Map,C={authenticated:null,unauthenticated:null};function re(t,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ne.set(o,n);}function v(){return C.unauthenticated?[C.unauthenticated]:[]}function se(){return C.authenticated?[C.authenticated]:[]}function ie(t,e){let o=e.find(n=>!Ke(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Ke(t,e){for(let o of t){let n=ne.get(o);if(n&&n.permissions.includes(e))return true}return false}var U={};function J(t,e){return w(),de(t),I("query",t,e)}function ae(t,e){return w(),de(t),I("mutation",t,e)}function ce(t,e){return w(),ue(t),I("query",t,e)}function le(t,e){return w(),ue(t),I("mutation",t,e)}function de(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ue(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function I(t,e,o){if(w(),U[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,s=typeof o=="function"?[]:o.permissions??[];U[e]={type:t,name:e,handler:n,permissions:s};}async function me(t,e,o){w();let n=U[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:s,handler:r}=n,i=j("method",`method:${t}`,{type:s,args:e}),c;try{ie(o.roles,n.permissions),c=await r(e,o);}catch(h){throw i.end("error"),h}return i.end(),c}var f=class{constructor(e,{stores:o=[],queries:n={},mutations:s={},routes:r=[],cronJobs:i={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=s,this.routes=r,this.cronJobs=i,this.configSchema=c;}};var m=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let s=await this.findOne(e,o);if(!s)throw n?n():new Error(`Record not found in ${this.name}`);return s}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var Ve=z$1.string.bind(z$1),He=z$1.number.bind(z$1),Ze=z$1.date.bind(z$1),Qe=z$1.boolean.bind(z$1),Ge=z$1.array.bind(z$1),Ye=z$1.object.bind(z$1),Xe=z$1.enum.bind(z$1),a={string:Ve,number:He,date:Ze,boolean:Qe,array:Ge,object:Ye,enum:Xe,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var x=new m("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function fe(t){let e=t?await x.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await tt()}async function he(t,e){await x.updateOne({authToken:t},{$set:{userId:e}});}async function ge(t){await x.updateOne({authToken:t},{$set:{userId:null}});}async function tt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await x.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function ot(t){let e=Date.now(),o=new Date(e+a$1.days(7));await x.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ye=new f("_system.session",{stores:[x],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 ot(e);}}});var p=new m("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),_=new m("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function we(t){let e=await fe(t),o=e.userId?await p.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,s=n?se():v();return {user:n,session:e,roles:s}}function be(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([s,r])=>{o.setHeader(s,r);}),o.send(n.data);}catch(n){n instanceof a$4||n instanceof b$2?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var g=null;async function Ce(){if(g)return g;let t=M();if(!t)throw new Error("MongoDB URI is not set");g=new MongoClient(t,{maxPoolSize:20});try{return await g.connect(),await g.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),g}catch(e){throw console.error(e),g=null,e}}function M(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function xe(){return g}function it(t,e){for(let o of e)for(let n of o.routes){let{path:s,handlers:r}=n;Object.entries(r).forEach(([i,c])=>{t[i](s,be(c));});}}async function Ee(t,{combinedModules:e}){let o=B();o.use(B.json()),o.use(B.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,i)=>{let{methodName:c}=r.params,h=await at(r);try{let d=await me(c,r.body.args,h);i.json({data:d,typeMap:a$3(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let E=d.flatten(),S=Object.entries(E.fieldErrors).map(([P,$])=>`${P}: ${($??[]).join(", ")}`).join("; "),k=E.formErrors.join("; "),j=[S,k].filter(Boolean).join("; ");i.status(400).send(j);}else i.status(500).send(d instanceof Error?d.message:String(d));}}),it(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,i)=>t.handler(r,i)),process.on("unhandledRejection",(r,i)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",i);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=st.createServer(o),s=process.env.PORT||3e3;n.listen(s,()=>{h("Application started",{source:"app"}),console.log(`Application started on port ${s}`);});}async function at(t){let e=y.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:ct(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!M()){let{session:r,user:i,roles:c}=await we(e);return {clientInfo:o,connectionInfo:n,session:r,user:i,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:v()}}function ct(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 Se({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 s=Object.values(o).map(i=>({name:i.getName(),schema:i.getSchema(),collections:[i.getName()]})),r=await z("/api/connect","POST",{hostname:lt.hostname(),containerId:n,dataModels:s,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(s){throw console.error("Unable to connect to Modelence Cloud:",s),s}}async function De(){return await z("/api/configs","GET")}async function Me(){return await z("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function z(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:s}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${s}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let i=await r.text();try{let c=JSON.parse(i);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${i}`)}}return await r.json()}var L=false,dt=a$1.seconds(10);function Te(){setInterval(async()=>{if(!L){L=true;try{await Me();}catch(t){console.error("Error syncing status",t);}try{await ut();}catch(t){console.error("Error syncing config",t);}L=false;}},dt);}async function ut(){let{configs:t}=await De();c(t);}async function Oe(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),s=await p.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(s){let c=s.emails?.find(h=>h.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await mt.hash(n,10);return (await p.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function _e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),s=z$1.string().parse(t.password),r=await p.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),i=r?.authMethods?.password?.hash;if(!r||!i||!await mt.compare(s,i))throw Ie();return await he(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Ae(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await ge(o.authToken);}function Ie(){return new Error("Incorrect email/password combination")}async function ke(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 je={interval:a$1.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(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,s=500;for(let r=0;r<o.length;r+=s){let i=o.slice(r,r+s);try{await _.insertMany(i.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var Pe=new f("_system.user",{stores:[p,_],queries:{getOwnProfile:ke},mutations:{signupWithPassword:Oe,loginWithPassword:_e,logout:Ae},cronJobs:{updateDisposableEmailList:je}});var A=new m("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function $e(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await A.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),s=t.filter(({version:r})=>!n.has(r));if(s.length!==0){console.log(`Running migrations (${s.length})...`);for(let{version:r,description:i,handler:c}of s)console.log(`Running migration v${r}: ${i}`),await A.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Ne=new f("_system.migration",{stores:[A]});var ft=a$1.minutes(1),ht=a$1.seconds(10),b={},F,T=new m("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Je(t,{description:e="",interval:o,timeout:n=ft,handler:s}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(F)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:s,state:{isRunning:false}};}async function qe(){if(F)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await T.findOne({...e,"lock.containerId":{$exists:true}});await T.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await gt(ht);let n=await T.fetch(e),s=Date.now();n.forEach(r=>{let i=b[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:s);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=s);}),F=setInterval(yt,a$1.seconds(1));}}function gt(t){return new Promise(e=>setTimeout(e,t))}async function yt(){let t=Date.now();Object.values(b).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await wt(e);});}async function wt(t){let{alias:e,params:o,handler:n,state:s}=t;s.isRunning=true,s.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Ue(s,o),r.end("success");}).catch(i=>{Ue(s,o),k(i),r.end("error"),console.error(`Error in cron job '${e}':`,i);}),await T.updateOne({alias:e},{$set:{lastStartDate:new Date(s.startTs)}});}function Ue(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Be(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var ze=new f("_system.cron",{stores:[T]});var K=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await Dt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[B.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Dt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Et.existsSync(W.join(t,n))),o=[xt(),Mt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:W.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":W.resolve(t,"src")}}}}function Mt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Le=new K;async function Tt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Le,migrations:s=[]}){Fe.config(),Fe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,i=process.env.MODELENCE_CRON_ENABLED==="true";jt().then(()=>{}).catch(()=>{});let c$1=[Pe,ye,ze,Ne],h=[...c$1,...t];e(),Ot(c$1),Rt(t),re(e$1,o);let d$1=It(h);d(d$1??{});let R=vt(h);if(i&&_t(h),r){let{configs:S,environmentId:k,appAlias:j,environmentAlias:P,telemetry:$}=await Se({configSchema:d$1,cronJobsMetadata:i?Be():void 0,stores:R});c(S),f$1({environmentId:k,appAlias:j,environmentAlias:P,telemetry:$});}else c(kt());let E=M();if(E&&(await Ce(),At(R)),i&&await $e(s),E)for(let S of R)S.createIndexes();r&&(await g$1(),Te()),i&&qe().catch(console.error),await Ee(n,{combinedModules:h});}function Rt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))J(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ae(`${e.name}.${o}`,n);}}function Ot(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ce(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))le(`${e.name}.${o}`,n);}}function vt(t){return t.flatMap(e=>e.stores)}function It(t){let e={};for(let o of t)for(let[n,s]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=s;}return e}function _t(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Je(`${e.name}.${o}`,n);}function At(t){let e=xe();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function kt(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function jt(){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 import('./package-X5TSICV7.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:n.default.version,environmentId:o})});}}
|
|
3
|
-
export{f as Module,
|
|
1
|
+
import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g,a as a$2,h as h$1,j as j$1,k as k$1}from'./chunk-F5MTZMFH.js';export{a as getConfig}from'./chunk-F5MTZMFH.js';import Qe from'dotenv';import mt from'http';import B from'express';import g$1,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import yt from'os';import xt from'bcrypt';import {createServer,defineConfig}from'vite';import It from'@vitejs/plugin-react';import V from'path';import _t from'fs';function Ye(){return typeof window!="object"}function w(){if(!Ye())throw new Error("This function can only be called on the server")}var ie=new Map,x={authenticated:null,unauthenticated:null};function se(t,e){x.authenticated=e.authenticated,x.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ie.set(o,n);}function A(){return x.unauthenticated?[x.unauthenticated]:[]}function ae(){return x.authenticated?[x.authenticated]:[]}function ce(t,e){let o=e.find(n=>!Xe(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Xe(t,e){for(let o of t){let n=ie.get(o);if(n&&n.permissions.includes(e))return true}return false}var U={};function J(t,e){return w(),me(t),k("query",t,e)}function le(t,e){return w(),me(t),k("mutation",t,e)}function de(t,e){return w(),pe(t),k("query",t,e)}function ue(t,e){return w(),pe(t),k("mutation",t,e)}function me(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function pe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function k(t,e,o){if(w(),U[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];U[e]={type:t,name:e,handler:n,permissions:i};}async function fe(t,e,o){w();let n=U[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j$1("method",`method:${t}`,{type:i,args:e}),c;try{ce(o.roles,n.permissions),c=await r(e,o);}catch(m){throw s.end("error"),m}return s.end(),c}var f=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:m=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=m;}};var p=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}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){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var et=z$1.string.bind(z$1),tt=z$1.number.bind(z$1),ot=z$1.date.bind(z$1),nt=z$1.boolean.bind(z$1),rt=z$1.array.bind(z$1),it=z$1.object.bind(z$1),st=z$1.enum.bind(z$1),a={string:et,number:tt,date:ot,boolean:nt,array:rt,object:it,enum:st,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var E=new p("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function ye(t){let e=t?await E.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ct()}async function ge(t,e){await E.updateOne({authToken:t},{$set:{userId:e}});}async function we(t){await E.updateOne({authToken:t},{$set:{userId:null}});}async function ct(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await E.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function lt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await E.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var be=new f("_system.session",{stores:[E],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 lt(e);}}});var h=new p("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),S=new p("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function Ce(t){let e=await ye(t),o=e.userId?await h.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?ae():A();return {user:n,session:e,roles:i}}function xe(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4||n instanceof b$2?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var y=null;async function Ee(){if(y)return y;let t=T();if(!t)throw new Error("MongoDB URI is not set");y=new MongoClient(t,{maxPoolSize:20});try{return await y.connect(),await y.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),y}catch(e){throw console.error(e),y=null,e}}function T(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Re(){return y}function pt(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,xe(c));});}}async function Me(t,{combinedModules:e}){let o=B();o.use(B.json()),o.use(B.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,m=await ft(r);try{let u=await fe(c,r.body.args,m);s.json({data:u,typeMap:a$3(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let O=u.flatten(),I=Object.entries(O.fieldErrors).map(([$,L])=>`${$}: ${(L??[]).join(", ")}`).join("; "),M=O.formErrors.join("; "),P=[I,M].filter(Boolean).join("; ");s.status(400).send(P);}else s.status(500).send(u instanceof Error?u.message:String(u));}}),pt(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=mt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function ft(t){let e=g$1.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=g$1.object({screenWidth:g$1.number(),screenHeight:g$1.number(),windowWidth:g$1.number(),windowHeight:g$1.number(),pixelRatio:g$1.number(),orientation:g$1.string().nullable()}).parse(t.body.clientInfo),n={ip:ht(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!T()){let{session:r,user:s,roles:c}=await Ce(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:A()}}function ht(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 De({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await z("/api/connect","POST",{hostname:yt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Se(){return await z("/api/configs","GET")}async function Te(){return await z("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function z(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var F=false,gt=a$1.seconds(10);function ve(){setInterval(async()=>{if(!F){F=true;try{await Te();}catch(t){console.error("Error syncing status",t);}try{await wt();}catch(t){console.error("Error syncing config",t);}F=false;}},gt);}async function wt(){let{configs:t}=await Se();c(t);}async function Oe(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await S.findOne({domain:o})}var Ie={interval:a$1.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(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await S.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var R=new p("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var W=[];function _e(t){if(W.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");W=t;}async function Ae({bucket:t,type:e,value:o}){let n=W.filter(i=>i.bucket===t&&i.type===e);for(let i of n)await bt(i,o);}async function bt(t,e,o){let n=()=>new Error(`Rate limit exceeded for ${t.bucket}`),i=await R.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window;if(i){let{count:c,modifier:m}=Ct(i,s,r);if(c>=t.limit)throw n();await R.updateOne(i._id.toString(),m);}else {if(t.limit<1)throw n();await R.insertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window,windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)});}}function Ct(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:i+r*s,modifier:{$inc:{windowCount:1}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:t.windowCount*i,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 je(t,{user:e,connectionInfo:o}){let n=z$1.string().email().parse(t.email),i=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password);if(await Oe(n))throw new Error("Please use a permanent email address");let r=await h.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(r){let u=r.emails?.find(C=>C.address===n);throw new Error(`User with email already exists: ${u?.address}`)}let s=o?.ip;s&&await Ae({bucket:"signup",type:"ip",value:s});let c=await xt.hash(i,10);return (await h.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}})).insertedId}async function Le(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),i=z$1.string().parse(t.password),r=await h.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await xt.compare(i,s))throw $e();return await ge(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Ne(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await we(o.authToken);}function $e(){return new Error("Incorrect email/password combination")}async function Ue(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await h.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var Je=new f("_system.user",{stores:[h,S],queries:{getOwnProfile:Ue},mutations:{signupWithPassword:je,loginWithPassword:Le,logout:Ne},cronJobs:{updateDisposableEmailList:Ie},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(5),limit:2},{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200}]});var j=new p("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function qe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await j.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await j.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Be=new f("_system.migration",{stores:[j]});var ze=new f("_system.rateLimit",{stores:[R]});var Rt=a$1.minutes(1),Mt=a$1.seconds(10),b={},K,v=new p("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function We(t,{description:e="",interval:o,timeout:n=Rt,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(K)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function Ke(){if(K)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await v.findOne({...e,"lock.containerId":{$exists:true}});await v.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await Dt(Mt);let n=await v.fetch(e),i=Date.now();n.forEach(r=>{let s=b[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),K=setInterval(St,a$1.seconds(1));}}function Dt(t){return new Promise(e=>setTimeout(e,t))}async function St(){let t=Date.now();Object.values(b).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Tt(e);});}async function Tt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j$1("cron",`cron:${e}`);n().then(()=>{Fe(i,o),r.end("success");}).catch(s=>{Fe(i,o),k$1(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await v.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Fe(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Ve(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var He=new f("_system.cron",{stores:[v]});var H=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await kt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[B.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function kt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>_t.existsSync(V.join(t,n))),o=[It(),jt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:V.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":V.resolve(t,"src")}}}}function jt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Ze=new H;async function Pt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ze,migrations:i=[]}){Qe.config(),Qe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";Ft().then(()=>{}).catch(()=>{});let c$1=[Je,be,He,Be,ze],m=[...c$1,...t];e(),Lt(c$1),$t(t),se(e$1,o);let u=Jt(m);d(u??{});let C=Nt(m);s&&qt(m);let O=Ut(m);if(_e(O),r){let{configs:M,environmentId:P,appAlias:$,environmentAlias:L,telemetry:Ge}=await De({configSchema:u,cronJobsMetadata:s?Ve():void 0,stores:C});c(M),f$1({environmentId:P,appAlias:$,environmentAlias:L,telemetry:Ge});}else c(zt());let I=T();if(I&&(await Ee(),Bt(C)),s&&await qe(i),I)for(let M of C)M.createIndexes();r&&(await g(),ve()),s&&Ke().catch(console.error),await Me(n,{combinedModules:m});}function $t(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))J(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))le(`${e.name}.${o}`,n);}}function Lt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))de(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ue(`${e.name}.${o}`,n);}}function Nt(t){return t.flatMap(e=>e.stores)}function Ut(t){return t.flatMap(e=>e.rateLimits)}function Jt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function qt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))We(`${e.name}.${o}`,n);}function Bt(t){let e=Re();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function zt(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function Ft(){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 import('./package-CHE6QRB4.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:n.default.version,environmentId:o})});}}
|
|
3
|
+
export{f as Module,p as Store,J as createQuery,h as dbUsers,a as schema,Pt as startApp};//# sourceMappingURL=server.js.map
|
|
4
4
|
//# sourceMappingURL=server.js.map
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/index.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/auth/disposableEmails.ts","../src/auth/user.ts","../src/migration/db.ts","../src/migration/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","type","handler","permissions","runMethod","args","context","method","transaction","startTransaction","response","error","Module","stores","queries","mutations","routes","cronJobs","configSchema","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","authenticate","userDoc","createRouteHandler","req","res","key","value","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getConfig","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","connectionInfo","getClientIp","forwardedFor","directIp","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","handleSignupWithPassword","email","password","existingUser","existingEmail","e","hash","bcrypt","handleLoginWithPassword","passwordHash","incorrectCredentialsError","handleLogout","getOwnProfile","_args","profile","updateDisposableEmailListCron","domains","domain","batchSize","i","batch","user_default","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","serviceEndpoint","packageJson"],"mappings":"ynBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,EAAAA,GACH,MAAM,IAAI,MAAM,gDAAgD,CAEpE,CCNA,IAAME,EAAAA,CAAU,IAAI,GACdC,CAAAA,CAAAA,CAA6B,CACjC,aAAe,CAAA,IAAA,CACf,gBAAiB,IACnB,CAAA,CAEO,SAASC,EAAAA,CAAUC,EAAqCC,CAAqC,CAAA,CAClGH,EAAa,aAAgBG,CAAAA,CAAAA,CAAc,cAC3CH,CAAa,CAAA,eAAA,CAAkBG,CAAc,CAAA,eAAA,CAE7C,OAAW,CAACC,CAAAA,CAAMC,CAAU,CAAK,GAAA,MAAA,CAAO,QAAQH,CAAK,CAAA,CACnDH,EAAQ,CAAA,GAAA,CAAIK,EAAMC,CAAU,EAEhC,CAEO,SAASC,CAAAA,EAA0B,CACxC,OAAON,CAAAA,CAAa,gBAAkB,CAACA,CAAAA,CAAa,eAAe,CAAI,CAAA,EACzE,CAEO,SAASO,IAA+B,CAC7C,OAAOP,CAAa,CAAA,aAAA,CAAgB,CAACA,CAAa,CAAA,aAAa,EAAI,EACrE,CAMO,SAASQ,EAAAA,CAAcN,CAAeO,CAAAA,CAAAA,CAAmC,CAC9E,IAAMC,CAAAA,CAAoBD,EAAoB,IAAKE,CAAAA,CAAAA,EAAc,CAACC,EAAcV,CAAAA,CAAAA,CAAOS,CAAU,CAAC,EAElG,GAAID,CAAAA,CACF,MAAM,I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AAAA,CAAAA,CAAM,KAAKlG,CAAM,EAErB,CAEA,SAAS6M,EAAAA,EAA+B,CACtC,IAAM5F,CAAAA,CAAuB,EAE7B,CAAA,OAAI,QAAQ,GAAI,CAAA,WAAA,EACdA,EAAQ,IAAK,CAAA,CACX,IAAK,oBACL,CAAA,IAAA,CAAM,SACN,KAAO,CAAA,OAAA,CAAQ,IAAI,WACrB,CAAC,EAGIA,CACT,CAEA,eAAe8E,EAAgB,EAAA,CAG7B,GAF0B,OAAQ,CAAA,GAAA,CAAI,6BAA+B,OAE9C,CAAA,CACrB,IAAMqB,CAAkB,CAAA,OAAA,CAAQ,IAAI,0BAA8B,EAAA,6BAAA,CAC5DZ,EAAgB,OAAQ,CAAA,GAAA,CAAI,yBAE5Ba,CAAc,CAAA,aAAa,uBAAoB,CAAA,CAErD,MAAM,KAAM,CAAA,CAAA,EAAGD,CAAe,CAAwB,oBAAA,CAAA,CAAA,CACpD,OAAQ,MACR,CAAA,OAAA,CAAS,CACP,cAAgB,CAAA,kBAClB,EACA,IAAM,CAAA,IAAA,CAAK,UAAU,CACnB,OAAA,CAASC,EAAY,OAAQ,CAAA,OAAA,CAC7B,cAAAb,CACF,CAAC,CACH,CAAC,EACH,CACF","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Create a new user\n * const result = await dbUsers.insertOne({\n * handle: 'john_doe',\n * emails: [{ address: 'john@example.com', verified: false }],\n * createdAt: new Date(),\n * authMethods: {\n * password: { hash: 'hashed_password' }\n * }\n * });\n * \n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from '@/telemetry';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { dbDisposableEmailDomains, usersCollection } from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection, dbDisposableEmailDomains],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n }\n});\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const packageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n version: packageJson.default.version,\n environmentId\n })\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/index.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/auth/disposableEmails.ts","../src/rate-limit/db.ts","../src/rate-limit/rules.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/auth/user.ts","../src/migration/db.ts","../src/migration/index.ts","../src/rate-limit/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","type","handler","permissions","runMethod","args","context","method","transaction","startTransaction","response","error","Module","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","authenticate","userDoc","createRouteHandler","req","res","key","value","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getConfig","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","connectionInfo","getClientIp","forwardedFor","directIp","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","isDisposableEmail","email","emailParts","domain","updateDisposableEmailListCron","domains","batchSize","i","batch","dbRateLimits","allRules","initRateLimits","consumeRateLimit","bucket","rules","rule","checkRateLimitRule","createError","createRateLimitError","record","currentWindowStart","count","modifier","getCount","prevWindowStart","currentWindowCount","prevWindowCount","prevWindowWeight","weight","handleSignupWithPassword","password","existingUser","existingEmail","e","ip","hash","bcrypt","handleLoginWithPassword","passwordHash","incorrectCredentialsError","handleLogout","getOwnProfile","_args","profile","user_default","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","rate_limit_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","getRateLimits","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","serviceEndpoint","packageJson"],"mappings":"yoBAAO,SAASA,EAAAA,EAAW,CACzB,OAAO,OAAO,MAAW,EAAA,QAC3B,CAEO,SAASC,GAAgB,CAC9B,GAAI,CAACD,EAAAA,GACH,MAAM,IAAI,KAAM,CAAA,gDAAgD,CAEpE,CCNA,IAAME,GAAU,IAAI,GAAA,CACdC,EAA6B,CACjC,aAAA,CAAe,IACf,CAAA,eAAA,CAAiB,IACnB,CAEO,CAAA,SAASC,EAAUC,CAAAA,CAAAA,CAAqCC,EAAqC,CAClGH,CAAAA,CAAa,aAAgBG,CAAAA,CAAAA,CAAc,cAC3CH,CAAa,CAAA,eAAA,CAAkBG,CAAc,CAAA,eAAA,CAE7C,OAAW,CAACC,CAAAA,CAAMC,CAAU,CAAA,GAAK,OAAO,OAAQH,CAAAA,CAAK,CACnDH,CAAAA,EAAAA,CAAQ,IAAIK,CAAMC,CAAAA,CAAU,EAEhC,CAEO,SAASC,CAA0B,EAAA,CACxC,OAAON,CAAa,CAAA,eAAA,CAAkB,CAACA,CAAa,CAAA,eAAe,CAAI,CAAA,EACzE,CAEO,SAASO,EAA+B,EAAA,CAC7C,OAAOP,CAAa,CAAA,aAAA,CAAgB,CAACA,CAAAA,CAAa,aAAa,CAAI,CAAA,EACrE,CAMO,SAASQ,EAAcN,CAAAA,CAAAA,CAAeO,CAAmC,CAAA,CAC9E,IAAMC,CAAoBD,CAAAA,CAAAA,CAAoB,IAAKE,CAAAA,CAAAA,EAAc,CAACC,EAAcV,CAAAA,CAAAA,CAAOS,CAAU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AI,CAAC9D,CACH,CAAA,MAAM,IAAI,KAAA,CAAM,6DAA6D,CAG/E,CAAA,IAAA,IAAWkG,CAAS3G,IAAAA,CAAAA,CAClB2G,CAAM,CAAA,IAAA,CAAKlG,CAAM,EAErB,CAEA,SAASqO,EAAAA,EAA+B,CACtC,IAAMpH,CAAuB,CAAA,EAE7B,CAAA,OAAI,QAAQ,GAAI,CAAA,WAAA,EACdA,CAAQ,CAAA,IAAA,CAAK,CACX,GAAA,CAAK,oBACL,CAAA,IAAA,CAAM,SACN,KAAO,CAAA,OAAA,CAAQ,GAAI,CAAA,WACrB,CAAC,CAAA,CAGIA,CACT,CAEA,eAAeqG,EAAgB,EAAA,CAG7B,GAF0B,OAAA,CAAQ,GAAI,CAAA,0BAAA,GAA+B,OAE9C,CAAA,CACrB,IAAMsB,CAAkB,CAAA,OAAA,CAAQ,GAAI,CAAA,0BAAA,EAA8B,6BAC5DZ,CAAAA,CAAAA,CAAgB,OAAQ,CAAA,GAAA,CAAI,yBAE5Ba,CAAc,CAAA,MAAa,OAAA,uBAAoB,CAErD,CAAA,MAAM,KAAM,CAAA,CAAA,EAAGD,CAAe,CAAwB,oBAAA,CAAA,CAAA,CACpD,MAAQ,CAAA,MAAA,CACR,OAAS,CAAA,CACP,cAAgB,CAAA,kBAClB,EACA,IAAM,CAAA,IAAA,CAAK,SAAU,CAAA,CACnB,OAASC,CAAAA,CAAAA,CAAY,OAAQ,CAAA,OAAA,CAC7B,cAAAb,CACF,CAAC,CACH,CAAC,EACH,CACF","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /** @internal */\n public readonly rateLimits: RateLimitRule[];\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {},\n rateLimits = []\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema,\n rateLimits?: RateLimitRule[]\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n * \n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: Filter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Create a new user\n * const result = await dbUsers.insertOne({\n * handle: 'john_doe',\n * emails: [{ address: 'john@example.com', verified: false }],\n * createdAt: new Date(),\n * authMethods: {\n * password: { hash: 'hashed_password' }\n * }\n * });\n * \n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from '@/telemetry';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\n/**\n * Two-bucket sliding window approximation to track rate limits.\n * This is a trade-off between storage and accuracy.\n * We're not keeping exact event logs, so we can't track the exact number of events in a window.\n * Instead, we're adding a weighted average from the previous window to the current window.\n */\nexport const dbRateLimits = new Store('_modelenceRateLimits', {\n schema: {\n bucket: schema.string(),\n type: schema.enum(['ip', 'user']),\n value: schema.string(),\n windowMs: schema.number(),\n\n windowStart: schema.date(),\n windowCount: schema.number(),\n prevWindowCount: schema.number(),\n\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { bucket: 1, type: 1, value: 1, windowMs: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ]\n});\n","import { RateLimitRule, RateLimitType } from './types';\nimport { dbRateLimits } from './db';\n\nlet allRules: Array<RateLimitRule> = [];\n\nexport function initRateLimits(rateLimits: RateLimitRule[]) {\n if (allRules.length > 0) {\n throw new Error('Duplicate call to initRateLimits - already initialized');\n }\n\n allRules = rateLimits;\n}\n\nexport async function consumeRateLimit(\n { bucket, type, value }: { bucket: string, type: RateLimitType, value: string }\n) {\n const rules = allRules.filter(rule => rule.bucket === bucket && rule.type === type);\n\n for (const rule of rules) {\n await checkRateLimitRule(rule, value);\n }\n}\n\n// Two-bucket sliding window approximation to track rate limits.\nasync function checkRateLimitRule(rule: RateLimitRule, value: string, createError?: () => Error) {\n const createRateLimitError = () => {\n return createError ? createError() : new Error(`Rate limit exceeded for ${rule.bucket}`);\n };\n\n const record = await dbRateLimits.findOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n });\n\n const now = Date.now();\n const currentWindowStart = Math.floor(now / rule.window) * rule.window;\n\n if (record) {\n const { count, modifier } = getCount(record, currentWindowStart, now);\n if (count >= rule.limit) {\n throw createRateLimitError();\n }\n\n await dbRateLimits.updateOne(record._id.toString(), modifier);\n } else {\n if (rule.limit < 1) {\n throw createRateLimitError();\n }\n\n await dbRateLimits.insertOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + rule.window + rule.window),\n });\n }\n}\n\nfunction getCount(record: typeof dbRateLimits['Doc'], currentWindowStart: number, now: number) {\n const prevWindowStart = currentWindowStart - record.windowMs;\n \n if (record.windowStart.getTime() === currentWindowStart) {\n const currentWindowCount = record.windowCount;\n const prevWindowCount = record.prevWindowCount;\n const prevWindowWeight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: currentWindowCount + prevWindowCount * prevWindowWeight,\n modifier: {\n $inc: { windowCount: 1 },\n }\n };\n }\n \n if (record.windowStart.getTime() === prevWindowStart) {\n const weight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: record.windowCount * weight,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: record.windowCount,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n return {\n count: 0,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { isDisposableEmail } from './disposableEmails';\nimport { consumeRateLimit } from '../rate-limit/rules';\n\nexport async function handleSignupWithPassword(args: Args, { user, connectionInfo }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n if (await isDisposableEmail(email)) {\n throw new Error('Please use a permanent email address');\n }\n\n // TODO: captcha check\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signup',\n type: 'ip',\n value: ip,\n });\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { dbDisposableEmailDomains, usersCollection } from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\nimport { time } from '../time';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection, dbDisposableEmailDomains],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n },\n rateLimits: [{\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(5),\n limit: 2,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(15),\n limit: 20,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.days(1),\n limit: 200,\n }],\n});\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","import { Module } from '../app/module';\nimport { dbRateLimits } from './db';\n\nexport default new Module('_system.rateLimit', {\n stores: [dbRateLimits],\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport rateLimitModule from '../rate-limit';\nimport { initRateLimits } from '../rate-limit/rules';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule, rateLimitModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n const rateLimits = getRateLimits(combinedModules);\n initRateLimits(rateLimits);\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getRateLimits(modules: Module[]) {\n return modules.flatMap(module => module.rateLimits);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const packageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n version: packageJson.default.version,\n environmentId\n })\n });\n }\n}\n"]}
|
package/package.json
CHANGED
package/dist/package-X5TSICV7.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var s="module",i="modelence",n="0.5.3-dev.1",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:m,repository:a,author:u,license:y,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
-
export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-X5TSICV7.js.map
|
|
3
|
-
//# sourceMappingURL=package-X5TSICV7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,aAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,CAAS,CACP,MACA,CAAA,UACF,EACAC,CAAO,CAAA,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,OACT,GAAO,CAAA,cAAA,CACP,eAAkB,eAClB,CAAA,IAAA,CAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CACAC,CAAAA,CAAAA,CAAc,CACZ,IAAQ,CAAA,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WACVC,CAAAA,CAAAA,CAAW,yBACXC,CAAQ,CAAA,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBACZC,CAAAA,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,SACnB,eAAiB,CAAA,QAAA,CACjB,iBAAkB,QAClB,CAAA,iBAAA,CAAmB,UACnB,aAAe,CAAA,SAAA,CACf,eAAgB,SAChB,CAAA,kBAAA,CAAoB,UACpB,kCAAoC,CAAA,SAAA,CACpC,4BAA6B,SAC7B,CAAA,KAAA,CAAS,UACT,WAAa,CAAA,SAAA,CACb,UAAc,CAAA,QAChB,EACAC,CAAgB,CAAA,CACd,gBAAiB,SACjB,CAAA,sBAAA,CAAwB,SACxB,QAAY,CAAA,QAAA,CACZ,OAAU,QACV,CAAA,SAAA,CAAa,UACb,MAAU,CAAA,SAAA,CACV,mBAAoB,QACpB,CAAA,OAAA,CAAW,UACX,UAAY,CAAA,SAAA,CACZ,IAAQ,CAAA,QAAA,CACR,QAAW,QACX,CAAA,IAAA,CAAQ,UACR,IAAQ,CAAA,QAAA,CACR,IAAO,SACP,CAAA,IAAA,CAAQ,SACR,oBAAsB,CAAA,QAAA,CACtB,QAAW,SACX,CAAA,uBAAA,CAAyB,UACzB,GAAO,CAAA,SAAA,CACP,QAAW,QACb,CAAA,CACAC,CAAoB,CAAA,CAClB,MAAS,UACT,CAAA,WAAA,CAAa,UACf,CA7EFC,CAAAA,CAAAA,CAAA,CACE,IAAAlB,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,OAAA,CAAAC,EACA,WAAAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAOA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAsBA,iBAAAC,CAIF","file":"package-X5TSICV7.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.3-dev.1\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|