@modelence/react-query 1.2.3 → 1.2.5

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