modelence 0.7.0-dev.0 → 0.7.0-dev.2

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.
@@ -1,90 +1,40 @@
1
1
  #!/usr/bin/env node
2
- import {s}from'../chunk-VQSLCX5F.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import*as d from'path';import d__default,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import Y from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import {parse as parse$1}from'@babel/parser';import Q from'@babel/traverse';import Ie from'archiver';import je from'open';var I=".modelence.env";async function oe(e,t){let o=await fetch(`${t}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!o.ok){let i=await o.text();throw new Error(i||`Request failed with status ${o.status}`)}return o.json()}async function re(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${I} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function se(e){return String(e).replace(/"/g,'\\"')}async function ie(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function z(e){try{let t=join(process.cwd(),I),o={};try{let r=await promises.readFile(t,"utf8");o=parse(r),await ie(t),await re()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let i=await oe(e.token,e.host),s={...o,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:i.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:i.serviceToken,MODELENCE_CONTAINER_ID:i.containerId},a=Object.entries(s).map(([r,n])=>`${r}="${se(n)}"`).join(`
2
+ import {s}from'../chunk-TKYF2MS5.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import*as f from'path';import f__default,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import Z from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import*as r from'typescript';import Fe from'archiver';import $e from'open';var I=".modelence.env";async function ne(e,t){let o=await fetch(`${t}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!o.ok){let n=await o.text();throw new Error(n||`Request failed with status ${o.status}`)}return o.json()}async function oe(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${I} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function re(e){return String(e).replace(/"/g,'\\"')}async function se(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function A(e){try{let t=join(process.cwd(),I),o={};try{let l=await promises.readFile(t,"utf8");o=parse(l),await se(t),await oe()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let n=await ne(e.token,e.host),s={...o,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:n.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:n.serviceToken,MODELENCE_CONTAINER_ID:n.containerId},a=Object.entries(s).map(([l,i])=>`${l}="${re(i)}"`).join(`
3
3
  `);await promises.writeFile(t,a.trim()+`
4
- `),console.log(`Successfully configured ${I} file`);}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var N=null,F=null;function pe(){if(!N)throw new Error("Environment variables not loaded");return N}function _(){if(!F)throw new Error("Configuration not loaded");return F}function A(e){return `${pe().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function x(){let{serverDir:e,serverEntry:t}=_();return join(e,t).replace(/\\/g,"/")}function U(){return _().postBuildCommand}function G(e){let t=L("build");return t.replace(/\\/g,"/")}function v(e){return join(process.cwd(),e).replace(/\\/g,"/")}function L(e){let t=v(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function j(){try{let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");F=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(o);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await Y.readFile(join(process.cwd(),".modelence.env"),"utf-8");N=parse(e);}catch(e){if(e.code==="ENOENT")N={};else throw e}}var R=Q.default||Q;async function W(e){let t=d.dirname(e),o=await promises.readFile(e,"utf-8"),i=parse$1(o,{sourceType:"module",plugins:["typescript","jsx"]}),s=new Map,a=[];R(i,{ImportDeclaration(n){let c=n.node.source.value;for(let p of n.node.specifiers)(p.type==="ImportDefaultSpecifier"||p.type==="ImportSpecifier")&&s.set(p.local.name,c);}}),R(i,{CallExpression(n){let c=n.node.callee;if(c.type==="Identifier"&&c.name==="startApp"){let p=n.node.arguments;if(p.length>0&&p[0].type==="ObjectExpression"){let u=p[0].properties.find(m=>m.type==="ObjectProperty"&&m.key.type==="Identifier"&&m.key.name==="modules");if(u&&u.value.type==="ArrayExpression"){for(let m of u.value.elements)if(m?.type==="Identifier"){let y=m.name,h=s.get(y);h&&a.push({name:y,importPath:h,serverDir:t});}}}}}});let r=[];for(let n of a){let c=await ue(n.importPath,n.serverDir);c&&r.push(c);}return r}async function ue(e,t){try{let o=await me(e,t),i=await promises.readFile(o,"utf-8"),s=parse$1(i,{sourceType:"module",plugins:["typescript","jsx"]}),a="",r=[],n=[];return R(s,{NewExpression(c){let p=c.node.callee;if(p.type==="Identifier"&&p.name==="Module"){let u=c.node.arguments;if(u.length>0&&u[0].type==="StringLiteral"&&(a=u[0].value),u.length>1&&u[1].type==="ObjectExpression"){let m=u[1],y=m.properties.find(l=>l.type==="ObjectProperty"&&l.key.type==="Identifier"&&l.key.name==="queries");if(y&&y.value.type==="ObjectExpression"){for(let l of y.value.properties)if((l.type==="ObjectProperty"||l.type==="ObjectMethod")&&(l.key.type==="Identifier"||l.key.type==="StringLiteral")){let $=l.key.type==="Identifier"?l.key.name:l.key.value,T=V(l,i);r.push({name:$,fullName:`${a}.${$}`,argsType:T.argsType,returnType:T.returnType});}}let h=m.properties.find(l=>l.type==="ObjectProperty"&&l.key.type==="Identifier"&&l.key.name==="mutations");if(h&&h.value.type==="ObjectExpression"){for(let l of h.value.properties)if((l.type==="ObjectProperty"||l.type==="ObjectMethod")&&(l.key.type==="Identifier"||l.key.type==="StringLiteral")){let $=l.key.type==="Identifier"?l.key.name:l.key.value,T=V(l,i);n.push({name:$,fullName:`${a}.${$}`,argsType:T.argsType,returnType:T.returnType});}}}}}}),a?{name:a,queries:r,mutations:n,filePath:o}:null}catch(o){return console.error(`Failed to analyze module file ${e}:`,o),null}}function V(e,t){let o,i,s;if(e.type==="ObjectMethod")s=e.body;else if(e.type==="ObjectProperty"){let n=e.value;(n.type==="ArrowFunctionExpression"||n.type==="FunctionExpression")&&(s=n.body);}if(!s)return {argsType:o,returnType:i};let a=s.start,r=s.end;if(a!==void 0&&r!==void 0){let n=t.substring(a,r),p=/z\.object\(\s*\{([^}]+)\}\s*\)\.parse\(|\.object\(\s*\{([^}]+)\}\s*\)\.parse\(/g.exec(n);if(p){let u=p[1]||p[2];o=de(u);}n.includes("return {")?i="Record<string, unknown>":n.includes("return [")&&(i="unknown[]");}return {argsType:o,returnType:i}}function de(e){let t=[],o=/(\w+):\s*z\.(\w+)\([^)]*\)([^,}\n]*)/g,i;for(;(i=o.exec(e))!==null;){let s=i[1],a=i[2],r=i[3]||"",n="unknown";switch(a){case "string":n="string";break;case "number":n="number";break;case "boolean":n="boolean";break;case "date":n="Date";break;case "array":n="unknown[]";break;case "object":n="Record<string, unknown>";break}let p=r.includes(".optional()")?`${s}?: ${n}`:`${s}: ${n}`;t.push(p);}return t.length>0?`{ ${t.join("; ")} }`:"Record<string, unknown>"}async function me(e,t){if(e.startsWith("./")||e.startsWith("../")){let o=d.resolve(t,e),i=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let s of i){let a=o+s;try{if((await promises.stat(a)).isFile())return a}catch{continue}}throw new Error(`Could not resolve module path: ${e} (tried ${o})`)}throw new Error(`Cannot resolve package import: ${e}`)}function Z(e){return e.map(t=>fe(t))}function fe(e){let t=E(e.name),o=`use${t}Store`,i=ge(e.queries),s=ye(e.mutations),a=`// Generated by Modelence - DO NOT EDIT MANUALLY
4
+ `),console.log(`Successfully configured ${I} file`);}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var S=null,L=null;function le(){if(!S)throw new Error("Environment variables not loaded");return S}function _(){if(!L)throw new Error("Configuration not loaded");return L}function R(e){return `${le().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function $(){let{serverDir:e,serverEntry:t}=_();return join(e,t).replace(/\\/g,"/")}function U(){return _().postBuildCommand}function G(e){let t=z("build");return t.replace(/\\/g,"/")}function E(e){return join(process.cwd(),e).replace(/\\/g,"/")}function z(e){let t=E(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function T(){try{let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");L=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(o);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await Z.readFile(join(process.cwd(),".modelence.env"),"utf-8");S=parse(e);}catch(e){if(e.code==="ENOENT")S={};else throw e}}async function J(e){let t=f.dirname(e),o=await promises.readFile(e,"utf-8"),n=r.createSourceFile(e,o,r.ScriptTarget.Latest,true),s=new Map,a=[];function l(c){if(r.isImportDeclaration(c)){let p=c.moduleSpecifier.text;if(c.importClause&&(c.importClause.name&&s.set(c.importClause.name.text,p),c.importClause.namedBindings&&r.isNamedImports(c.importClause.namedBindings)))for(let m of c.importClause.namedBindings.elements)s.set(m.name.text,p);}if(r.isCallExpression(c)&&r.isIdentifier(c.expression)&&c.expression.text==="startApp"){let p=c.arguments[0];if(p&&r.isObjectLiteralExpression(p)){let m=p.properties.find(d=>r.isPropertyAssignment(d)&&r.isIdentifier(d.name)&&d.name.text==="modules");if(m&&r.isArrayLiteralExpression(m.initializer)){for(let d of m.initializer.elements)if(r.isIdentifier(d)){let x=d.text,w=s.get(x);w&&a.push({name:x,importPath:w,serverDir:t});}}}}r.forEachChild(c,l);}l(n);let i=[];for(let c of a){let p=await ue(c.importPath,c.serverDir);p&&i.push(p);}return i}async function ue(e,t){try{let p=function(m){if(r.isNewExpression(m)&&r.isIdentifier(m.expression)&&m.expression.text==="Module"){let d=m.arguments;if(d&&d.length>0&&r.isStringLiteral(d[0])&&(l=d[0].text),d&&d.length>1&&r.isObjectLiteralExpression(d[1])){let x=d[1],w=x.properties.find(u=>r.isPropertyAssignment(u)&&r.isIdentifier(u.name)&&u.name.text==="queries");if(w&&r.isObjectLiteralExpression(w.initializer)){for(let u of w.initializer.properties)if(r.isPropertyAssignment(u)||r.isMethodDeclaration(u)){let g=r.isIdentifier(u.name)||r.isStringLiteral(u.name)?u.name.text:"";if(g){let M=V(u,s,a);i.push({name:g,fullName:`${l}.${g}`,argsType:M.argsType,returnType:M.returnType});}}}let D=x.properties.find(u=>r.isPropertyAssignment(u)&&r.isIdentifier(u.name)&&u.name.text==="mutations");if(D&&r.isObjectLiteralExpression(D.initializer)){for(let u of D.initializer.properties)if(r.isPropertyAssignment(u)||r.isMethodDeclaration(u)){let g=r.isIdentifier(u.name)||r.isStringLiteral(u.name)?u.name.text:"";if(g){let M=V(u,s,a);c.push({name:g,fullName:`${l}.${g}`,argsType:M.argsType,returnType:M.returnType});}}}}}r.forEachChild(m,p);};var o=p;let n=await pe(e,t),s=await promises.readFile(n,"utf-8"),a=r.createSourceFile(n,s,r.ScriptTarget.Latest,!0),l="",i=[],c=[];return p(a),l?{name:l,queries:i,mutations:c,filePath:n}:null}catch(n){return console.error(`Failed to analyze module file ${e}:`,n),null}}function V(e,t,o){let n,s,a;if(r.isMethodDeclaration(e)&&e.body)a=e.body;else if(r.isPropertyAssignment(e)){let d=e.initializer;(r.isArrowFunction(d)||r.isFunctionExpression(d))&&(a=d.body);}if(!a)return {argsType:n,returnType:s};let l=a.getStart(o),i=a.getEnd(),c=t.substring(l,i),m=/z\.object\(\s*\{([^}]+)\}\s*\)\.parse\(|\.object\(\s*\{([^}]+)\}\s*\)\.parse\(/g.exec(c);if(m){let d=m[1]||m[2];n=de(d);}return c.includes("return {")?s="Record<string, unknown>":c.includes("return [")&&(s="unknown[]"),{argsType:n,returnType:s}}function de(e){let t=[],o=/(\w+):\s*z\.(\w+)\([^)]*\)([^,}\n]*)/g,n;for(;(n=o.exec(e))!==null;){let s=n[1],a=n[2],l=n[3]||"",i="unknown";switch(a){case "string":i="string";break;case "number":i="number";break;case "boolean":i="boolean";break;case "date":i="Date";break;case "array":i="unknown[]";break;case "object":i="Record<string, unknown>";break}let p=l.includes(".optional()")?`${s}?: ${i}`:`${s}: ${i}`;t.push(p);}return t.length>0?`{ ${t.join("; ")} }`:"Record<string, unknown>"}async function pe(e,t){if(e.startsWith("./")||e.startsWith("../")){let o=f.resolve(t,e),n=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let s of n){let a=o+s;try{if((await promises.stat(a)).isFile())return a}catch{continue}}throw new Error(`Could not resolve module path: ${e} (tried ${o})`)}throw new Error(`Cannot resolve package import: ${e}`)}function q(e){return e.map(t=>me(t))}function me(e){let o=`use${Q(e.name)}Store`,n=fe(e.queries),s=ge(e.mutations),a=`// Generated by Modelence - DO NOT EDIT MANUALLY
5
5
  import { create } from 'zustand';
6
6
  import { callMethod } from 'modelence/client';
7
7
 
8
- /**
9
- * Zustand store for ${e.name} module
10
- * Auto-generated from module queries and mutations
11
- */
12
-
13
- // Query methods
14
- ${i.methods}
15
-
16
- // Mutation methods
17
- ${s.methods}
18
-
19
- // Store interface
20
- interface ${t}Store {
21
- // Queries
22
- ${i.interface}
8
+ export const ${o} = create((set, get) => ({
9
+ ${n.dataFields}
10
+ ${s.dataFields}
23
11
 
24
- // Mutations
25
- ${s.interface}
26
- }
27
-
28
- // Create the store
29
- export const ${o} = create<${t}Store>((set, get) => ({
30
- // Query implementations
31
- ${i.implementations}
32
-
33
- // Mutation implementations
12
+ ${n.implementations}
34
13
  ${s.implementations}
35
14
  }));
36
- `,r=`// Generated by Modelence - DO NOT EDIT MANUALLY
37
-
38
- /**
39
- * Type definitions for ${e.name} module store
40
- */
41
-
42
- // Query argument types
43
- ${i.types}
44
-
45
- // Mutation argument types
46
- ${s.types}
47
-
48
- // Query return types - these should be manually typed or inferred from the server
49
- ${i.returnTypes}
50
-
51
- // Mutation return types - these should be manually typed or inferred from the server
52
- ${s.returnTypes}
53
- `;return {fileName:`${e.name}.ts`,content:a,typesContent:r}}function ge(e){if(e.length===0)return {methods:"// No queries defined",interface:" // No queries",implementations:" // No queries",types:"// No queries",returnTypes:"// No queries"};let t=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return `/**
54
- * Query: ${r.name}
55
- * Call the ${r.fullName} method on the server
56
- */
57
- async function ${r.name}(args: ${n} = {} as ${n}) {
58
- return callMethod('${r.fullName}', args);
59
- }`}).join(`
60
-
61
- `),o=e.map(r=>{let n=r.argsType||"Record<string, unknown>",c=r.returnType||"unknown";return ` ${r.name}: (args?: ${n}) => Promise<${c}>;`}).join(`
62
- `),i=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return ` ${r.name}: async (args = {} as ${n}) => callMethod('${r.fullName}', args),`}).join(`
63
- `),s=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return `export type ${E(r.name)}Args = ${n};`}).join(`
64
- `),a=e.map(r=>{let n=r.returnType||"unknown";return `export type ${E(r.name)}Result = ${n};`}).join(`
65
- `);return {methods:t,interface:o,implementations:i,types:s,returnTypes:a}}function ye(e){if(e.length===0)return {methods:"// No mutations defined",interface:" // No mutations",implementations:" // No mutations",types:"// No mutations",returnTypes:"// No mutations"};let t=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return `/**
66
- * Mutation: ${r.name}
67
- * Call the ${r.fullName} method on the server
68
- */
69
- async function ${r.name}(args: ${n} = {} as ${n}) {
70
- return callMethod('${r.fullName}', args);
71
- }`}).join(`
72
-
73
- `),o=e.map(r=>{let n=r.argsType||"Record<string, unknown>",c=r.returnType||"unknown";return ` ${r.name}: (args?: ${n}) => Promise<${c}>;`}).join(`
74
- `),i=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return ` ${r.name}: async (args = {} as ${n}) => callMethod('${r.fullName}', args),`}).join(`
75
- `),s=e.map(r=>{let n=r.argsType||"Record<string, unknown>";return `export type ${E(r.name)}Args = ${n};`}).join(`
76
- `),a=e.map(r=>{let n=r.returnType||"unknown";return `export type ${E(r.name)}Result = ${n};`}).join(`
77
- `);return {methods:t,interface:o,implementations:i,types:s,returnTypes:a}}function E(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function q(e){return `// Generated by Modelence - DO NOT EDIT MANUALLY
15
+ `;return {fileName:`${e.name}.ts`,content:a}}function fe(e){if(e.length===0)return {dataFields:"",implementations:""};let t=e.map(n=>{let s=n.returnType||"unknown";return ` ${n.name}Data: null as ${s} | null,`}).join(`
16
+ `),o=e.map(n=>{let s=n.argsType||"Record<string, unknown>";return ` ${n.name}: async (args = {} as ${s}) => {
17
+ const result = await callMethod('${n.fullName}', args);
18
+ set({ ${n.name}Data: result });
19
+ return result;
20
+ },`}).join(`
21
+ `);return {dataFields:t,implementations:o}}function ge(e){if(e.length===0)return {dataFields:"",implementations:""};let t=e.map(n=>{let s=n.returnType||"unknown";return ` ${n.name}Data: null as ${s} | null,`}).join(`
22
+ `),o=e.map(n=>{let s=n.argsType||"Record<string, unknown>";return ` ${n.name}: async (args = {} as ${s}) => {
23
+ const result = await callMethod('${n.fullName}', args);
24
+ set({ ${n.name}Data: result });
25
+ return result;
26
+ },`}).join(`
27
+ `);return {dataFields:t,implementations:o}}function Q(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function W(e){return `// Generated by Modelence - DO NOT EDIT MANUALLY
78
28
  /**
79
29
  * Auto-generated zustand stores for all modules
80
30
  * Import these stores in your client-side code to interact with the server
81
31
  */
82
32
 
83
- ${e.map(o=>`export { ${`use${E(o.name)}Store`} } from './${o.name}';`).join(`
33
+ ${e.map(o=>`export { ${`use${Q(o.name)}Store`} } from './${o.name}';`).join(`
84
34
  `)}
85
- `}async function S(e={}){let{serverPath:t=await he(),outputDir:o=d.join(process.cwd(),".modelence/stores"),generateTypes:i=true}=e;console.log("\u{1F504} Generating zustand stores from modules...");try{await promises.mkdir(o,{recursive:!0}),console.log(` Analyzing modules from: ${t}`);let s=await W(t);if(s.length===0){console.log(" \u26A0\uFE0F No modules found. Skipping store generation.");return}console.log(` Found ${s.length} module(s): ${s.map(c=>c.name).join(", ")}`);let a=Z(s);for(let c of a){let p=d.join(o,c.fileName);if(await promises.writeFile(p,c.content,"utf-8"),console.log(` \u2713 Generated: ${c.fileName}`),i){let u=d.join(o,c.fileName.replace(".ts",".types.ts"));await promises.writeFile(u,c.typesContent,"utf-8"),console.log(` \u2713 Generated: ${c.fileName.replace(".ts",".types.ts")}`);}}let r=q(s),n=d.join(o,"index.ts");await promises.writeFile(n,r,"utf-8"),console.log(" \u2713 Generated: index.ts"),console.log(`\u2705 Zustand stores generated successfully!
86
- `),console.log(" Import them in your client code:"),console.log(` import { use${we(s[0].name)}Store } from '.modelence/stores';
87
- `);}catch(s){throw console.error("\u274C Failed to generate zustand stores:",s),s}}async function he(){try{let t=d.join(process.cwd(),"modelence.config.ts"),o=await promises.readFile(t,"utf-8"),i=o.match(/serverDir:\s*['"](.+?)['"]/),s=o.match(/serverEntry:\s*['"](.+?)['"]/);if(i&&s){let a=d.join(process.cwd(),i[1],s[1]);return await promises.access(a),a}}catch{}let e=[d.join(process.cwd(),"src/server/app.ts"),d.join(process.cwd(),"src/server/index.ts"),d.join(process.cwd(),"server/app.ts"),d.join(process.cwd(),"server/index.ts")];for(let t of e)try{return await promises.access(t),t}catch{}throw new Error("Could not find server entry file. Make sure your modelence.config.ts is configured correctly.")}function we(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function ke(){let e=U();if(e){console.log("Running post-build command..."),execSync(e);return}await Ne();}async function Ne(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:d__default.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function xe(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[x()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function O(){console.log("Building Modelence project...");try{let e=G();await Y.rm(e,{recursive:!0,force:!0}),console.log(`
88
- \u{1F527} Generating zustand stores...`);try{await S();}catch(t){console.warn(`
89
- \u26A0\uFE0F Store generation failed, continuing anyway...`),console.warn(t);}await xe(),await ke(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await Y.access(L());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function K(e){let t=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!t.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:i}=await t.json();console.log(`Please visit ${i} to authenticate`),console.log(`Code: ${o}`),await je(i);let s=await Oe(e,o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function Oe(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let a=await Pe(e,t);if(a)return a}catch(a){console.error("Error polling for CLI token:",a);}await new Promise(a=>setTimeout(a,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function Pe(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:i}=await o.json();return i}async function X(e){let t=process.cwd(),o=join(t,".modelence"),i=join(o,"tmp","bundle.zip"),s=e.host||A("");await O(),await Fe(i);let{token:a}=await K(s),{bundleName:r}=await Le(e.app,e.env,i,a,s);await promises.unlink(i),await Re(e.app,e.env,r,join(".modelence","build","app.mjs"),a,s);}async function Fe(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Ie("zip",{zlib:{level:9}});o.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),o.on("error",n=>{throw n});let i=new Promise((n,c)=>{t.on("close",n),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],a=["public","server",join(".modelence","build"),".next"];for(let n of s)await promises.access(v(n)).then(()=>true).catch(()=>false)&&o.file(v(n),{name:n});for(let n of a)await promises.access(v(n)).then(()=>true).catch(()=>false)&&o.directory(v(n),n);await o.finalize(),await i;let r=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(r.size/1024/1024).toFixed(2)} MB)`);}async function Le(e,t,o,i,s){let a=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!a.ok)throw console.error(await a.text()),new Error(`Failed to create upload URL: ${a.statusText}`);let{uploadUrl:r,bundleName:n}=await a.json(),c=await promises.readFile(o),p=await fetch(r,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!p.ok)throw new Error(`Failed to upload bundle: ${p.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function Re(e,t,o,i,s,a){let r=await fetch(`${a}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:i})});if(!r.ok)throw new Error(`Failed to trigger deployment: ${r.statusText}`);let{deploymentUrl:n}=await r.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${n}`);}async function H(){console.log("Starting Modelence dev server...");try{await S();}catch(o){console.warn("\u26A0\uFE0F Store generation failed, continuing anyway..."),console.warn(o);}let e=x(),t=d__default.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var Ve=fileURLToPath(import.meta.url),Je=dirname(Ve),We=JSON.parse(readFileSync(join(Je,"../../package.json"),"utf-8")),M=new Command().name("modelence").description("Modelence CLI tool").version(We.version);M.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await z(e);});M.command("build").description("Build the application").action(async()=>{await j(),await O();});M.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await j(),await X(e);});M.command("dev").description("Start development server").action(async()=>{await j(),await H();});M.parse(process.argv);//# sourceMappingURL=modelence.js.map
35
+ `}async function j(e={}){let{serverPath:t=await he(),outputDir:o=f.join(process.cwd(),".modelence/stores")}=e;console.log("\u{1F504} Generating zustand stores from modules...");try{await promises.mkdir(o,{recursive:!0}),console.log(` Analyzing modules from: ${t}`);let n=await J(t);if(n.length===0){console.log(" \u26A0\uFE0F No modules found. Skipping store generation.");return}console.log(` Found ${n.length} module(s): ${n.map(i=>i.name).join(", ")}`);let s=q(n);for(let i of s){let c=f.join(o,i.fileName);await promises.writeFile(c,i.content,"utf-8"),console.log(` \u2713 Generated: ${i.fileName}`);}let a=W(n),l=f.join(o,"index.ts");await promises.writeFile(l,a,"utf-8"),console.log(" \u2713 Generated: index.ts"),console.log(`\u2705 Zustand stores generated successfully!
36
+ `),console.log(" Import them in your client code:"),console.log(` import { use${we(n[0].name)}Store } from '.modelence/stores';
37
+ `);}catch(n){throw console.error("\u274C Failed to generate zustand stores:",n),n}}async function he(){try{let t=f.join(process.cwd(),"modelence.config.ts"),o=await promises.readFile(t,"utf-8"),n=o.match(/serverDir:\s*['"](.+?)['"]/),s=o.match(/serverEntry:\s*['"](.+?)['"]/);if(n&&s){let a=f.join(process.cwd(),n[1],s[1]);return await promises.access(a),a}}catch{}let e=[f.join(process.cwd(),"src/server/app.ts"),f.join(process.cwd(),"src/server/index.ts"),f.join(process.cwd(),"server/app.ts"),f.join(process.cwd(),"server/index.ts")];for(let t of e)try{return await promises.access(t),t}catch{}throw new Error("Could not find server entry file. Make sure your modelence.config.ts is configured correctly.")}function we(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function be(){let e=U();if(e){console.log("Running post-build command..."),execSync(e);return}await Ne();}async function Ne(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:f__default.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function Se(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[$()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function P(){console.log("Building Modelence project...");try{let e=G();await Z.rm(e,{recursive:!0,force:!0}),console.log(`
38
+ \u{1F527} Generating zustand stores...`);try{await j();}catch(t){console.warn(`
39
+ \u26A0\uFE0F Store generation failed, continuing anyway...`),console.warn(t);}await Se(),await be(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await Z.access(z());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function Y(e){let t=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!t.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:n}=await t.json();console.log(`Please visit ${n} to authenticate`),console.log(`Code: ${o}`),await $e(n);let s=await je(e,o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function je(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let a=await Pe(e,t);if(a)return a}catch(a){console.error("Error polling for CLI token:",a);}await new Promise(a=>setTimeout(a,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function Pe(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:n}=await o.json();return n}async function K(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||R("");await P(),await Oe(n);let{token:a}=await Y(s),{bundleName:l}=await Ie(e.app,e.env,n,a,s);await promises.unlink(n),await Le(e.app,e.env,l,join(".modelence","build","app.mjs"),a,s);}async function Oe(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Fe("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,c)=>{t.on("close",i),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],a=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(E(i)).then(()=>true).catch(()=>false)&&o.file(E(i),{name:i});for(let i of a)await promises.access(E(i)).then(()=>true).catch(()=>false)&&o.directory(E(i),i);await o.finalize(),await n;let l=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(l.size/1024/1024).toFixed(2)} MB)`);}async function Ie(e,t,o,n,s){let a=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!a.ok)throw console.error(await a.text()),new Error(`Failed to create upload URL: ${a.statusText}`);let{uploadUrl:l,bundleName:i}=await a.json(),c=await promises.readFile(o),p=await fetch(l,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!p.ok)throw new Error(`Failed to upload bundle: ${p.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function Le(e,t,o,n,s,a){let l=await fetch(`${a}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:n})});if(!l.ok)throw new Error(`Failed to trigger deployment: ${l.statusText}`);let{deploymentUrl:i}=await l.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}async function X(){console.log("Starting Modelence dev server...");try{await j();}catch(o){console.warn("\u26A0\uFE0F Store generation failed, continuing anyway..."),console.warn(o);}let e=$(),t=f__default.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var Ve=fileURLToPath(import.meta.url),Je=dirname(Ve),qe=JSON.parse(readFileSync(join(Je,"../../package.json"),"utf-8")),b=new Command().name("modelence").description("Modelence CLI tool").version(qe.version);b.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await A(e);});b.command("build").description("Build the application").action(async()=>{await T(),await P();});b.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await T(),await K(e);});b.command("dev").description("Start development server").action(async()=>{await T(),await X();});b.parse(process.argv);//# sourceMappingURL=modelence.js.map
90
40
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/codegen/astAnalyzer.ts","../../src/codegen/zustandGenerator.ts","../../src/codegen/index.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","traverse","babelTraverse","analyzeModulesFromServerFile","serverPath","C","serverCode","ast","parse","moduleImports","foundModules","nodePath","importPath","specifier","callee","args","modulesProperty","prop","element","moduleName","analyzedModules","moduleInfo","analyzed","analyzeModuleFile","fullPath","resolveModulePath","moduleCode","queries","mutations","queriesProperty","queryName","typeInfo","extractMethodTypes","mutationsProperty","mutationName","sourceCode","argsType","returnType","functionBody","start","end","methodSource","zodMatch","schemaContent","convertZodSchemaToTypeScript","schemaStr","fields","fieldPattern","match","fieldName","zodType","modifiers","tsType","fieldDef","resolved","extensions","ext","candidate","generateZustandStores","modules","module","generateStoreForModule","storeName","toPascalCase","hookName","queriesSection","generateQueriesSection","mutationsSection","generateMutationsSection","content","typesContent","methods","q","interfaceDef","implementations","types","returnTypes","m","str","word","generateIndexFile","generateStores","findServerPath","outputDir","generateTypes","stores","store","storePath","typesPath","indexContent","indexPath","configContent","serverDirMatch","serverEntryMatch","possiblePaths","p","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","package_default","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","tsxPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";+nBAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,EAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,EAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAA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,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,uCAAuC,CAAA,CACnD,cAAA,CAAe,qBAAA,CAAuB,uBAAuB,CAAA,CAC7D,OAAO,mBAAA,CAAqB,gBAAA,CAAkB,6BAA6B,CAAA,CAC3E,MAAA,CAAO,MAAOpL,GAAY,CACzB,MAAMD,CAAAA,CAAMC,CAAO,EACrB,CAAC,EAEHoL,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,uBAAuB,CAAA,CACnC,MAAA,CAAO,SAAY,CAClB,MAAM7J,CAAAA,EAAQ,CACd,MAAMiH,IACR,CAAC,CAAA,CAEH4C,CAAAA,CACG,OAAA,CAAQ,QAAQ,EAChB,WAAA,CAAY,2BAA2B,CAAA,CACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,EACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,CAAA,CAC5C,MAAA,CAAO,MAAOpL,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,GACN,MAAM2H,CAAAA,CAAOlJ,CAAO,EACtB,CAAC,CAAA,CAEHoL,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM7J,CAAAA,EAAQ,CACd,MAAMqJ,CAAAA,GACR,CAAC,CAAA,CAEHQ,CAAAA,CAAQ,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import { parse } from '@babel/parser';\nimport babelTraverse from '@babel/traverse';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { ObjectProperty } from '@babel/types';\n\n// Handle default export for traverse (CommonJS/ESM compatibility)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst traverse = (babelTraverse as any).default || babelTraverse;\n\nexport interface ModuleMetadata {\n name: string;\n queries: QueryMetadata[];\n mutations: MutationMetadata[];\n filePath: string;\n}\n\nexport interface QueryMetadata {\n name: string;\n fullName: string;\n argsType?: string; // TypeScript type string for arguments\n returnType?: string; // TypeScript type string for return value\n}\n\nexport interface MutationMetadata {\n name: string;\n fullName: string;\n argsType?: string;\n returnType?: string;\n}\n\n/**\n * Analyzes the server entry file using AST parsing to extract module metadata\n * This approach doesn't require running the code, making it safe for build-time\n */\nexport async function analyzeModulesFromServerFile(serverPath: string): Promise<ModuleMetadata[]> {\n const serverDir = path.dirname(serverPath);\n\n // Read the server file\n const serverCode = await fs.readFile(serverPath, 'utf-8');\n\n // Parse the file into an AST\n const ast = parse(serverCode, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n });\n\n // Find all module imports and their sources\n const moduleImports = new Map<string, string>(); // localName -> importPath\n const foundModules: ModuleInfo[] = [];\n\n traverse(ast, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ImportDeclaration(nodePath: any) {\n const importPath = nodePath.node.source.value;\n for (const specifier of nodePath.node.specifiers) {\n if (specifier.type === 'ImportDefaultSpecifier') {\n moduleImports.set(specifier.local.name, importPath);\n } else if (specifier.type === 'ImportSpecifier') {\n moduleImports.set(specifier.local.name, importPath);\n }\n }\n },\n });\n\n // Find the startApp call and extract modules array\n traverse(ast, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n CallExpression(nodePath: any) {\n const callee = nodePath.node.callee;\n if (callee.type === 'Identifier' && callee.name === 'startApp') {\n const args = nodePath.node.arguments;\n if (args.length > 0 && args[0].type === 'ObjectExpression') {\n const modulesProperty = args[0].properties.find(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (prop: any): prop is ObjectProperty =>\n prop.type === 'ObjectProperty' &&\n prop.key.type === 'Identifier' &&\n prop.key.name === 'modules'\n );\n\n if (modulesProperty && modulesProperty.value.type === 'ArrayExpression') {\n // Extract module names from the array\n for (const element of modulesProperty.value.elements) {\n if (element?.type === 'Identifier') {\n const moduleName = element.name;\n const importPath = moduleImports.get(moduleName);\n if (importPath) {\n // Found a module! Now we need to analyze its file\n foundModules.push({\n name: moduleName,\n importPath,\n serverDir,\n });\n }\n }\n }\n }\n }\n }\n },\n });\n\n // Analyze each module file to extract queries and mutations\n const analyzedModules: ModuleMetadata[] = [];\n for (const moduleInfo of foundModules) {\n const analyzed = await analyzeModuleFile(moduleInfo.importPath, moduleInfo.serverDir);\n if (analyzed) {\n analyzedModules.push(analyzed);\n }\n }\n\n return analyzedModules;\n}\n\ninterface ModuleInfo {\n name: string;\n importPath: string;\n serverDir: string;\n}\n\n/**\n * Analyzes a module file to extract its name, queries, and mutations\n */\nasync function analyzeModuleFile(\n importPath: string,\n serverDir: string\n): Promise<ModuleMetadata | null> {\n try {\n // Resolve the full path\n const fullPath = await resolveModulePath(importPath, serverDir);\n const moduleCode = await fs.readFile(fullPath, 'utf-8');\n\n // Parse the module file\n const ast = parse(moduleCode, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n });\n\n let moduleName = '';\n const queries: QueryMetadata[] = [];\n const mutations: MutationMetadata[] = [];\n\n // Find the Module constructor call (can be in export default or a variable)\n traverse(ast, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n NewExpression(nodePath: any) {\n const callee = nodePath.node.callee;\n if (callee.type === 'Identifier' && callee.name === 'Module') {\n const args = nodePath.node.arguments;\n\n // First argument is the module name\n if (args.length > 0 && args[0].type === 'StringLiteral') {\n moduleName = args[0].value;\n }\n\n // Second argument is the config object\n if (args.length > 1 && args[1].type === 'ObjectExpression') {\n const config = args[1];\n\n // Find queries property\n const queriesProperty = config.properties.find(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (prop: any): prop is ObjectProperty =>\n prop.type === 'ObjectProperty' &&\n prop.key.type === 'Identifier' &&\n prop.key.name === 'queries'\n );\n\n if (queriesProperty && queriesProperty.value.type === 'ObjectExpression') {\n for (const prop of queriesProperty.value.properties) {\n // Handle both ObjectProperty and ObjectMethod (async methods)\n if (\n (prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&\n (prop.key.type === 'Identifier' || prop.key.type === 'StringLiteral')\n ) {\n const queryName = prop.key.type === 'Identifier' ? prop.key.name : prop.key.value;\n\n // Extract type information from the method\n const typeInfo = extractMethodTypes(prop, moduleCode);\n\n queries.push({\n name: queryName,\n fullName: `${moduleName}.${queryName}`,\n argsType: typeInfo.argsType,\n returnType: typeInfo.returnType,\n });\n }\n }\n }\n\n // Find mutations property\n const mutationsProperty = config.properties.find(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (prop: any): prop is ObjectProperty =>\n prop.type === 'ObjectProperty' &&\n prop.key.type === 'Identifier' &&\n prop.key.name === 'mutations'\n );\n\n if (mutationsProperty && mutationsProperty.value.type === 'ObjectExpression') {\n for (const prop of mutationsProperty.value.properties) {\n // Handle both ObjectProperty and ObjectMethod (async methods)\n if (\n (prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&\n (prop.key.type === 'Identifier' || prop.key.type === 'StringLiteral')\n ) {\n const mutationName =\n prop.key.type === 'Identifier' ? prop.key.name : prop.key.value;\n\n // Extract type information from the method\n const typeInfo = extractMethodTypes(prop, moduleCode);\n\n mutations.push({\n name: mutationName,\n fullName: `${moduleName}.${mutationName}`,\n argsType: typeInfo.argsType,\n returnType: typeInfo.returnType,\n });\n }\n }\n }\n }\n }\n },\n });\n\n if (moduleName) {\n return {\n name: moduleName,\n queries,\n mutations,\n filePath: fullPath,\n };\n }\n\n return null;\n } catch (error) {\n console.error(`Failed to analyze module file ${importPath}:`, error);\n return null;\n }\n}\n\n/**\n * Extracts type information from a method (ObjectProperty or ObjectMethod)\n * Analyzes Zod schemas and return statements to infer types\n */\nfunction extractMethodTypes(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n prop: any,\n sourceCode: string\n): { argsType?: string; returnType?: string } {\n let argsType: string | undefined;\n let returnType: string | undefined;\n\n // Get the function body\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let functionBody: any;\n if (prop.type === 'ObjectMethod') {\n functionBody = prop.body;\n } else if (prop.type === 'ObjectProperty') {\n const value = prop.value;\n if (value.type === 'ArrowFunctionExpression' || value.type === 'FunctionExpression') {\n functionBody = value.body;\n }\n }\n\n if (!functionBody) {\n return { argsType, returnType };\n }\n\n // Extract the source code for this method\n const start = functionBody.start;\n const end = functionBody.end;\n if (start !== undefined && end !== undefined) {\n const methodSource = sourceCode.substring(start, end);\n\n // Look for Zod schema parsing patterns\n // Pattern: z.object({ field: z.string(), ... }).parse(args)\n const zodObjectPattern =\n /z\\.object\\(\\s*\\{([^}]+)\\}\\s*\\)\\.parse\\(|\\.object\\(\\s*\\{([^}]+)\\}\\s*\\)\\.parse\\(/g;\n const zodMatch = zodObjectPattern.exec(methodSource);\n\n if (zodMatch) {\n const schemaContent = zodMatch[1] || zodMatch[2];\n argsType = convertZodSchemaToTypeScript(schemaContent);\n }\n\n // Look for explicit return statements to infer return type\n // This is basic - in reality, we'd need full type inference\n if (methodSource.includes('return {')) {\n returnType = 'Record<string, unknown>'; // Generic object type\n } else if (methodSource.includes('return [')) {\n returnType = 'unknown[]'; // Array type\n }\n }\n\n return { argsType, returnType };\n}\n\n/**\n * Converts a Zod schema string to TypeScript type\n * This is a simplified version - handles common cases\n */\nfunction convertZodSchemaToTypeScript(schemaStr: string): string {\n const fields: string[] = [];\n\n // Parse field definitions like: fieldName: z.string().min(1)\n const fieldPattern = /(\\w+):\\s*z\\.(\\w+)\\([^)]*\\)([^,}\\n]*)/g;\n let match;\n\n while ((match = fieldPattern.exec(schemaStr)) !== null) {\n const fieldName = match[1];\n const zodType = match[2];\n const modifiers = match[3] || '';\n\n // Map Zod types to TypeScript types\n let tsType = 'unknown';\n switch (zodType) {\n case 'string':\n tsType = 'string';\n break;\n case 'number':\n tsType = 'number';\n break;\n case 'boolean':\n tsType = 'boolean';\n break;\n case 'date':\n tsType = 'Date';\n break;\n case 'array':\n tsType = 'unknown[]';\n break;\n case 'object':\n tsType = 'Record<string, unknown>';\n break;\n }\n\n // Check if optional\n const isOptional = modifiers.includes('.optional()');\n const fieldDef = isOptional ? `${fieldName}?: ${tsType}` : `${fieldName}: ${tsType}`;\n fields.push(fieldDef);\n }\n\n if (fields.length > 0) {\n return `{ ${fields.join('; ')} }`;\n }\n\n return 'Record<string, unknown>';\n}\n\n/**\n * Resolves a module import path to an absolute file path\n */\nasync function resolveModulePath(importPath: string, serverDir: string): Promise<string> {\n // Handle relative imports\n if (importPath.startsWith('./') || importPath.startsWith('../')) {\n const resolved = path.resolve(serverDir, importPath);\n\n // Try common extensions and index files\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.js'];\n for (const ext of extensions) {\n const candidate = resolved + ext;\n try {\n const stats = await fs.stat(candidate);\n if (stats.isFile()) {\n return candidate;\n }\n } catch {\n continue;\n }\n }\n\n throw new Error(`Could not resolve module path: ${importPath} (tried ${resolved})`);\n }\n\n // Handle package imports (node_modules)\n // For now, we'll skip these as modules should be local\n throw new Error(`Cannot resolve package import: ${importPath}`);\n}\n","import { ModuleMetadata, QueryMetadata, MutationMetadata } from './astAnalyzer';\n\nexport interface GeneratedStore {\n fileName: string;\n content: string;\n typesContent: string;\n}\n\n/**\n * Generates zustand stores for all modules\n */\nexport function generateZustandStores(modules: ModuleMetadata[]): GeneratedStore[] {\n return modules.map((module) => generateStoreForModule(module));\n}\n\n/**\n * Generates a zustand store for a single module\n */\nfunction generateStoreForModule(module: ModuleMetadata): GeneratedStore {\n const storeName = toPascalCase(module.name);\n const hookName = `use${storeName}Store`;\n\n const queriesSection = generateQueriesSection(module.queries);\n const mutationsSection = generateMutationsSection(module.mutations);\n\n const content = `// Generated by Modelence - DO NOT EDIT MANUALLY\nimport { create } from 'zustand';\nimport { callMethod } from 'modelence/client';\n\n/**\n * Zustand store for ${module.name} module\n * Auto-generated from module queries and mutations\n */\n\n// Query methods\n${queriesSection.methods}\n\n// Mutation methods\n${mutationsSection.methods}\n\n// Store interface\ninterface ${storeName}Store {\n // Queries\n${queriesSection.interface}\n\n // Mutations\n${mutationsSection.interface}\n}\n\n// Create the store\nexport const ${hookName} = create<${storeName}Store>((set, get) => ({\n // Query implementations\n${queriesSection.implementations}\n\n // Mutation implementations\n${mutationsSection.implementations}\n}));\n`;\n\n const typesContent = `// Generated by Modelence - DO NOT EDIT MANUALLY\n\n/**\n * Type definitions for ${module.name} module store\n */\n\n// Query argument types\n${queriesSection.types}\n\n// Mutation argument types\n${mutationsSection.types}\n\n// Query return types - these should be manually typed or inferred from the server\n${queriesSection.returnTypes}\n\n// Mutation return types - these should be manually typed or inferred from the server\n${mutationsSection.returnTypes}\n`;\n\n return {\n fileName: `${module.name}.ts`,\n content,\n typesContent,\n };\n}\n\ninterface SectionContent {\n methods: string;\n interface: string;\n implementations: string;\n types: string;\n returnTypes: string;\n}\n\nfunction generateQueriesSection(queries: QueryMetadata[]): SectionContent {\n if (queries.length === 0) {\n return {\n methods: '// No queries defined',\n interface: ' // No queries',\n implementations: ' // No queries',\n types: '// No queries',\n returnTypes: '// No queries',\n };\n }\n\n const methods = queries\n .map((q) => {\n const argsType = q.argsType || 'Record<string, unknown>';\n return `/**\n * Query: ${q.name}\n * Call the ${q.fullName} method on the server\n */\nasync function ${q.name}(args: ${argsType} = {} as ${argsType}) {\n return callMethod('${q.fullName}', args);\n}`;\n })\n .join('\\n\\n');\n\n const interfaceDef = queries\n .map((q) => {\n const argsType = q.argsType || 'Record<string, unknown>';\n const returnType = q.returnType || 'unknown';\n return ` ${q.name}: (args?: ${argsType}) => Promise<${returnType}>;`;\n })\n .join('\\n');\n\n const implementations = queries\n .map((q) => {\n const argsType = q.argsType || 'Record<string, unknown>';\n return ` ${q.name}: async (args = {} as ${argsType}) => callMethod('${q.fullName}', args),`;\n })\n .join('\\n');\n\n const types = queries\n .map((q) => {\n const argsType = q.argsType || 'Record<string, unknown>';\n return `export type ${toPascalCase(q.name)}Args = ${argsType};`;\n })\n .join('\\n');\n\n const returnTypes = queries\n .map((q) => {\n const returnType = q.returnType || 'unknown';\n return `export type ${toPascalCase(q.name)}Result = ${returnType};`;\n })\n .join('\\n');\n\n return {\n methods,\n interface: interfaceDef,\n implementations,\n types,\n returnTypes,\n };\n}\n\nfunction generateMutationsSection(mutations: MutationMetadata[]): SectionContent {\n if (mutations.length === 0) {\n return {\n methods: '// No mutations defined',\n interface: ' // No mutations',\n implementations: ' // No mutations',\n types: '// No mutations',\n returnTypes: '// No mutations',\n };\n }\n\n const methods = mutations\n .map((m) => {\n const argsType = m.argsType || 'Record<string, unknown>';\n return `/**\n * Mutation: ${m.name}\n * Call the ${m.fullName} method on the server\n */\nasync function ${m.name}(args: ${argsType} = {} as ${argsType}) {\n return callMethod('${m.fullName}', args);\n}`;\n })\n .join('\\n\\n');\n\n const interfaceDef = mutations\n .map((m) => {\n const argsType = m.argsType || 'Record<string, unknown>';\n const returnType = m.returnType || 'unknown';\n return ` ${m.name}: (args?: ${argsType}) => Promise<${returnType}>;`;\n })\n .join('\\n');\n\n const implementations = mutations\n .map((m) => {\n const argsType = m.argsType || 'Record<string, unknown>';\n return ` ${m.name}: async (args = {} as ${argsType}) => callMethod('${m.fullName}', args),`;\n })\n .join('\\n');\n\n const types = mutations\n .map((m) => {\n const argsType = m.argsType || 'Record<string, unknown>';\n return `export type ${toPascalCase(m.name)}Args = ${argsType};`;\n })\n .join('\\n');\n\n const returnTypes = mutations\n .map((m) => {\n const returnType = m.returnType || 'unknown';\n return `export type ${toPascalCase(m.name)}Result = ${returnType};`;\n })\n .join('\\n');\n\n return {\n methods,\n interface: interfaceDef,\n implementations,\n types,\n returnTypes,\n };\n}\n\n/**\n * Convert a string to PascalCase\n */\nfunction toPascalCase(str: string): string {\n return str\n .split(/[-_\\s]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n}\n\n/**\n * Generate an index file that exports all stores\n */\nexport function generateIndexFile(modules: ModuleMetadata[]): string {\n const exports = modules\n .map((module) => {\n const storeName = toPascalCase(module.name);\n const hookName = `use${storeName}Store`;\n return `export { ${hookName} } from './${module.name}';`;\n })\n .join('\\n');\n\n return `// Generated by Modelence - DO NOT EDIT MANUALLY\n/**\n * Auto-generated zustand stores for all modules\n * Import these stores in your client-side code to interact with the server\n */\n\n${exports}\n`;\n}\n","import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { analyzeModulesFromServerFile } from './astAnalyzer';\nimport { generateZustandStores, generateIndexFile } from './zustandGenerator';\n\nexport interface CodegenOptions {\n /**\n * Path to the server entry file\n * By default, uses the serverPath from modelence.config.ts\n */\n serverPath?: string;\n\n /**\n * Output directory for generated stores\n * Default: .modelence/stores\n */\n outputDir?: string;\n\n /**\n * Whether to generate TypeScript definition files\n * Default: true\n */\n generateTypes?: boolean;\n}\n\n/**\n * Main code generation function\n * This is called during `modelence dev` and `modelence build`\n */\nexport async function generateStores(options: CodegenOptions = {}) {\n const {\n serverPath = await findServerPath(),\n outputDir = path.join(process.cwd(), '.modelence/stores'),\n generateTypes = true,\n } = options;\n\n console.log('🔄 Generating zustand stores from modules...');\n\n try {\n // Ensure output directory exists\n await fs.mkdir(outputDir, { recursive: true });\n\n // Analyze modules using AST parsing (no code execution)\n console.log(` Analyzing modules from: ${serverPath}`);\n const modules = await analyzeModulesFromServerFile(serverPath);\n\n if (modules.length === 0) {\n console.log(' ⚠️ No modules found. Skipping store generation.');\n return;\n }\n\n console.log(` Found ${modules.length} module(s): ${modules.map((m) => m.name).join(', ')}`);\n\n // Generate stores\n const stores = generateZustandStores(modules);\n\n // Write store files\n for (const store of stores) {\n const storePath = path.join(outputDir, store.fileName);\n await fs.writeFile(storePath, store.content, 'utf-8');\n console.log(` ✓ Generated: ${store.fileName}`);\n\n if (generateTypes) {\n const typesPath = path.join(outputDir, store.fileName.replace('.ts', '.types.ts'));\n await fs.writeFile(typesPath, store.typesContent, 'utf-8');\n console.log(` ✓ Generated: ${store.fileName.replace('.ts', '.types.ts')}`);\n }\n }\n\n // Generate index file\n const indexContent = generateIndexFile(modules);\n const indexPath = path.join(outputDir, 'index.ts');\n await fs.writeFile(indexPath, indexContent, 'utf-8');\n console.log(` ✓ Generated: index.ts`);\n\n console.log('✅ Zustand stores generated successfully!\\n');\n console.log(` Import them in your client code:`);\n console.log(\n ` import { use${toPascalCase(modules[0].name)}Store } from '.modelence/stores';\\n`\n );\n } catch (error) {\n console.error('❌ Failed to generate zustand stores:', error);\n throw error;\n }\n}\n\n/**\n * Find the server entry file in the user's project\n * This should be the file that calls startApp()\n */\nasync function findServerPath(): Promise<string> {\n // Try to read from modelence.config.ts\n try {\n const configPath = path.join(process.cwd(), 'modelence.config.ts');\n const configContent = await fs.readFile(configPath, 'utf-8');\n\n // Simple regex to extract serverDir and serverEntry\n const serverDirMatch = configContent.match(/serverDir:\\s*['\"](.+?)['\"]/);\n const serverEntryMatch = configContent.match(/serverEntry:\\s*['\"](.+?)['\"]/);\n\n if (serverDirMatch && serverEntryMatch) {\n const serverPath = path.join(process.cwd(), serverDirMatch[1], serverEntryMatch[1]);\n await fs.access(serverPath);\n return serverPath;\n }\n } catch {\n // Config not found or parse failed, try defaults\n }\n\n // Fallback to common paths\n const possiblePaths = [\n path.join(process.cwd(), 'src/server/app.ts'),\n path.join(process.cwd(), 'src/server/index.ts'),\n path.join(process.cwd(), 'server/app.ts'),\n path.join(process.cwd(), 'server/index.ts'),\n ];\n\n for (const p of possiblePaths) {\n try {\n await fs.access(p);\n return p;\n } catch {\n // File doesn't exist, continue\n }\n }\n\n throw new Error(\n 'Could not find server entry file. Make sure your modelence.config.ts is configured correctly.'\n );\n}\n\nfunction toPascalCase(str: string): string {\n return str\n .split(/[-_\\s]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n}\n\nexport * from './astAnalyzer';\nexport * from './zustandGenerator';\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\nimport pkg from '../../package.json';\nimport { generateStores } from '../codegen';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n // Generate zustand stores before building\n console.log('\\n🔧 Generating zustand stores...');\n try {\n await generateStores();\n } catch (error) {\n console.warn('\\n⚠️ Store generation failed, continuing anyway...');\n console.warn(error);\n }\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\nimport { generateStores } from '../codegen';\n\nexport async function dev() {\n console.log('Starting Modelence dev server...');\n\n // Generate zustand stores before starting dev server\n try {\n await generateStores();\n } catch (error) {\n console.warn('⚠️ Store generation failed, continuing anyway...');\n console.warn(error);\n }\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n await dev();\n });\n\nprogram.parse(process.argv);\n"]}
1
+ {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/codegen/astAnalyzer.ts","../../src/codegen/zustandGenerator.ts","../../src/codegen/index.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","analyzeModulesFromServerFile","serverPath","k","serverCode","sourceFile","moduleImports","foundModules","visitNode","node","importPath","element","configArg","modulesProperty","prop","moduleName","analyzedModules","moduleInfo","analyzed","analyzeModuleFile","args","queriesProperty","queryName","typeInfo","extractMethodTypes","moduleCode","queries","mutationsProperty","mutationName","mutations","fullPath","resolveModulePath","sourceCode","argsType","returnType","functionBody","initializer","start","end","methodSource","zodMatch","schemaContent","convertZodSchemaToTypeScript","schemaStr","fields","fieldPattern","match","fieldName","zodType","modifiers","tsType","fieldDef","resolved","extensions","ext","candidate","generateZustandStores","modules","module","generateStoreForModule","hookName","toPascalCase","queriesSection","generateQueriesSection","mutationsSection","generateMutationsSection","content","dataFields","q","implementations","m","str","word","generateIndexFile","generateStores","findServerPath","outputDir","stores","store","storePath","indexContent","indexPath","configContent","serverDirMatch","serverEntryMatch","possiblePaths","p","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","package_default","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","tsxPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";glBAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,EAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,EAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,MAClB,CAEA,eAAeE,EAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,CAAA,CAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CACD,CAAA,SAAA,EAAYP,CAAkB,CAAA,oDAAA,CAAA,CAC7BU,CAAAA,EAAW,CACVH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,CAAAA,CAAO,aAAY,GAAM,GAAG,EACtC,CACF,EACF,CAAC,CACH,CAEA,SAASC,EAAAA,CAAeC,CAAAA,CAAgC,CAEtD,OAAO,MAAA,CAAOA,CAA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,MAAMpJ,CAAAA,EAAQ,CACd,MAAM4I,CAAAA,GACR,CAAC,CAAA,CAEHQ,CAAAA,CAAQ,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import * as ts from 'typescript';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\n\nexport interface ModuleMetadata {\n name: string;\n queries: QueryMetadata[];\n mutations: MutationMetadata[];\n filePath: string;\n}\n\nexport interface QueryMetadata {\n name: string;\n fullName: string;\n argsType?: string; // TypeScript type string for arguments\n returnType?: string; // TypeScript type string for return value\n}\n\nexport interface MutationMetadata {\n name: string;\n fullName: string;\n argsType?: string;\n returnType?: string;\n}\n\n/**\n * Analyzes the server entry file using AST parsing to extract module metadata\n * This approach doesn't require running the code, making it safe for build-time\n */\nexport async function analyzeModulesFromServerFile(serverPath: string): Promise<ModuleMetadata[]> {\n const serverDir = path.dirname(serverPath);\n\n // Read the server file\n const serverCode = await fs.readFile(serverPath, 'utf-8');\n\n // Parse the file into an AST using TypeScript compiler\n const sourceFile = ts.createSourceFile(\n serverPath,\n serverCode,\n ts.ScriptTarget.Latest,\n true\n );\n\n // Find all module imports and their sources\n const moduleImports = new Map<string, string>(); // localName -> importPath\n const foundModules: ModuleInfo[] = [];\n\n // Visit all nodes to find imports\n function visitNode(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const importPath = (node.moduleSpecifier as ts.StringLiteral).text;\n\n if (node.importClause) {\n // Handle default import: import Foo from './foo'\n if (node.importClause.name) {\n moduleImports.set(node.importClause.name.text, importPath);\n }\n\n // Handle named imports: import { Foo } from './foo'\n if (node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) {\n for (const element of node.importClause.namedBindings.elements) {\n moduleImports.set(element.name.text, importPath);\n }\n }\n }\n }\n\n // Find the startApp call\n if (ts.isCallExpression(node)) {\n if (ts.isIdentifier(node.expression) && node.expression.text === 'startApp') {\n // Get the first argument (config object)\n const configArg = node.arguments[0];\n if (configArg && ts.isObjectLiteralExpression(configArg)) {\n // Find the modules property\n const modulesProperty = configArg.properties.find(\n (prop): prop is ts.PropertyAssignment =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === 'modules'\n );\n\n if (modulesProperty && ts.isArrayLiteralExpression(modulesProperty.initializer)) {\n // Extract module identifiers from the array\n for (const element of modulesProperty.initializer.elements) {\n if (ts.isIdentifier(element)) {\n const moduleName = element.text;\n const importPath = moduleImports.get(moduleName);\n if (importPath) {\n foundModules.push({\n name: moduleName,\n importPath,\n serverDir,\n });\n }\n }\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visitNode);\n }\n\n visitNode(sourceFile);\n\n // Analyze each module file to extract queries and mutations\n const analyzedModules: ModuleMetadata[] = [];\n for (const moduleInfo of foundModules) {\n const analyzed = await analyzeModuleFile(moduleInfo.importPath, moduleInfo.serverDir);\n if (analyzed) {\n analyzedModules.push(analyzed);\n }\n }\n\n return analyzedModules;\n}\n\ninterface ModuleInfo {\n name: string;\n importPath: string;\n serverDir: string;\n}\n\n/**\n * Analyzes a module file to extract its name, queries, and mutations\n */\nasync function analyzeModuleFile(\n importPath: string,\n serverDir: string\n): Promise<ModuleMetadata | null> {\n try {\n // Resolve the full path\n const fullPath = await resolveModulePath(importPath, serverDir);\n const moduleCode = await fs.readFile(fullPath, 'utf-8');\n\n // Parse the module file\n const sourceFile = ts.createSourceFile(\n fullPath,\n moduleCode,\n ts.ScriptTarget.Latest,\n true\n );\n\n let moduleName = '';\n const queries: QueryMetadata[] = [];\n const mutations: MutationMetadata[] = [];\n\n // Find the Module constructor call\n function visitNode(node: ts.Node) {\n if (ts.isNewExpression(node)) {\n if (ts.isIdentifier(node.expression) && node.expression.text === 'Module') {\n const args = node.arguments;\n\n // First argument is the module name\n if (args && args.length > 0 && ts.isStringLiteral(args[0])) {\n moduleName = args[0].text;\n }\n\n // Second argument is the config object\n if (args && args.length > 1 && ts.isObjectLiteralExpression(args[1])) {\n const config = args[1];\n\n // Find queries property\n const queriesProperty = config.properties.find(\n (prop): prop is ts.PropertyAssignment =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === 'queries'\n );\n\n if (queriesProperty && ts.isObjectLiteralExpression(queriesProperty.initializer)) {\n for (const prop of queriesProperty.initializer.properties) {\n if (ts.isPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) {\n const queryName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : '';\n\n if (queryName) {\n // Extract type information\n const typeInfo = extractMethodTypes(prop, moduleCode, sourceFile);\n\n queries.push({\n name: queryName,\n fullName: `${moduleName}.${queryName}`,\n argsType: typeInfo.argsType,\n returnType: typeInfo.returnType,\n });\n }\n }\n }\n }\n\n // Find mutations property\n const mutationsProperty = config.properties.find(\n (prop): prop is ts.PropertyAssignment =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === 'mutations'\n );\n\n if (mutationsProperty && ts.isObjectLiteralExpression(mutationsProperty.initializer)) {\n for (const prop of mutationsProperty.initializer.properties) {\n if (ts.isPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) {\n const mutationName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : '';\n\n if (mutationName) {\n // Extract type information\n const typeInfo = extractMethodTypes(prop, moduleCode, sourceFile);\n\n mutations.push({\n name: mutationName,\n fullName: `${moduleName}.${mutationName}`,\n argsType: typeInfo.argsType,\n returnType: typeInfo.returnType,\n });\n }\n }\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visitNode);\n }\n\n visitNode(sourceFile);\n\n if (moduleName) {\n return {\n name: moduleName,\n queries,\n mutations,\n filePath: fullPath,\n };\n }\n\n return null;\n } catch (error) {\n console.error(`Failed to analyze module file ${importPath}:`, error);\n return null;\n }\n}\n\n/**\n * Extracts type information from a method (PropertyAssignment or MethodDeclaration)\n * Analyzes Zod schemas and return statements to infer types\n */\nfunction extractMethodTypes(\n prop: ts.PropertyAssignment | ts.MethodDeclaration,\n sourceCode: string,\n sourceFile: ts.SourceFile\n): { argsType?: string; returnType?: string } {\n let argsType: string | undefined;\n let returnType: string | undefined;\n\n // Get the function body\n let functionBody: ts.Node | undefined;\n\n if (ts.isMethodDeclaration(prop) && prop.body) {\n functionBody = prop.body;\n } else if (ts.isPropertyAssignment(prop)) {\n const initializer = prop.initializer;\n if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) {\n functionBody = initializer.body;\n }\n }\n\n if (!functionBody) {\n return { argsType, returnType };\n }\n\n // Extract the source code for this method\n const start = functionBody.getStart(sourceFile);\n const end = functionBody.getEnd();\n const methodSource = sourceCode.substring(start, end);\n\n // Look for Zod schema parsing patterns\n // Pattern: z.object({ field: z.string(), ... }).parse(args)\n const zodObjectPattern =\n /z\\.object\\(\\s*\\{([^}]+)\\}\\s*\\)\\.parse\\(|\\.object\\(\\s*\\{([^}]+)\\}\\s*\\)\\.parse\\(/g;\n const zodMatch = zodObjectPattern.exec(methodSource);\n\n if (zodMatch) {\n const schemaContent = zodMatch[1] || zodMatch[2];\n argsType = convertZodSchemaToTypeScript(schemaContent);\n }\n\n // Look for explicit return statements to infer return type\n // This is basic - in reality, we'd need full type inference\n if (methodSource.includes('return {')) {\n returnType = 'Record<string, unknown>'; // Generic object type\n } else if (methodSource.includes('return [')) {\n returnType = 'unknown[]'; // Array type\n }\n\n return { argsType, returnType };\n}\n\n/**\n * Converts a Zod schema string to TypeScript type\n * This is a simplified version - handles common cases\n */\nfunction convertZodSchemaToTypeScript(schemaStr: string): string {\n const fields: string[] = [];\n\n // Parse field definitions like: fieldName: z.string().min(1)\n const fieldPattern = /(\\w+):\\s*z\\.(\\w+)\\([^)]*\\)([^,}\\n]*)/g;\n let match;\n\n while ((match = fieldPattern.exec(schemaStr)) !== null) {\n const fieldName = match[1];\n const zodType = match[2];\n const modifiers = match[3] || '';\n\n // Map Zod types to TypeScript types\n let tsType = 'unknown';\n switch (zodType) {\n case 'string':\n tsType = 'string';\n break;\n case 'number':\n tsType = 'number';\n break;\n case 'boolean':\n tsType = 'boolean';\n break;\n case 'date':\n tsType = 'Date';\n break;\n case 'array':\n tsType = 'unknown[]';\n break;\n case 'object':\n tsType = 'Record<string, unknown>';\n break;\n }\n\n // Check if optional\n const isOptional = modifiers.includes('.optional()');\n const fieldDef = isOptional ? `${fieldName}?: ${tsType}` : `${fieldName}: ${tsType}`;\n fields.push(fieldDef);\n }\n\n if (fields.length > 0) {\n return `{ ${fields.join('; ')} }`;\n }\n\n return 'Record<string, unknown>';\n}\n\n/**\n * Resolves a module import path to an absolute file path\n */\nasync function resolveModulePath(importPath: string, serverDir: string): Promise<string> {\n // Handle relative imports\n if (importPath.startsWith('./') || importPath.startsWith('../')) {\n const resolved = path.resolve(serverDir, importPath);\n\n // Try common extensions and index files\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.js'];\n for (const ext of extensions) {\n const candidate = resolved + ext;\n try {\n const stats = await fs.stat(candidate);\n if (stats.isFile()) {\n return candidate;\n }\n } catch {\n continue;\n }\n }\n\n throw new Error(`Could not resolve module path: ${importPath} (tried ${resolved})`);\n }\n\n // Handle package imports (node_modules)\n // For now, we'll skip these as modules should be local\n throw new Error(`Cannot resolve package import: ${importPath}`);\n}\n","import { ModuleMetadata, QueryMetadata, MutationMetadata } from './astAnalyzer';\n\nexport interface GeneratedStore {\n fileName: string;\n content: string;\n}\n\n/**\n * Generates zustand stores for all modules\n */\nexport function generateZustandStores(modules: ModuleMetadata[]): GeneratedStore[] {\n return modules.map((module) => generateStoreForModule(module));\n}\n\n/**\n * Generates a zustand store for a single module\n */\nfunction generateStoreForModule(module: ModuleMetadata): GeneratedStore {\n const storeName = toPascalCase(module.name);\n const hookName = `use${storeName}Store`;\n\n const queriesSection = generateQueriesSection(module.queries);\n const mutationsSection = generateMutationsSection(module.mutations);\n\n const content = `// Generated by Modelence - DO NOT EDIT MANUALLY\nimport { create } from 'zustand';\nimport { callMethod } from 'modelence/client';\n\nexport const ${hookName} = create((set, get) => ({\n${queriesSection.dataFields}\n${mutationsSection.dataFields}\n\n${queriesSection.implementations}\n${mutationsSection.implementations}\n}));\n`;\n\n return {\n fileName: `${module.name}.ts`,\n content,\n };\n}\n\ninterface SectionContent {\n dataFields: string;\n implementations: string;\n}\n\nfunction generateQueriesSection(queries: QueryMetadata[]): SectionContent {\n if (queries.length === 0) {\n return {\n dataFields: '',\n implementations: '',\n };\n }\n\n const dataFields = queries\n .map((q) => {\n const returnType = q.returnType || 'unknown';\n return ` ${q.name}Data: null as ${returnType} | null,`;\n })\n .join('\\n');\n\n const implementations = queries\n .map((q) => {\n const argsType = q.argsType || 'Record<string, unknown>';\n return ` ${q.name}: async (args = {} as ${argsType}) => {\n const result = await callMethod('${q.fullName}', args);\n set({ ${q.name}Data: result });\n return result;\n },`;\n })\n .join('\\n');\n\n return {\n dataFields,\n implementations,\n };\n}\n\nfunction generateMutationsSection(mutations: MutationMetadata[]): SectionContent {\n if (mutations.length === 0) {\n return {\n dataFields: '',\n implementations: '',\n };\n }\n\n const dataFields = mutations\n .map((m) => {\n const returnType = m.returnType || 'unknown';\n return ` ${m.name}Data: null as ${returnType} | null,`;\n })\n .join('\\n');\n\n const implementations = mutations\n .map((m) => {\n const argsType = m.argsType || 'Record<string, unknown>';\n return ` ${m.name}: async (args = {} as ${argsType}) => {\n const result = await callMethod('${m.fullName}', args);\n set({ ${m.name}Data: result });\n return result;\n },`;\n })\n .join('\\n');\n\n return {\n dataFields,\n implementations,\n };\n}\n\n/**\n * Convert a string to PascalCase\n */\nfunction toPascalCase(str: string): string {\n return str\n .split(/[-_\\s]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n}\n\n/**\n * Generate an index file that exports all stores\n */\nexport function generateIndexFile(modules: ModuleMetadata[]): string {\n const exports = modules\n .map((module) => {\n const storeName = toPascalCase(module.name);\n const hookName = `use${storeName}Store`;\n return `export { ${hookName} } from './${module.name}';`;\n })\n .join('\\n');\n\n return `// Generated by Modelence - DO NOT EDIT MANUALLY\n/**\n * Auto-generated zustand stores for all modules\n * Import these stores in your client-side code to interact with the server\n */\n\n${exports}\n`;\n}\n","import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { analyzeModulesFromServerFile } from './astAnalyzer';\nimport { generateZustandStores, generateIndexFile } from './zustandGenerator';\n\nexport interface CodegenOptions {\n /**\n * Path to the server entry file\n * By default, uses the serverPath from modelence.config.ts\n */\n serverPath?: string;\n\n /**\n * Output directory for generated stores\n * Default: .modelence/stores\n */\n outputDir?: string;\n}\n\n/**\n * Main code generation function\n * This is called during `modelence dev` and `modelence build`\n */\nexport async function generateStores(options: CodegenOptions = {}) {\n const {\n serverPath = await findServerPath(),\n outputDir = path.join(process.cwd(), '.modelence/stores'),\n } = options;\n\n console.log('🔄 Generating zustand stores from modules...');\n\n try {\n // Ensure output directory exists\n await fs.mkdir(outputDir, { recursive: true });\n\n // Analyze modules using AST parsing (no code execution)\n console.log(` Analyzing modules from: ${serverPath}`);\n const modules = await analyzeModulesFromServerFile(serverPath);\n\n if (modules.length === 0) {\n console.log(' ⚠️ No modules found. Skipping store generation.');\n return;\n }\n\n console.log(` Found ${modules.length} module(s): ${modules.map((m) => m.name).join(', ')}`);\n\n // Generate stores\n const stores = generateZustandStores(modules);\n\n // Write store files\n for (const store of stores) {\n const storePath = path.join(outputDir, store.fileName);\n await fs.writeFile(storePath, store.content, 'utf-8');\n console.log(` ✓ Generated: ${store.fileName}`);\n }\n\n // Generate index file\n const indexContent = generateIndexFile(modules);\n const indexPath = path.join(outputDir, 'index.ts');\n await fs.writeFile(indexPath, indexContent, 'utf-8');\n console.log(` ✓ Generated: index.ts`);\n\n console.log('✅ Zustand stores generated successfully!\\n');\n console.log(` Import them in your client code:`);\n console.log(\n ` import { use${toPascalCase(modules[0].name)}Store } from '.modelence/stores';\\n`\n );\n } catch (error) {\n console.error('❌ Failed to generate zustand stores:', error);\n throw error;\n }\n}\n\n/**\n * Find the server entry file in the user's project\n * This should be the file that calls startApp()\n */\nasync function findServerPath(): Promise<string> {\n // Try to read from modelence.config.ts\n try {\n const configPath = path.join(process.cwd(), 'modelence.config.ts');\n const configContent = await fs.readFile(configPath, 'utf-8');\n\n // Simple regex to extract serverDir and serverEntry\n const serverDirMatch = configContent.match(/serverDir:\\s*['\"](.+?)['\"]/);\n const serverEntryMatch = configContent.match(/serverEntry:\\s*['\"](.+?)['\"]/);\n\n if (serverDirMatch && serverEntryMatch) {\n const serverPath = path.join(process.cwd(), serverDirMatch[1], serverEntryMatch[1]);\n await fs.access(serverPath);\n return serverPath;\n }\n } catch {\n // Config not found or parse failed, try defaults\n }\n\n // Fallback to common paths\n const possiblePaths = [\n path.join(process.cwd(), 'src/server/app.ts'),\n path.join(process.cwd(), 'src/server/index.ts'),\n path.join(process.cwd(), 'server/app.ts'),\n path.join(process.cwd(), 'server/index.ts'),\n ];\n\n for (const p of possiblePaths) {\n try {\n await fs.access(p);\n return p;\n } catch {\n // File doesn't exist, continue\n }\n }\n\n throw new Error(\n 'Could not find server entry file. Make sure your modelence.config.ts is configured correctly.'\n );\n}\n\nfunction toPascalCase(str: string): string {\n return str\n .split(/[-_\\s]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join('');\n}\n\nexport * from './astAnalyzer';\nexport * from './zustandGenerator';\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\nimport pkg from '../../package.json';\nimport { generateStores } from '../codegen';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n // Generate zustand stores before building\n console.log('\\n🔧 Generating zustand stores...');\n try {\n await generateStores();\n } catch (error) {\n console.warn('\\n⚠️ Store generation failed, continuing anyway...');\n console.warn(error);\n }\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\nimport { generateStores } from '../codegen';\n\nexport async function dev() {\n console.log('Starting Modelence dev server...');\n\n // Generate zustand stores before starting dev server\n try {\n await generateStores();\n } catch (error) {\n console.warn('⚠️ Store generation failed, continuing anyway...');\n console.warn(error);\n }\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n await dev();\n });\n\nprogram.parse(process.argv);\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",o="0.7.0-dev.2",r="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="https://modelence.com",h={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",jest:"^30.2.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",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","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",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"},v={react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:o,description:r,main:n,types:p,exports:c,files:d,bin:l,scripts:m,repository:a,author:y,license:u,bugs:j,homepage:g,devDependencies:h,dependencies:x,peerDependencies:v};
2
+ export{s as a,i as b,o as c,r as d,n as e,p as f,c as g,d as h,l as i,m as j,a as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-TKYF2MS5.js.map
3
+ //# sourceMappingURL=chunk-TKYF2MS5.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,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,cACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,eACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,eAAA,CAClB,IAAA,CAAQ,6CAAA,CACR,YAAA,CAAc,sDACd,eAAA,CAAiB,wDAAA,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OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,CAAA,CAlGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,EACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAaA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-TKYF2MS5.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.7.0-dev.2\",\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 \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\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 \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\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/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"jest\": \"^30.2.0\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\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 \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\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"]}
@@ -1,2 +1,2 @@
1
- export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-VQSLCX5F.js';//# sourceMappingURL=package-DVI2JFS6.js.map
2
- //# sourceMappingURL=package-DVI2JFS6.js.map
1
+ export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-TKYF2MS5.js';//# sourceMappingURL=package-Y6FUSHZG.js.map
2
+ //# sourceMappingURL=package-Y6FUSHZG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-DVI2JFS6.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-Y6FUSHZG.js"}
package/dist/server.js CHANGED
@@ -14,6 +14,6 @@ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UES
14
14
  `}var ge={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function lt(t,{connectionInfo:e}){let o=L(t.email),n=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ge;let r=b().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await S.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,d=`${So(a$1,b().passwordReset?.redirectUrl)}?token=${i}`,u=(b()?.passwordReset?.template||xo)({email:o,resetUrl:d,name:""}),C=X(u);return await r.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:C,html:u}),ge}async function dt(t,{}){let e=z.string().parse(t.token),o=te(t.password),n=await S.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await S.deleteOne({token:e}),new Error("Reset token has expired");let r=await p.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await fo.hash(o,10);return await p.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await S.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var ut=new E("_system.user",{stores:[p,W,D,S],queries:{getOwnProfile:st},mutations:{signupWithPassword:ct,loginWithPassword:rt,logout:it,sendResetPasswordToken:lt,resetPassword:dt},cronJobs:{updateDisposableEmailList:Qe},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:et}}]});async function mt({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await ye("/api/connect","POST",{hostname:To.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function pt(){return await ye("/api/configs","GET")}async function ft(){return await ye("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ye(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var we=false,Do=a.seconds(10);function ht(){setInterval(async()=>{if(!we){we=true;try{await ft();}catch(t){console.error("Error syncing status",t);}try{await vo();}catch(t){console.error("Error syncing config",t);}we=false;}},Do);}async function vo(){let{configs:t}=await pt();c$1(t);}var J=new w("_modelenceLocks",{schema:{resource:c.string(),instanceId:c.string(),acquiredAt:c.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var N={},gt=a.seconds(10),yt=randomBytes(32).toString("base64url"),ko=a.seconds(30);async function oe(t,{lockDuration:e=ko,successfulLockCacheDuration:o=gt,failedLockCacheDuration:n=gt,instanceId:r=yt}={}){let i=Date.now();if(N[t]&&i<N[t].expiresAt)return N[t].value;let s=new Date(i-e);h(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:r});try{let a=await J.upsertOne({$or:[{resource:t,instanceId:r},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:r,acquiredAt:new Date}}),l=a.upsertedCount>0||a.modifiedCount>0;return N[t]={value:l,expiresAt:i+(l?o:n)},l?h(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:r}):h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),l}catch{return N[t]={value:false,expiresAt:i+n},h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),false}}async function wt(t,{instanceId:e=yt}={}){let o=await J.deleteOne({resource:t,instanceId:e});return delete N[t],o.deletedCount>0}var Ro=a.minutes(1),A={},be=null,Ee=new w("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Et(t,{description:e="",interval:o,timeout:n=Ro,handler:r}){if(A[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(be)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);A[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Ct(){if(be)throw new Error("Cron jobs already started");let t=Object.keys(A);if(t.length>0){let e={alias:{$in:t}},o=await Ee.fetch(e),n=Date.now();o.forEach(r=>{let i=A[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:n);}),Object.values(A).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=n);}),be=setInterval(Oo,a.seconds(1));}}async function Oo(){let t=Date.now();await oe("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(A).forEach(async o=>{let{params:n,state:r}=o;if(r.isRunning){r.startTs&&r.startTs+n.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await Mo(o);});}async function Mo(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now(),await Ee.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});let i=k$1("cron",`cron:${e}`);try{await n(),bt(r,o),i.end("success");}catch(s){bt(r,o);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function bt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function St(){return Object.values(A).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var xt=new E("_system.cron",{stores:[Ee]});var Ce={};function Se(t,e){return O(),_t(t),ne("query",t,e)}function Tt(t,e){return O(),_t(t),ne("mutation",t,e)}function Dt(t,e){return O(),kt(t),ne("query",t,e)}function vt(t,e){return O(),kt(t),ne("mutation",t,e)}function _t(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function kt(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(O(),Ce[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];Ce[e]={type:t,name:e,handler:n,permissions:r};}async function Rt(t,e,o){O();let n=Ce[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=k$1("method",`method:${t}`,{type:r,args:e}),a;try{He(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var xe=new E("_system.lock",{stores:[J]});var H=new w("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function Ao(t){if(t.length===0)return;if(!await oe("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),n=await H.fetch({version:{$in:o}}),r=new Set(n.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!r.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:l}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let y=(await l()||"").toString().trim(),u=15*1024*1024,C=y.length>u?y.slice(0,u)+`
15
15
  [Output truncated - exceeded size limit]`:y;await H.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:C,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(d){d instanceof Error&&(await H.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:d.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${d.message}`,{source:"migrations"}));}}await wt("migrations");}}function Ot(t){setTimeout(()=>{Ao(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Mt=new E("_system.migration",{stores:[H]});var At=new E("_system.rateLimit",{stores:[B]});var It=new E("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var De=class{async init(){this.config=await qo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ke.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ke.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function $o(){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 zo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function qo(){let t=process.cwd(),e=await $o(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>No.existsSync(Te.join(t,i))),n=[Lo(),Zo()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Te.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Te.resolve(t,"src").replace(/\\/g,"/")}}});return zo(r,e)}function Zo(){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 Ut=new De;async function jt(t,e){let{authToken:o}=await me(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function $(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function re(t,e,o){let n=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await ve(t);try{if(n){await jt(e,n._id),g().onAfterLogin?.({user:n,session:r,connectionInfo:i}),g().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(g().login?.onError?.(s),g().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await 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 jt(e,a.insertedId);let l=await p.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(g().onAfterSignup?.({user:l,session:r,connectionInfo:i}),g().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(g().onSignupError?.({error:s,session:r,connectionInfo:i}),g().signup?.onError?.(s)),s}}function ie(t){return !t||typeof t!="string"?null:t}async function Fo(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Bo(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 Jo(t,e){let o=ie(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=$("google");try{let s=await Fo(o,n,r,i),a=await Bo(s.access_token),l={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await re(t,e,l);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function Ho(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=$("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,Jo),t}var Lt=Ho;async function Go(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Ko(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 Qo(t,e){let o=ie(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=$("github");try{let s=await Go(o,n,r,i),a=await Ko(s.access_token),l=a.email||"";if(!l){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let d={id:String(a.id),email:l,emailVerified:!0,providerName:"github"};await re(t,e,d);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function Yo(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=$("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(d=>d.trim()).join(" "):"user:email",l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",r),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a),n.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,Qo),t}var Nt=Yo;function $t(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&R())try{let{session:d,user:y}=await k(s);a={session:d,user:y};}catch{}let l=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let d=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,req:n,res:r,next:i},a);l.end(),d&&(r.status(d.status||200),d.redirect&&r.redirect(d.redirect),d.headers&&Object.entries(d.headers).forEach(([y,u])=>{r.setHeader(y,u);}),r.send(d.data));}catch(d){l.end("error"),d instanceof a$3?r.status(d.status).send(d.message):(console.error(`Error in route handler: ${n.path}`),console.error(d),r.status(500).send(String(d)));}}}var _e=Object.freeze({});function zt(t){_e=Object.freeze(Object.assign({},_e,t));}function se(){return _e}function tn(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,$t(s,r,a));});}}async function qt(t,{combinedModules:e,channels:o}){let n=ke();n.use(ke.json({limit:"16mb"})),n.use(ke.urlencoded({extended:true,limit:"16mb"})),n.use(Xo()),n.use(Lt()),n.use(Nt()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:d}=a.params,y=await ve(a);try{let u=await Rt(d,a.body.args,y);l.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${d}:`,u),u instanceof a$3)l.status(u.status).send(u.message);else if(u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let I=u.flatten(),ae=Object.entries(I.fieldErrors).map(([z,le])=>`${z}: ${(le??[]).join(", ")}`).join("; "),ce=I.formErrors.join("; "),V=[ae,ce].filter(Boolean).join("; ");l.status(400).send(V);}else l.status(500).send(u instanceof Error?u.message:String(u));}}),tn(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.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 r=en.createServer(n),i$1=se()?.provider;i$1&&i$1.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{i("Application started",{source:"app"}),console.log(`
16
16
  Application started on http://localhost:${s}
17
- `);});}async function ve(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},n={ip:on(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!R()){let{session:i,user:s,roles:a}=await k(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:Q()}}function on(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 an({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ut,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Zt.config(),Zt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";bn().then(()=>{}).catch(()=>{});let y=[ut,We,xt,Mt,At,It,xe],u=[...y,...t];e(),ln(y),cn(t),Be(e$1,o);let C=pn(u);d$1(C);let I=dn(u),ae=un(u);d&&fn(u);let ce=mn(u);if(at(ce),l){let{configs:z,environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt}=await mt({configSchema:C,cronJobsMetadata:d?St():void 0,stores:I});c$1(z),f({environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt});}else c$1(wn(C));Ye(i),ot(s),zt({...a,provider:a.provider||Ge});let V=R();if(V&&(await Ve(),hn(I)),d&&Ot(r),V)for(let z of I)z.createIndexes();l&&(await g$1(),ht()),d&&Ct().catch(console.error),await qt(n,{combinedModules:u,channels:ae});}function cn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Se(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Tt(`${e.name}.${o}`,n);}}function ln(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Dt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))vt(`${e.name}.${o}`,n);}}function dn(t){return t.flatMap(e=>e.stores)}function un(t){return t.flatMap(e=>e.channels)}function mn(t){return t.flatMap(e=>e.rateLimits)}function pn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function fn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Et(`${e.name}.${o}`,n);}function hn(t){let e=Y();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var gn={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 yn(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 wn(t){let e=[];for(let[o,n]of Object.entries(gn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:yn(r,s)});}}return e}async function bn(){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 En(),r=await import('./package-DVI2JFS6.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:To.hostname(),environmentId:o})});}}async function En(){try{let t=Te.join(process.cwd(),"package.json"),e=await nn.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Wt(t){await D.deleteMany({userId:t}),await S.deleteMany({userId:t});}async function Sn(t){await Wt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function xn(t){await Wt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Re=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=se().provider;if(!n){j$1("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Tn(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
17
+ `);});}async function ve(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},n={ip:on(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!R()){let{session:i,user:s,roles:a}=await k(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:Q()}}function on(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 an({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ut,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Zt.config(),Zt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";bn().then(()=>{}).catch(()=>{});let y=[ut,We,xt,Mt,At,It,xe],u=[...y,...t];e(),ln(y),cn(t),Be(e$1,o);let C=pn(u);d$1(C);let I=dn(u),ae=un(u);d&&fn(u);let ce=mn(u);if(at(ce),l){let{configs:z,environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt}=await mt({configSchema:C,cronJobsMetadata:d?St():void 0,stores:I});c$1(z),f({environmentId:le,appAlias:Ft,environmentAlias:Bt,telemetry:Jt});}else c$1(wn(C));Ye(i),ot(s),zt({...a,provider:a.provider||Ge});let V=R();if(V&&(await Ve(),hn(I)),d&&Ot(r),V)for(let z of I)z.createIndexes();l&&(await g$1(),ht()),d&&Ct().catch(console.error),await qt(n,{combinedModules:u,channels:ae});}function cn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Se(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Tt(`${e.name}.${o}`,n);}}function ln(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Dt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))vt(`${e.name}.${o}`,n);}}function dn(t){return t.flatMap(e=>e.stores)}function un(t){return t.flatMap(e=>e.channels)}function mn(t){return t.flatMap(e=>e.rateLimits)}function pn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function fn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Et(`${e.name}.${o}`,n);}function hn(t){let e=Y();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var gn={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 yn(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 wn(t){let e=[];for(let[o,n]of Object.entries(gn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:yn(r,s)});}}return e}async function bn(){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 En(),r=await import('./package-Y6FUSHZG.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:To.hostname(),environmentId:o})});}}async function En(){try{let t=Te.join(process.cwd(),"package.json"),e=await nn.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Wt(t){await D.deleteMany({userId:t}),await S.deleteMany({userId:t});}async function Sn(t){await Wt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function xn(t){await Wt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Re=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=se().provider;if(!n){j$1("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Tn(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
18
18
  export{E as Module,Re as ServerChannel,w as Store,k as authenticate,M as consumeRateLimit,Se as createQuery,p as dbUsers,xn as deleteUser,Sn as disableUser,c as schema,Tn as sendEmail,an as startApp};//# sourceMappingURL=server.js.map
19
19
  //# sourceMappingURL=server.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.7.0-dev.0",
4
+ "version": "0.7.0-dev.2",
5
5
  "description": "The Node.js Framework for Real-Time MongoDB Apps",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",
@@ -68,9 +68,6 @@
68
68
  "ts-node": "^10.9.2"
69
69
  },
70
70
  "dependencies": {
71
- "@babel/parser": "^7.28.5",
72
- "@babel/traverse": "^7.28.5",
73
- "@babel/types": "^7.28.5",
74
71
  "@socket.io/mongo-adapter": "^0.4.0",
75
72
  "@vitejs/plugin-react": "^4.3.4",
76
73
  "archiver": "^7.0.1",
@@ -1,3 +0,0 @@
1
- var s="module",i="modelence",r="0.7.0-dev.0",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",n="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",jest:"^30.2.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},h={"@babel/parser":"^7.28.5","@babel/traverse":"^7.28.5","@babel/types":"^7.28.5","@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",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","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",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"},x={react:">=18.0.0","react-dom":">=18.0.0"},v={type:s,name:i,version:r,description:o,main:p,types:n,exports:c,files:d,bin:l,scripts:a,repository:m,author:y,license:u,bugs:j,homepage:g,devDependencies:b,dependencies:h,peerDependencies:x};
2
- export{s as a,i as b,r as c,o as d,p as e,n as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,j as n,g as o,b as p,h as q,x as r,v as s};//# sourceMappingURL=chunk-VQSLCX5F.js.map
3
- //# sourceMappingURL=chunk-VQSLCX5F.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,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,cACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CAC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AA,CAAoB,QAAA,CACpB,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,IAAA,CAAQ,SACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,SAAA,CACX,uBAAA,CAAyB,SAAA,CACzB,IAAO,SAAA,CACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,MAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CArGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAaA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA6BA,gBAAA,CAAAC,CAIF","file":"chunk-VQSLCX5F.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.7.0-dev.0\",\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 \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\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 \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\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/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"jest\": \"^30.2.0\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@babel/parser\": \"^7.28.5\",\n \"@babel/traverse\": \"^7.28.5\",\n \"@babel/types\": \"^7.28.5\",\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\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 \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\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"]}