modelence 0.7.0-dev.6 → 0.7.0

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,40 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {s}from'../chunk-33DVBH5R.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import*as h from'path';import h__default,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import K 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 Ie from'archiver';import ke from'open';var z=".modelence.env";async function re(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 ie(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${z} 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 ae(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 R(e){try{let t=join(process.cwd(),z),o={};try{let l=await promises.readFile(t,"utf8");o=parse(l),await ae(t),await ie()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let n=await re(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}="${se(i)}"`).join(`
3
- `);await promises.writeFile(t,a.trim()+`
4
- `),console.log(`Successfully configured ${z} file`);}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var k=null,B=null;function de(){if(!k)throw new Error("Environment variables not loaded");return k}function U(){if(!B)throw new Error("Configuration not loaded");return B}function G(e){return `${de().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function P(){let{serverDir:e,serverEntry:t}=U();return join(e,t).replace(/\\/g,"/")}function V(){return U().postBuildCommand}function J(e){let t=A("build");return t.replace(/\\/g,"/")}function M(e){return join(process.cwd(),e).replace(/\\/g,"/")}function A(e){let t=M(".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");B=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 K.readFile(join(process.cwd(),".modelence.env"),"utf-8");k=parse(e);}catch(e){if(e.code==="ENOENT")k={};else throw e}}async function Q(e){let t=h.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(g=>r.isPropertyAssignment(g)&&r.isIdentifier(g.name)&&g.name.text==="modules");if(m&&r.isArrayLiteralExpression(m.initializer)){for(let g of m.initializer.elements)if(r.isIdentifier(g)){let f=g.text,d=s.get(f);d&&a.push({name:f,importPath:d,serverDir:t});}}}}r.forEachChild(c,l);}l(n);let i=[];for(let c of a){let p=await pe(c.importPath,c.serverDir);p&&i.push(p);}return i}async function pe(e,t){try{let g=function(f){if(r.isNewExpression(f)&&r.isIdentifier(f.expression)&&f.expression.text==="Module"){let d=f.arguments;if(d&&d.length>0&&r.isStringLiteral(d[0])&&(c=d[0].text),d&&d.length>1&&r.isObjectLiteralExpression(d[1])){let S=d[1],w=S.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 y=r.isIdentifier(u.name)||r.isStringLiteral(u.name)?u.name.text:"";if(y){let N=q(u,s,a,i);p.push({name:y,fullName:`${c}.${y}`,argsType:N.argsType,returnType:N.returnType});}}}let v=S.properties.find(u=>r.isPropertyAssignment(u)&&r.isIdentifier(u.name)&&u.name.text==="mutations");if(v&&r.isObjectLiteralExpression(v.initializer)){for(let u of v.initializer.properties)if(r.isPropertyAssignment(u)||r.isMethodDeclaration(u)){let y=r.isIdentifier(u.name)||r.isStringLiteral(u.name)?u.name.text:"";if(y){let N=q(u,s,a,i);m.push({name:y,fullName:`${c}.${y}`,argsType:N.argsType,returnType:N.returnType});}}}}}r.forEachChild(f,g);};var o=g;let n=await fe(e,t),s=await promises.readFile(n,"utf-8"),a=r.createSourceFile(n,s,r.ScriptTarget.Latest,!0),i=r.createProgram([n],{noEmit:!0,target:r.ScriptTarget.Latest,moduleResolution:r.ModuleResolutionKind.Node10,allowJs:!0,checkJs:!1}).getTypeChecker(),c="",p=[],m=[];return g(a),c?{name:c,queries:p,mutations:m,filePath:n}:null}catch(n){return console.error(`Failed to analyze module file ${e}:`,n),null}}function q(e,t,o,n){let s,a,l,i;if(r.isMethodDeclaration(e))l=e.body,i=e;else if(r.isPropertyAssignment(e)){let d=e.initializer;(r.isArrowFunction(d)||r.isFunctionExpression(d))&&(l=d.body,i=d);}if(!l)return {argsType:s,returnType:a};let c=l.getStart(o),p=l.getEnd(),m=t.substring(c,p),f=/z\.object\(\s*\{([^}]+)\}\s*\)\.parse\(|\.object\(\s*\{([^}]+)\}\s*\)\.parse\(/g.exec(m);if(f){let d=f[1]||f[2];s=me(d);}if(i)try{let d=n.getSignatureFromDeclaration(i);if(d){let S=d.getReturnType();if(S){let w=n.typeToString(S),v=w.match(/^Promise<(.+)>$/);v&&(w=v[1]),w!=="any"&&w!=="void"&&(a=w);}}}catch{}return a||(m.includes("return {")?a="Record<string, unknown>":m.includes("return [")&&(a="unknown[]")),{argsType:s,returnType:a}}function me(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 fe(e,t){if(e.startsWith("./")||e.startsWith("../")){let o=h.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 W(e){return e.map(t=>ge(t))}function ge(e){let o=`use${Z(e.name)}Store`,n=he(e.queries),s=we(e.mutations),a=`// Generated by Modelence - DO NOT EDIT MANUALLY
5
- import { create } from 'zustand';
6
- import { callMethod } from 'modelence/client';
7
-
8
- export const ${o} = create((set, get) => ({
9
- ${n.dataFields}
10
- ${s.dataFields}
11
-
12
- ${n.implementations}
13
- ${s.implementations}
14
- }));
15
- `;return {fileName:`${e.name}.ts`,content:a}}function he(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 we(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 Z(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function Y(e){return `// Generated by Modelence - DO NOT EDIT MANUALLY
28
- /**
29
- * Auto-generated zustand stores for all modules
30
- * Import these stores in your client-side code to interact with the server
31
- */
32
-
33
- ${e.map(o=>`export { ${`use${Z(o.name)}Store`} } from './${o.name}';`).join(`
34
- `)}
35
- `}async function F(e={}){let{serverPath:t=await ye(),outputDir:o=h.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 Q(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=W(n);for(let i of s){let c=h.join(o,i.fileName);await promises.writeFile(c,i.content,"utf-8"),console.log(` \u2713 Generated: ${i.fileName}`);}let a=Y(n),l=h.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${Ee(n[0].name)}Store } from '.modelence/stores';
37
- `);}catch(n){throw console.error("\u274C Failed to generate zustand stores:",n),n}}async function ye(){try{let t=h.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=h.join(process.cwd(),n[1],s[1]);return await promises.access(a),a}}catch{}let e=[h.join(process.cwd(),"src/server/app.ts"),h.join(process.cwd(),"src/server/index.ts"),h.join(process.cwd(),"server/app.ts"),h.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 Ee(e){return e.split(/[-_\s]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function be(){let e=V();if(e){console.log("Running post-build command..."),execSync(e);return}await Te();}async function Te(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:h__default.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function $e(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[P()],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=J();await K.rm(e,{recursive:!0,force:!0}),console.log(`
38
- \u{1F527} Generating zustand stores...`);try{await F();}catch(t){console.warn(`
39
- \u26A0\uFE0F Store generation failed, continuing anyway...`),console.warn(t);}await $e(),await be(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await K.access(A());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function X(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 ke(n);let s=await De(e,o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function De(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let a=await Fe(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 Fe(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 H(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||G("");await O(),await Le(n);let{token:a}=await X(s),{bundleName:l}=await ze(e.app,e.env,n,a,s);await promises.unlink(n),await Be(e.app,e.env,l,join(".modelence","build","app.mjs"),a,s);}async function Le(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=Ie("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(M(i)).then(()=>true).catch(()=>false)&&o.file(M(i),{name:i});for(let i of a)await promises.access(M(i)).then(()=>true).catch(()=>false)&&o.directory(M(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 ze(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 Be(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 ee(){console.log("Starting Modelence dev server...");try{await F();}catch(o){console.warn("\u26A0\uFE0F Store generation failed, continuing anyway..."),console.warn(o);}let e=P(),t=h__default.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var qe=fileURLToPath(import.meta.url),Qe=dirname(qe),We=JSON.parse(readFileSync(join(Qe,"../../package.json"),"utf-8")),T=new Command().name("modelence").description("Modelence CLI tool").version(We.version);T.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 R(e);});T.command("build").description("Build the application").action(async()=>{await j(),await O();});T.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 H(e);});T.command("dev").description("Start development server").action(async()=>{await j(),await ee();});T.parse(process.argv);//# sourceMappingURL=modelence.js.map
2
+ import {s}from'../chunk-DWZLITCD.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import X,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import j from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import se from'archiver';import ee from'open';var C=".modelence.env";async function I(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${C} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function R(e){return String(e).replace(/"/g,'\\"')}async function U(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function x(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await U(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(e.token,e.host),s={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},i=Object.entries(s).map(([a,n])=>`${a}="${R(n)}"`).join(`
3
+ `);await promises.writeFile(o,i.trim()+`
4
+ `),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var g=null,b=null;function J(){if(!g)throw new Error("Environment variables not loaded");return g}function S(){if(!b)throw new Error("Configuration not loaded");return b}function D(e){return `${J().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function w(){let{serverDir:e,serverEntry:o}=S();return join(e,o).replace(/\\/g,"/")}function O(){return S().postBuildCommand}function T(e){let o=N("build");return o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function N(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function h(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");b=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await j.readFile(join(process.cwd(),".modelence.env"),"utf-8");g=parse(e);}catch(e){if(e.code==="ENOENT")g={};else throw e}}async function H(){let e=O();if(e){console.log("Running post-build command..."),execSync(e);return}await Q();}async function Q(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:X.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function Z(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[w()],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 E(){console.log("Building Modelence project...");try{let e=T();await j.rm(e,{recursive:!0,force:!0}),await Z(),await H(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await j.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function P(e){let o=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!o.ok)throw new Error("Failed to create CLI authentication code");let{code:t,verificationUrl:r}=await o.json();console.log(`Please visit ${r} to authenticate`),console.log(`Code: ${t}`),await ee(r);let s=await ne(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function ne(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await re(e,o);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function re(e,o){let t=await fetch(`${e}/api/cli/token?code=${o}`,{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:r}=await t.json();return r}async function $(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||D("");await E(),await ae(r);let{token:i}=await P(s),{bundleName:a}=await ce(e.app,e.env,r,i,s);await promises.unlink(r),await le(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function ae(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 o=createWriteStream(e),t=se("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,m)=>{o.on("close",n),o.on("error",m),t.on("error",m);});t.pipe(o);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server",join(".modelence","build"),".next"];for(let n of s)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.file(p(n),{name:n});for(let n of i)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.directory(p(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ce(e,o,t,r,s){let i=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:a,bundleName:n}=await i.json(),m=await promises.readFile(t),k=await fetch(a,{method:"PUT",body:new Uint8Array(m),headers:{"Content-Type":"application/zip"}});if(!k.ok)throw new Error(`Failed to upload bundle: ${k.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function le(e,o,t,r,s,i){let a=await fetch(`${i}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:n}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${n}`);}function B(){console.log("Starting Modelence dev server...");let e=w(),o=X.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var he=fileURLToPath(import.meta.url),Ee=dirname(he),ve=JSON.parse(readFileSync(join(Ee,"../../package.json"),"utf-8")),u=new Command().name("modelence").description("Modelence CLI tool").version(ve.version);u.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 x(e);});u.command("build").description("Build the application").action(async()=>{await h(),await E();});u.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 h(),await $(e);});u.command("dev").description("Start development server").action(async()=>{await h(),B();});u.parse(process.argv);//# sourceMappingURL=modelence.js.map
40
5
  //# 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","analyzeModulesFromServerFile","serverPath","D","serverCode","sourceFile","moduleImports","foundModules","visitNode","node","importPath","element","configArg","modulesProperty","prop","moduleName","analyzedModules","moduleInfo","analyzed","analyzeModuleFile","args","queriesProperty","queryName","typeInfo","extractMethodTypes","moduleCode","typeChecker","queries","mutationsProperty","mutationName","mutations","fullPath","resolveModulePath","sourceCode","argsType","returnType","functionBody","functionNode","initializer","start","end","methodSource","zodMatch","schemaContent","convertZodSchemaToTypeScript","signature","returnTypeNode","typeString","promiseMatch","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,CAAK,CAAA,CAAE,OAAA,CAAQ,KAAM,KAAK,CAC1C,CAEA,eAAeC,EAAAA,CAAcC,CAAAA,CAAgC,CAC3D,GAAI,CACF,IAAMC,CAAAA,CAAaD,CAAAA,CAAQ,OAAA,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AO,CAAA,CACf,WAAA,CAAY,uBAAuB,CAAA,CACnC,MAAA,CAAO,SAAY,CAClB,MAAM1J,CAAAA,EAAQ,CACd,MAAM8G,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,MAAOjL,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,GACN,MAAMwH,CAAAA,CAAO/I,CAAO,EACtB,CAAC,CAAA,CAEHiL,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM1J,CAAAA,EAAQ,CACd,MAAMkJ,EAAAA,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(serverPath, serverCode, ts.ScriptTarget.Latest, true);\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(fullPath, moduleCode, ts.ScriptTarget.Latest, true);\n\n // Create TypeScript program and type checker for type inference\n const program = ts.createProgram([fullPath], {\n noEmit: true,\n target: ts.ScriptTarget.Latest,\n moduleResolution: ts.ModuleResolutionKind.Node10,\n allowJs: true,\n checkJs: false,\n });\n const typeChecker = program.getTypeChecker();\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, typeChecker);\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, typeChecker);\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 typeChecker: ts.TypeChecker\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 let functionNode: ts.FunctionLikeDeclaration | undefined;\n\n if (ts.isMethodDeclaration(prop)) {\n functionBody = prop.body;\n functionNode = prop;\n } else if (ts.isPropertyAssignment(prop)) {\n const initializer = prop.initializer;\n if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) {\n functionBody = initializer.body;\n functionNode = initializer;\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 // Try to use TypeScript's type checker for return type inference\n if (functionNode) {\n try {\n const signature = typeChecker.getSignatureFromDeclaration(functionNode);\n if (signature) {\n const returnTypeNode = signature.getReturnType();\n if (returnTypeNode) {\n // Get the type string, removing Promise wrapper if present\n let typeString = typeChecker.typeToString(returnTypeNode);\n\n // Remove Promise wrapper: Promise<Type> -> Type\n const promiseMatch = typeString.match(/^Promise<(.+)>$/);\n if (promiseMatch) {\n typeString = promiseMatch[1];\n }\n\n // Only use the inferred type if it's not 'any' or 'void'\n if (typeString !== 'any' && typeString !== 'void') {\n returnType = typeString;\n }\n }\n }\n } catch {\n // If type checker fails, fall back to basic pattern matching\n // This can happen with certain syntax patterns\n }\n }\n\n // Fallback to basic pattern matching if type checker didn't work\n if (!returnType) {\n if (methodSource.includes('return {')) {\n returnType = 'Record<string, unknown>';\n } else if (methodSource.includes('return [')) {\n returnType = 'unknown[]';\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}\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"]}
1
+ {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.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","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","serverPath","tsxPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";4gBAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,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,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAA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AAY,CACzB,MAAMD,CAAAA,CAAMC,CAAO,EACrB,CAAC,CAAA,CAEHsF,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,uBAAuB,CAAA,CACnC,MAAA,CAAO,SAAY,CAClB,MAAM/D,GAAQ,CACd,MAAMkB,IACR,CAAC,CAAA,CAEH6C,CAAAA,CACG,QAAQ,QAAQ,CAAA,CAChB,YAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,cAAA,CAAe,kBAAmB,mBAAmB,CAAA,CACrD,OAAO,mBAAA,CAAqB,gBAAgB,EAC5C,MAAA,CAAO,MAAOtF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,EAAQ,CACd,MAAM4B,CAAAA,CAAOnD,CAAO,EACtB,CAAC,CAAA,CAEHsF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM/D,CAAAA,EAAQ,CACdsD,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,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 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';\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 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';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\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 dev();\n });\n\nprogram.parse(process.argv);\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",o="0.7.0",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-DWZLITCD.js.map
3
+ //# sourceMappingURL=chunk-DWZLITCD.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,QACXC,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,CACjB,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,CAAAA,CAAU,YACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA,CAAO,+CACT,EACAC,CAAAA,CAAY,uBAAA,CACZC,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,QAAA,CACnB,gBAAiB,QAAA,CACjB,sBAAA,CAAwB,QAAA,CACxB,gBAAA,CAAkB,QAAA,CAClB,iBAAA,CAAmB,UACnB,aAAA,CAAe,SAAA,CACf,aAAA,CAAe,SAAA,CACf,cAAA,CAAgB,SAAA,CAChB,mBAAo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,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-DWZLITCD.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.7.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 \"@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"]}
package/dist/client.d.ts CHANGED
@@ -21,7 +21,10 @@ declare function renderApp({ loadingElement, routesElement, favicon, errorHandle
21
21
  }): void;
22
22
 
23
23
  type MethodArgs = Record<string, unknown>;
24
- declare function callMethod<T = unknown>(methodName: string, args?: MethodArgs): Promise<T>;
24
+ type CallMethodOptions = {
25
+ errorHandler?: (error: Error, methodName: string) => void;
26
+ };
27
+ declare function callMethod<T = unknown>(methodName: string, args?: MethodArgs, options?: CallMethodOptions): Promise<T>;
25
28
 
26
29
  type User = {
27
30
  id: string;
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-3S2FFBNS.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import U,{useState,useEffect}from'react';import {create}from'zustand';import {z}from'zod';import {jsx}from'react/jsx-runtime';import K from'react-dom/client';import Y from'socket.io-client';function a(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(t){return console.error("Error parsing session from localStorage",t),null}}function y(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var v=(e,t)=>{throw new Error(`Error calling method '${t}': ${e.toString()}`)};function C(e){v=e;}function k(e,t){return v(e,t)}async function i(e,t={}){try{return await I(`/api/_internal/method/${e}`,t)}catch(r){throw k(r,e),r}}async function I(e,t){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:t,authToken:a()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!r.ok){let s=await r.text();throw new Error(s)}let o=await r.text(),n=o?JSON.parse(o):void 0;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}var S={};function L(e){return S[e]?.value}function x(e){S=e;}var p=create(e=>({user:null,setUser:t=>e({user:t})})),P=false,_=a$1.seconds(30);async function E(){if(P)return;P=true;let{configs:e,session:t,user:r}=await i("_system.session.init");x(e),y(t);let o=r?(()=>{let n=z.object({id:z.string(),handle:z.string(),roles:z.array(z.string())}).parse(r);return Object.freeze({...n,hasRole:s=>n.roles.includes(s),requireRole:s=>{if(!n.roles.includes(s))throw new Error(`Access denied - role '${s}' required`)}})})():null;p.getState().setUser(o),await T();}async function T(){await i("_system.session.heartbeat"),setTimeout(T,_);}function u(e){p.getState().setUser(e);}function j(){return {user:p(t=>t.user)}}var b=false;function g({children:e,loadingElement:t}){let[r,o]=useState(true);return useEffect(()=>{async function n(){b||(b=true,await E(),o(false));}n();},[]),r?t??jsx("div",{children:"Loading..."}):e}function B({loadingElement:e,routesElement:t,favicon:r,errorHandler:o}){if(o&&C(o),window.addEventListener("unload",()=>{}),K.createRoot(document.getElementById("root")).render(jsx(U.StrictMode,{children:jsx(W,{loadingElement:e,children:t})})),r){let n=document.querySelector("link[rel~='icon']");if(n)n.href=r;else {let s=document.createElement("link");s.rel="icon",s.href=r,document.head.appendChild(s);}}}async function D(e){let{email:t,password:r}=e;await i("_system.user.signupWithPassword",{email:t,password:r});}async function V(e){let{email:t,password:r}=e,{user:o}=await i("_system.user.loginWithPassword",{email:t,password:r});return u(o),o}async function F(e){let{token:t}=e;await i("_system.user.verifyEmail",{token:t});}async function G(){await i("_system.user.logout"),u(null);}async function Q(e){let{email:t}=e;await i("_system.user.sendResetPasswordToken",{email:t});}async function X(e){let{token:t,password:r}=e;await i("_system.user.resetPassword",{token:t,password:r});}var c;function Z(e){c=Y("/",{auth:{token:a()?.authToken}}),e.channels?.forEach(t=>t.init());}function ee({category:e,listener:t}){c.on(e,t);}function te({category:e,listener:t}){c.once(e,t);}function re({category:e,listener:t}){c.off(e,t);}function f({eventName:e,category:t,id:r}){c.emit(e,`${t}:${r}`);}function oe({category:e,id:t}){f({eventName:"joinChannel",category:e,id:t});}function ne({category:e,id:t}){f({eventName:"leaveChannel",category:e,id:t});}var ie={init:Z,on:ee,once:te,off:re,emit:f,joinChannel:oe,leaveChannel:ne},A=ie;var H=null;function M(e){H=e;}function d(){return H}function se(e){let t=e?.provider||A;t.init({channels:e?.channels}),M(t);}var m=class{constructor(t,r){this.category=t,this.onMessage=r;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(t){d()?.joinChannel({category:this.category,id:t});}leaveChannel(t){d()?.leaveChannel({category:this.category,id:t});}};var W="useClient"in U?U.useClient(g):g;export{W as AppProvider,m as ClientChannel,i as callMethod,L as getConfig,a as getLocalStorageSession,d as getWebsocketClientProvider,V as loginWithPassword,G as logout,B as renderApp,X as resetPassword,Q as sendResetPasswordToken,M as setWebsocketClientProvider,D as signupWithPassword,se as startWebsockets,j as useSession,F as verifyEmail};//# sourceMappingURL=client.js.map
1
+ import {b as b$1}from'./chunk-3S2FFBNS.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import N,{useState,useEffect}from'react';import {create}from'zustand';import {z}from'zod';import {jsx}from'react/jsx-runtime';import K from'react-dom/client';import Y from'socket.io-client';function a(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function y(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var v=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function C(e){v=e;}function k(e,r){return v(e,r)}async function i(e,r={},t={}){try{return await U(`/api/_internal/method/${e}`,r)}catch(o){throw (t.errorHandler??k)(o,e),o}}async function U(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:a()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!t.ok){let s=await t.text();throw new Error(s)}let o=await t.text(),n=o?JSON.parse(o):void 0;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}var S={};function I(e){return S[e]?.value}function x(e){S=e;}var p=create(e=>({user:null,setUser:r=>e({user:r})})),P=false,_=a$1.seconds(30);async function E(){if(P)return;P=true;let{configs:e,session:r,user:t}=await i("_system.session.init");x(e),y(r);let o=t?(()=>{let n=z.object({id:z.string(),handle:z.string(),roles:z.array(z.string())}).parse(t);return Object.freeze({...n,hasRole:s=>n.roles.includes(s),requireRole:s=>{if(!n.roles.includes(s))throw new Error(`Access denied - role '${s}' required`)}})})():null;p.getState().setUser(o),await T();}async function T(){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(T,_);}function u(e){p.getState().setUser(e);}function j(){return {user:p(r=>r.user)}}var b=false;function g({children:e,loadingElement:r}){let[t,o]=useState(true);return useEffect(()=>{async function n(){b||(b=true,await E(),o(false));}n();},[]),t?r??jsx("div",{children:"Loading..."}):e}function B({loadingElement:e,routesElement:r,favicon:t,errorHandler:o}){if(o&&C(o),window.addEventListener("unload",()=>{}),K.createRoot(document.getElementById("root")).render(jsx(N.StrictMode,{children:jsx(W,{loadingElement:e,children:r})})),t){let n=document.querySelector("link[rel~='icon']");if(n)n.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}async function D(e){let{email:r,password:t}=e;await i("_system.user.signupWithPassword",{email:r,password:t});}async function V(e){let{email:r,password:t}=e,{user:o}=await i("_system.user.loginWithPassword",{email:r,password:t});return u(o),o}async function F(e){let{token:r}=e;await i("_system.user.verifyEmail",{token:r});}async function G(){await i("_system.user.logout"),u(null);}async function Q(e){let{email:r}=e;await i("_system.user.sendResetPasswordToken",{email:r});}async function X(e){let{token:r,password:t}=e;await i("_system.user.resetPassword",{token:r,password:t});}var c;function Z(e){c=Y("/",{auth:{token:a()?.authToken}}),e.channels?.forEach(r=>r.init());}function ee({category:e,listener:r}){c.on(e,r);}function re({category:e,listener:r}){c.once(e,r);}function te({category:e,listener:r}){c.off(e,r);}function f({eventName:e,category:r,id:t}){c.emit(e,`${r}:${t}`);}function oe({category:e,id:r}){f({eventName:"joinChannel",category:e,id:r});}function ne({category:e,id:r}){f({eventName:"leaveChannel",category:e,id:r});}var ie={init:Z,on:ee,once:re,off:te,emit:f,joinChannel:oe,leaveChannel:ne},A=ie;var H=null;function M(e){H=e;}function d(){return H}function se(e){let r=e?.provider||A;r.init({channels:e?.channels}),M(r);}var m=class{constructor(r,t){this.category=r,this.onMessage=t;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(r){d()?.joinChannel({category:this.category,id:r});}leaveChannel(r){d()?.leaveChannel({category:this.category,id:r});}};var W="useClient"in N?N.useClient(g):g;export{W as AppProvider,m as ClientChannel,i as callMethod,I as getConfig,a as getLocalStorageSession,d as getWebsocketClientProvider,V as loginWithPassword,G as logout,B as renderApp,X as resetPassword,Q as sendResetPasswordToken,M as setWebsocketClientProvider,D as signupWithPassword,se as startWebsockets,j as useSession,F as verifyEmail};//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map