modelence 0.18.0-dev.3 → 0.18.0-dev.4

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import S,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T 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 ce from'archiver';import te from'open';var C=".modelence.env";async function z(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 J(){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 A(e){return String(e).replace(/"/g,'\\"')}async function q(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 D(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await q(o),await J()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await z(e.token,e.host),s={...t,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}="${A(n)}"`).join(`
2
+ import {a}from'../chunk-FL573BOT.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import S,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import P from'fs/promises';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ae from'archiver';import oe from'open';var b=".modelence.env";async function z(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 A(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function J(e){return String(e).replace(/"/g,'\\"')}async function q(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 D(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await q(o),await A()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await z(e.token,e.host),s={...t,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}="${J(n)}"`).join(`
3
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 h=null,N=null;function X(){if(!h)throw new Error("Environment variables not loaded");return h}function E(){if(!N)throw new Error("Configuration not loaded");return N}function O(e){return `${X().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function d(){let{serverDir:e,serverEntry:o}=E();return join(e,o).replace(/\\/g,"/")}function P(){return E().postBuildCommand}function v(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function f(){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");N=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional(),ssr:z$1.boolean().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");h=parse(e);}catch(e){if(e.code==="ENOENT")h={};else throw e}}async function Q(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}let o=!!E().ssr;await Z({ssr:o}),o&&await ee();}async function Z({ssr:e}){console.log("Building client with Vite...");let o=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:S.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:e}};await build$1(mergeConfig(o?.config||{},t,true));}async function ee(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:S.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:S.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},t,true));}async function oe(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[d()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function y(){console.log("Building Modelence project...");try{let e=v();await T.rm(e,{recursive:!0,force:!0}),await oe(),await Q(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function M(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 te(r);let s=await ie(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function ie(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await se(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 se(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 F(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await y(),await le(r);let{token:i}=await M(s),{bundleName:a}=await de(e.app,e.env,r,i,s);await promises.unlink(r),await pe(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function le(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=ce("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,w)=>{o.on("close",n),o.on("error",w),t.on("error",w);});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 de(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(),w=await promises.readFile(t),k=await fetch(a,{method:"PUT",body:new Uint8Array(w),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 pe(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 _(){console.log("Starting Modelence dev server...");let e=d(),o=S.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function L(){console.log("Starting Modelence production server...");let e=d(),o=S.basename(e,S.extname(e)),t=v(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var ye=fileURLToPath(import.meta.url),be=dirname(ye),Ce=JSON.parse(readFileSync(join(be,"../../package.json"),"utf-8")),u=new Command().name("modelence").description("Modelence CLI tool").version(Ce.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 D(e);});u.command("build").description("Build the application").action(async()=>{await f(),await y();});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 f(),await F(e);});u.command("dev").description("Start development server").action(async()=>{await f(),_();});u.command("start").description("Start production server").action(async()=>{await f(),L();});u.parse(process.argv);//# sourceMappingURL=modelence.js.map
4
+ `),console.log(`Successfully configured ${b} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,C=null;function K(){if(!w)throw new Error("Environment variables not loaded");return w}function h(){if(!C)throw new Error("Configuration not loaded");return C}function O(e){return `${K().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function l(){let{serverDir:e,serverEntry:o}=h();return join(e,o).replace(/\\/g,"/")}function T(){return h().postBuildCommand}function E(e){let o=N("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function N(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){try{C=await a();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await P.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function H(){let e=T();if(e){console.log("Running post-build command..."),execSync(e);return}let o=!!h().ssr;await Q({ssr:o}),o&&await Z();}async function Q({ssr:e}){console.log("Building client with Vite...");let o=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:S.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:e}};await build$1(mergeConfig(o?.config||{},t,true));}async function Z(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:S.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:S.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},t,true));}async function ee(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[l()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=E();await P.rm(e,{recursive:!0,force:!0}),await ee(),await H(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await P.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function j(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 oe(r);let s=await re(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function re(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await ie(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 ie(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 F(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await v(),await ce(r);let{token:i}=await j(s),{bundleName:a}=await le(e.app,e.env,r,i,s);await promises.unlink(r),await de(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function ce(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=ae("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,g)=>{o.on("close",n),o.on("error",g),t.on("error",g);});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(d(n)).then(()=>true).catch(()=>false)&&t.file(d(n),{name:n});for(let n of i)await promises.access(d(n)).then(()=>true).catch(()=>false)&&t.directory(d(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 le(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(),g=await promises.readFile(t),x=await fetch(a,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!x.ok)throw new Error(`Failed to upload bundle: ${x.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function de(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 _(){console.log("Starting Modelence dev server...");let e=l(),o=S.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function L(){console.log("Starting Modelence production server...");let e=l(),o=S.basename(e,S.extname(e)),t=E(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var ve=fileURLToPath(import.meta.url),ye=dirname(ve),be=JSON.parse(readFileSync(join(ye,"../../package.json"),"utf-8")),p=new Command().name("modelence").description("Modelence CLI tool").version(be.version);p.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 D(e);});p.command("build").description("Build the application").action(async()=>{await m(),await v();});p.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 m(),await F(e);});p.command("dev").description("Start development server").action(async()=>{await m(),_();});p.command("start").description("Start production server").action(async()=>{await m(),L();});p.parse(process.argv);//# sourceMappingURL=modelence.js.map
5
5
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
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/start.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","ssrEnabled","buildVite","buildViteSsr","ssr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","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","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";8eAKA,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,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,EAED,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,EAAO,WAAA,EAAY,GAAM,GAAG,EACtC,CACF,EACF,CAAC,CACH,CAEA,SAASC,CAAAA,CAAeC,CAAAA,CAAgC,CAEtD,OAAO,MAAA,CAAOA,CAAK,CAAA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AAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAMpE,GAAQ,CACdwD,CAAAA,GACF,CAAC,CAAA,CAEHY,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,yBAAyB,EACrC,MAAA,CAAO,SAAY,CAClB,MAAMpE,CAAAA,GACN2D,CAAAA,GACF,CAAC,CAAA,CAEHS,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_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 ssr: z.boolean().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 {\n getBuildPath,\n getConfig,\n getModelencePath,\n getPostBuildCommand,\n getServerPath,\n} 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';\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 const ssrEnabled = Boolean(getConfig().ssr);\n\n await buildVite({ ssr: ssrEnabled });\n\n if (ssrEnabled) {\n await buildViteSsr();\n }\n}\n\nasync function buildVite({ ssr }: { ssr: boolean }) {\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 // Emit `.vite/ssr-manifest.json` so the SSR runtime can map rendered\n // modules to their CSS assets (see ssr/collectCss.ts:loadProdCssAssets).\n ssrManifest: ssr,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\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 skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\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 --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\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 { start } from './start';\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\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\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/start.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","loadModelenceConfig","parseDotenv","buildClient","postBuildCommand","execSync","ssrEnabled","buildVite","buildViteSsr","ssr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","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","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";0dAKA,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,C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,MAAMuB,CAAAA,EAAQ,CACd,MAAM2B,CAAAA,CAAOlD,CAAO,EACtB,CAAC,CAAA,CAEHwF,EACG,OAAA,CAAQ,KAAK,EACb,WAAA,CAAY,0BAA0B,EACtC,MAAA,CAAO,SAAY,CAClB,MAAMjE,CAAAA,GACNqD,CAAAA,GACF,CAAC,CAAA,CAEHY,CAAAA,CACG,QAAQ,OAAO,CAAA,CACf,YAAY,yBAAyB,CAAA,CACrC,OAAO,SAAY,CAClB,MAAMjE,CAAAA,EAAQ,CACdwD,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_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 { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\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 config = await loadModelenceConfig();\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 {\n getBuildPath,\n getConfig,\n getModelencePath,\n getPostBuildCommand,\n getServerPath,\n} 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';\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 const ssrEnabled = Boolean(getConfig().ssr);\n\n await buildVite({ ssr: ssrEnabled });\n\n if (ssrEnabled) {\n await buildViteSsr();\n }\n}\n\nasync function buildVite({ ssr }: { ssr: boolean }) {\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 // Emit `.vite/ssr-manifest.json` so the SSR runtime can map rendered\n // modules to their CSS assets (see ssr/collectCss.ts:loadProdCssAssets).\n ssrManifest: ssr,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\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 skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\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 --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\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 { start } from './start';\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\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
@@ -0,0 +1,2 @@
1
+ import {join}from'path';import {createJiti}from'jiti';import {z}from'zod';var n=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional(),ssr:z.boolean().optional()});async function m(){let t=join(process.cwd(),"modelence.config.ts"),e=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(t);if(typeof e!="object")throw new Error("modelence.config.ts should export an object");return n.parse(e)}export{m as a};//# sourceMappingURL=chunk-FL573BOT.js.map
2
+ //# sourceMappingURL=chunk-FL573BOT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/app/modelenceConfig.ts"],"names":["configSchema","z","loadModelenceConfig","configPath","join","configModule","createJiti"],"mappings":"0EAKA,IAAMA,CAAAA,CAAeC,CAAAA,CAAE,MAAA,CAAO,CAC5B,SAAA,CAAWA,CAAAA,CAAE,MAAA,EAAO,CACpB,YAAaA,CAAAA,CAAE,MAAA,EAAO,CACtB,gBAAA,CAAkBA,EAAE,MAAA,EAAO,CAAE,QAAA,EAAS,CACtC,IAAKA,CAAAA,CAAE,OAAA,EAAQ,CAAE,QAAA,EACnB,CAAC,CAAA,CAED,eAAsBC,CAAAA,EAAgD,CACpE,IAAMC,CAAAA,CAAaC,IAAAA,CAAK,OAAA,CAAQ,KAAI,CAAG,qBAAqB,CAAA,CAOtDC,CAAAA,CAAe,MALRC,UAAAA,CAAW,MAAA,CAAA,IAAA,CAAY,GAAA,CAAK,CACvC,eAAgB,IAAA,CAChB,YAAA,CAAc,KAChB,CAAC,EAE+B,MAAA,CAAOH,CAAU,CAAA,CACjD,GAAI,OAAOE,CAAAA,EAAiB,QAAA,CAC1B,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAG/D,OAAOL,CAAAA,CAAa,KAAA,CAAMK,CAAY,CACxC","file":"chunk-FL573BOT.js","sourcesContent":["import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n ssr: z.boolean().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\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\n return configSchema.parse(configModule);\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import {s as s$1}from'./chunk-UMT3RHGL.js';import {a,b,c,k,l,m,n,g,h as h$1,f,s,e,i,d,j as j$1,o,t,u,v,w as w$1,x,q as q$1,p,A,y as y$1,z as z$1}from'./chunk-GZI4X3CV.js';import {d as d$1,a as a$5}from'./chunk-C3UESBRX.js';import {a as a$2,f as f$1,e as e$1,g as g$1,c as c$1,h as h$2,k as k$1,j as j$2,d as d$2,i as i$1,l as l$1,m as m$1}from'./chunk-3SPXJEOR.js';import {a as a$3}from'./chunk-FL573BOT.js';import {a as a$4,b as b$1}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import _r from'dotenv';import Ho from'fs/promises';import fo from'os';import W from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoClient,MongoError,MongoServerError}from'mongodb';export{ObjectId as m}from'mongodb';import Jr from'bcrypt';import I,{z}from'zod';import {randomBytes,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Lo from'@vitejs/plugin-react';import qe from'fs';import U,{Router}from'express';import Ri from'cookie-parser';import Ai from'http';var Z=new a("_system",{configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var P=null;async function At(){if(P)return P;let e=D();if(!e)throw new Error("MongoDB URI is not set");let t=Z.getConfig("mongodbPoolSize");P=new MongoClient(e,{driverInfo:{name:"Modelence",version:s$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await P.connect(),await P.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),P}catch(r){throw console.error(r),P=null,r}}function D(){return Z.getConfig("mongodbUri")||void 0}function me(){return P}var ee=null,Fr="_modelenceSocketio",kt=60;async function Vr({httpServer:e,channels:t}){let r=me(),o=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let i=null;if(o&&r){i=r.db().collection(Fr);try{await i.createIndex({createdAt:1},{expireAfterSeconds:kt,background:!0});}catch(n){if(n instanceof Error&&"code"in n&&n.code===85)try{await i.dropIndex("createdAt_1"),await i.createIndex({createdAt:1},{expireAfterSeconds:kt,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",n);}}ee=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:i?createAdapter(i):void 0,transports:["websocket"],perMessageDeflate:false}),ee.on("error",n=>{console.error("Socket.IO error:",n);}),ee.use(async(n,s)=>{let a=n.handshake.auth.token;try{n.data=await q$1(a);}finally{s();}}),ee.on("connection",n=>{n.on("disconnect",()=>{A(n);}),n.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(n.data))&&(n.join(s),c=true,n.emit("joinedChannel",s));break}c||n.emit("joinError",{channel:s,error:"Access denied"});}),n.on("leaveChannel",s=>{n.leave(s),console.log(`User ${n.id} left channel ${s}`),n.emit("leftChannel",s);}),n.on("subscribeLiveQuery",s=>y$1(n,s)),n.on("unsubscribeLiveQuery",s=>z$1(n,s));}),console.log("Socket.IO server initialized");}function zr({category:e,id:t,data:r}){ee?.to(`${e}:${t}`).emit(e,r);}var xt={init:Vr,broadcast:zr};async function Ot(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let r=t[1];return !!await l.findOne({domain:r})}var Lt={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let r=(await e.text()).split(`
2
+ `).map(n=>n.trim().toLowerCase()).filter(n=>n.length>0),o=new Date,i=500;for(let n=0;n<r.length;n+=i){let s=r.slice(n,n+i);try{await l.insertMany(s.map(a=>({domain:a,addedAt:o})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var pe=3,$=50,_t=8,Pt=128,Mt=254,It=e=>z.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),Oe=e=>z.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),Br=z.object({firstName:Oe({max:50}),lastName:Oe({max:50}),avatarUrl:Oe({max:400}),handle:It({min:pe,max:$})}).strict();function fe(e){let t=Br.partial().safeParse(e);if(!t.success){let r=t.error.issues[0],o=r.path.join("."),i=o?`${o}: ${r.message}`:r.message;throw new Error(i)}return t.data}function ge(e){return z.string().min(_t,{message:`Password must contain at least ${_t} characters`}).max(Pt,{message:`Password must be at most ${Pt} characters`}).parse(e)}function M(e){return z.string().max(Mt,{message:`Email must be at most ${Mt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Ut(e){return It({min:pe,max:$}).parse(e)}function he(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function Tt(e){let t=e.slice(0,$);try{if(!await k.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(i){throw new Error(`Database error while checking handle availability: ${i}`)}let r=51;for(let i=2;i<=r;i++){let n=`_${i}`,s=`${t.slice(0,$-n.length)}${n}`;try{if(!await k.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let o=10;for(let i=0;i<o;i++){let n=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,$-n.length)}${n}`;try{if(!await k.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function j(e,t,{throwOnConflict:r=true}={}){if(e!=null&&String(e).trim()!==""){let i=Ut(String(e).trim());if(r){if(await k.findOne({handle:i},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return i}return Tt(i)}let o=t.split("@")[0].padEnd(pe,"_").slice(0,$);return Tt(o)}var Le=Object.freeze({});function Nt(e){Le=Object.freeze(Object.assign({},Le,e));}function w(){return Le}var _e=Object.freeze({});function Dt(e){_e=Object.freeze(Object.assign({},_e,e));}function y(){return _e}async function jt(e,{user:t,session:r,connectionInfo:o,res:i}){try{if(!r)throw new Error("Session is not initialized");let n=o?.ip;n&&await R({bucket:"signin",type:"ip",value:n});let s=M(e.email),a=z.string().parse(e.password),c=await k.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=c?.authMethods?.password?.hash;if(!l)throw $t();if(!c.emails?.find(b=>b.address.toLowerCase()===s)?.verified&&w()?.provider)throw new Error("Your email address hasn't been verified yet. Please check your inbox for the verification email.");if(!await Jr.compare(a,l))throw $t();return await d(r.authToken,c._id),i&&h$1(i,r.authToken),y().onAfterLogin?.({provider:"email",user:c,session:r,connectionInfo:o}),y().login?.onSuccess?.(c),{user:he(c)}}catch(n){throw n instanceof Error&&(y().onLoginError?.({provider:"email",error:n,session:r,connectionInfo:o}),y().login?.onError?.(n)),n}}async function Ht(e$1,{session:t,res:r}){if(!t)throw new Error("Session is not initialized");await e(t.authToken),r&&i(r);}function $t(){return new Error("Incorrect email/password combination")}async function Gt(e,{user:t}){if(!t)throw new Error("Not authenticated");let r=await k.requireById(t.id);return {handle:r.handle,emails:r.emails,authMethods:Object.keys(r.authMethods||{}),firstName:r.firstName??void 0,lastName:r.lastName??void 0,avatarUrl:r.avatarUrl??void 0}}async function Ft(e,{user:t}){if(!t)throw new Error("Not authenticated");let r=await k.requireById(t.id),o=fe(e);if(await y().validateProfileUpdate?.(o),"handle"in o&&o.handle!==void 0&&await k.findOne({handle:o.handle,_id:{$ne:r._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(o).length>0){let i={},n={};for(let[a,c]of Object.entries(o))c===void 0?n[a]="":i[a]=c;let s={};Object.keys(i).length>0&&(s.$set=i),Object.keys(n).length>0&&(s.$unset=n);try{await k.updateOne({_id:r._id},s);let a=Object.fromEntries(Object.keys(n).map(c=>[c,void 0]));r={...r,...i,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:he(r)}}var Pe=["google","github"];async function Vt({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!Pe.includes(e))throw new Error(`Invalid provider. Supported providers are: ${Pe.join(", ")}.`);let r=await k.requireById(t.id),o=r.authMethods??{};if(!o[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(o).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(o).filter(l=>l!==e&&o[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await k.updateOne({_id:r._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var re=new b("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user","email"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Me=[];function zt(e){if(Me.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Me=e;}async function R(e){let{bucket:t,type:r,value:o,message:i}=e,n=Me.filter(a=>a.bucket===t&&a.type===r),s=i?()=>new d$1(i):void 0;for(let a of n)await Kr(a,o,s);}async function Kr(e,t,r){let o=()=>r?r():new d$1(`Rate limit exceeded for ${e.bucket}`),i=await re.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),n=Date.now(),s=Math.floor(n/e.window)*e.window,{count:a,modifier:c}=i?Qr(i,s,n):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw o();await re.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Qr(e,t,r){let o=t-e.windowMs;if(e.windowStart.getTime()===t){let i=e.windowCount,n=e.prevWindowCount,s=1-(r-t)/e.windowMs;return {count:Math.round(i+n*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===o){let i=1-(r-t)/e.windowMs;return {count:Math.round(e.windowCount*i),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function Bt({name:e,email:t,verificationUrl:r}){return `
3
+ <p>Hi${e?` ${e}`:""},</p>
4
+ <p>Please verify your email address ${t} by clicking the link below:</p>
5
+ <p><a href="${r}">${r}</a></p>
6
+ <p>If you did not request this, please ignore this email.</p>
7
+ `}async function Zr(e){let t=await m.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");if(!await k.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}}))throw new Error("User not found");let o=t.email;if(!o)throw new Error("Email not found in token");let i=await k.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},"emails.address":o,"emails.verified":{$ne:true}},{$set:{"emails.$.verified":true}},{returnDocument:"after"});if(!i)throw await k.findOne({_id:t.userId,"emails.address":o})?new Error("Email is already verified"):new Error("Email address not found for this user");return await m.deleteOne({_id:t._id}),{userDoc:i,email:o}}async function qt(e){let t=a$2("_system.site.url"),r=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||t||"/";try{let o=z.string().parse(e.query.token),{userDoc:i}=await Zr(o);y().onAfterEmailVerification?.({provider:"email",user:i,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await g(i._id);return h$1(e.res,s),{status:301,redirect:`${r}?status=verified`}}catch(o){let i=o instanceof Error?o.message:"An unexpected error occurred";return o instanceof Error&&(y().onEmailVerificationError?.({provider:"email",error:o,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",o)),{status:301,redirect:`${r}?status=error&message=${encodeURIComponent(i)}`}}}async function Ue({userId:e,email:t,baseUrl:r=a$2("_system.site.url")}){if(w().provider){let o=w().provider,i=randomBytes(32).toString("hex"),n=new Date(Date.now()+a$1.hours(24));await m.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:n});let s$1=`${r}/api/_internal/auth/verify-email?token=${i}`,c=(w()?.verification?.template||Bt)({name:"",email:t,verificationUrl:s$1}),l=s(c);await o?.sendEmail({to:t,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:l,html:c});}}var Ie={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function Jt(e,{connectionInfo:t}){let r=M(e.email),o=await k.findOne({"emails.address":r,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!o)return Ie;let i=o.emails?.find(n=>n.address.toLowerCase()===r);if(!i||i.verified)return Ie;if(!w().provider)throw new Error("Email provider is not configured");return await R({bucket:"verification",type:"user",value:o._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await Ue({userId:o._id,email:r,baseUrl:t?.baseUrl}),Ie}async function Wt(e,{user:t,session:r,connectionInfo:o}){let i=y();try{let n=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=n,d=M(n.email),p=ge(n.password),b=o?.ip;if(b&&await R({bucket:"signupAttempt",type:"ip",value:b}),await Ot(d))throw new Error("Please use a permanent email address");let S=await k.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(S){let O=S.emails?.find(Ae=>Ae.address.toLowerCase()===d);throw S.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${O?.address}`)}b&&await R({bucket:"signup",type:"ip",value:b});let E=fe({firstName:s,lastName:a,avatarUrl:c,handle:l});await i.validateSignup?.({email:d,password:p,...E});let A;if(E.handle)A=await j(E.handle,d);else if(i.generateHandle){let O=await i.generateHandle({email:d,firstName:E.firstName,lastName:E.lastName});A=await j(O,d,{throwOnConflict:!1});}else A=await j(void 0,d);let Re=await Jr.hash(p,10),T=await k.insertOne({handle:A,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:Re}},...E.firstName!==void 0&&{firstName:E.firstName},...E.lastName!==void 0&&{lastName:E.lastName},...E.avatarUrl!==void 0&&{avatarUrl:E.avatarUrl}}),ae=await k.findOne({_id:T.insertedId},{readPreference:"primary"});if(!ae)throw new Error("User not found");return await Ue({userId:T?.insertedId,email:d,baseUrl:o?.baseUrl}),i.onAfterSignup?.({provider:"email",user:ae,session:r,connectionInfo:o}),i.signup?.onSuccess?.(ae),T.insertedId}catch(n){throw n instanceof Error&&(i.onSignupError?.({provider:"email",error:n,session:r,connectionInfo:o}),i.signup?.onError?.(n)),n}}function io(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function no({email:e,resetUrl:t}){return `
8
+ <p>Hi,</p>
9
+ <p>We received a request to reset your password for ${e}.</p>
10
+ <p>Click the link below to reset your password:</p>
11
+ <p><a href="${t}">${t}</a></p>
12
+ <p>This link will expire in 1 hour.</p>
13
+ <p>If you did not request this password reset, please ignore this email.</p>
14
+ `}var Te={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Kt(e,{connectionInfo:t}){let r=M(e.email),o=t?.ip;o&&await R({bucket:"passwordReset",type:"ip",value:o}),await R({bucket:"passwordReset",type:"email",value:r});let i=await k.findOne({"emails.address":r,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!i||!i.authMethods?.password)return Te;let n$1=w().provider;if(!n$1)throw new Error("Email provider is not configured");let s$1=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await n.insertOne({userId:i._id,email:r,token:s$1,createdAt:c,expiresAt:l});let d=a$2("_system.site.url")||t?.baseUrl,b=`${io(d,w().passwordReset?.redirectUrl)}?token=${s$1}`,E=(w()?.passwordReset?.template||no)({email:r,resetUrl:b,name:""}),A=s(E);return await n$1.sendEmail({to:r,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:A,html:E}),Te}async function Qt(e,{}){let t=z.string().parse(e.token),r=ge(e.password),o=await n.findOne({token:t});if(!o)throw new Error("Invalid or expired reset token");if(o.expiresAt<new Date)throw await n.deleteOne({token:t}),new Error("Reset token has expired");let i=await k.findOne({_id:o.userId});if(!i)throw new Error("User not found");let n$1=await Jr.hash(r,10);return await k.updateOne({_id:i._id},{$set:{"authMethods.password.hash":n$1}}),o.email&&await k.updateOne({_id:i._id,"emails.address":o.email},{$set:{"emails.$.verified":true}}),await f(i._id),await n.deleteOne({token:t}),{success:true,message:"Password has been reset successfully"}}var Yt=false;function so(e){Yt||(Yt=true,console.warn(`[modelence] auth.rateLimits.${e}: the legacy object form (e.g. { perIp15Minutes, perIpPerDay }) is deprecated and will be removed in 1.0.0. Use the array form: [{ type: 'ip', window: time.minutes(15), limit: 10 }, ...].`));}function Xt(e){return `${e.bucket}\0${e.type}\0${e.window}`}function ao(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10}]}function co(e,t){let r=[];if(e==="verification"){let i=t;return i.perUserPerMinute!==void 0&&r.push({bucket:e,type:"user",window:a$1.seconds(60),limit:i.perUserPerMinute}),i.perUserPerDay!==void 0&&r.push({bucket:e,type:"user",window:a$1.days(1),limit:i.perUserPerDay}),r}let o=t;if(o.perIp15Minutes!==void 0&&r.push({bucket:e,type:"ip",window:a$1.minutes(15),limit:o.perIp15Minutes}),o.perIpPerDay!==void 0&&r.push({bucket:e,type:"ip",window:a$1.days(1),limit:o.perIpPerDay}),e==="passwordReset"){let i=t;i.perEmailPerHour!==void 0&&r.push({bucket:e,type:"email",window:a$1.hours(1),limit:i.perEmailPerHour}),i.perEmailPerDay!==void 0&&r.push({bucket:e,type:"email",window:a$1.days(1),limit:i.perEmailPerDay});}return r}function lo(e){let t=[],r=["signup","signupAttempt","signin","verification","passwordReset"];for(let o of r){let i=e[o];if(i!==void 0)if(Array.isArray(i))for(let n of i)t.push({bucket:o,...n});else {so(o);for(let n of co(o,i))t.push(n);}}return t}function Ne(e={}){let t=ao(),r=lo(e),o=new Map;for(let s of r)o.set(Xt(s),s);let i=[],n=new Set;for(let s of t){let a=Xt(s),c=o.get(a);c!==void 0?(i.push(c),n.add(a)):i.push(s);}for(let[s,a]of o)n.has(s)||i.push(a);return i}var De=new a("_system.user",{stores:[k,l,m,n],queries:{getOwnProfile:Gt},mutations:{signupWithPassword:Wt,loginWithPassword:jt,logout:Ht,resendEmailVerification:Jt,sendResetPasswordToken:Kt,resetPassword:Qt,updateProfile:Ft,unlinkOAuthProvider:Vt},cronJobs:{updateDisposableEmailList:Lt},rateLimits:Ne(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:qt}}]});var uo={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function mo(e,t){if(t==="number"){let r=Number(e);if(isNaN(r))throw new Error(`Invalid number value for config: ${e}`);return r}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function po(e,t){let r=[];for(let[o,i]of Object.entries(e)){let n=process.env[o],s=t[i];if(n){let a=s?.type??"string";r.push({key:i,type:a,value:mo(n,a)});}}return r}function we(e,t="withoutRemoteServer"){let r=uo[t];return po(r,e)}async function Zt({configSchema:e,cronJobsMetadata:t,stores:r,roles:o}){let i=process.env.MODELENCE_CONTAINER_ID;if(!i)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=(r??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await $e("/api/connect","POST",{hostname:fo.hostname(),containerId:i,dataModels:n,configSchema:e,cronJobsMetadata:t,roles:o});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function er(){return $e("/api/configs","GET")}async function tr(){return await $e("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function $e(e,t,r){return q(e,t,r?JSON.stringify(r):void 0,r?{"Content-Type":"application/json"}:{})}async function q(e,t,r,o){let{MODELENCE_SERVICE_ENDPOINT:i,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!i)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let s=await fetch(`${i}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o},body:r});if(!s.ok){let a=await s.text();try{let c=JSON.parse(a);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${a}`)}}if(!(s.status===204||s.headers?.get("content-length")==="0"))return await s.json()}var je=false,go=a$1.seconds(10);function rr(){setInterval(async()=>{if(!je){je=true;try{await tr();}catch(e){console.error("Error syncing status",e);}try{await ho();}catch(e){console.error("Error syncing config",e);}je=false;}},go);}function He(e){c$1(e),c$1(we(d$2(),"withRemoteServer"));}async function ho(){let{configs:e}=await er();He(e);}var H=new b("_modelenceLocks",{schema:{_id:c.string(),instanceId:c.string(),acquiredAt:c.date(),resource:c.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var G={},or=a$1.seconds(10),ar=randomBytes(32).toString("base64url"),bo=a$1.seconds(30),J=new Map,Ge=e=>e instanceof MongoError&&e.code===11e3,ir=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),Eo=async({error:e,resource:t})=>{if(ir(e,"resource"))return true;if(ir(e,"_id"))return false;let r=await H.findOne({resource:t});return !!r&&r._id!==t},nr=async({resource:e,staleThresholdDate:t,instanceId:r})=>{let o=await H.upsertOne({_id:e,$or:[{instanceId:r},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:r,acquiredAt:new Date},$setOnInsert:{_id:e}});return o.upsertedCount>0||o.modifiedCount>0},cr=async({resource:e,instanceId:t,staleThresholdDate:r})=>{let o=r?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:r}}]}:{resource:e,instanceId:t};return (await H.deleteOne(o)).deletedCount>0},vo=e=>{let t=e,r=J.get(t);r&&(r.stopRequested=true,r.timer&&(clearTimeout(r.timer),r.timer=null),J.delete(t));},sr=({resource:e,lockDuration:t,instanceId:r})=>{let o=Math.floor(t/3),i=e,n=J.get(i);if(n&&!n.stopRequested&&n.heartbeatInterval===o&&n.lockDuration===t)return;n&&(n.stopRequested=true,n.timer&&(clearTimeout(n.timer),n.timer=null),J.delete(i));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:o},a=()=>{s.timer=setTimeout(()=>{F(e,{lockDuration:t,bypassCache:true,instanceId:r}).then(c=>{c||(s.stopRequested=true,i$1(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:r}));}).finally(()=>{if(s.stopRequested){J.delete(i);return}a();});},o);};J.set(i,s),a();};async function F(e,{lockDuration:t=bo,successfulLockCacheDuration:r=or,failedLockCacheDuration:o=or,heartbeat:i,bypassCache:n,instanceId:s=ar}={}){let a=Date.now();if(!n&&G[e]&&a<G[e].expiresAt)return G[e].value&&i&&sr({resource:e,lockDuration:t,instanceId:s}),G[e].value;let c=new Date(a-t);i$1(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await Co({resource:e,staleThresholdDate:c,instanceId:s});return G[e]={value:l,expiresAt:a+(l?r:o)},l?(i&&sr({resource:e,lockDuration:t,instanceId:s}),i$1(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):i$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return G[e]={value:false,expiresAt:a+o},i$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var Co=async({resource:e,staleThresholdDate:t,instanceId:r})=>{try{return await nr({resource:e,staleThresholdDate:t,instanceId:r})}catch(o){if(Ge(o)&&await Eo({error:o,resource:e})){if(!await cr({resource:e,staleThresholdDate:t,instanceId:r}))return false;try{return await nr({resource:e,staleThresholdDate:t,instanceId:r})}catch(n){if(Ge(n))return false;throw n}}if(Ge(o))return false;throw o}};async function oe(e,{instanceId:t=ar}={}){vo(e);try{let r=await H.deleteOne({_id:e,instanceId:t});return r.deletedCount===0?await cr({resource:e,instanceId:t}):r.deletedCount>0}catch{return false}finally{delete G[e];}}var V={},Fe=null,Ve=new b("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function dr(e,{description:t="",interval:r,timeout:o=Math.min(Math.max(r,a$1.minutes(1)),a$1.days(1)),handler:i}){if(V[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(Fe)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(r<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(o>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);V[e]={alias:e,params:{description:t,interval:r,timeout:o},handler:i,state:{isRunning:false}};}async function ur(){if(Fe)throw new Error("Cron jobs already started");let e=Object.keys(V);if(e.length>0){let t={alias:{$in:e}},r=await Ve.fetch(t),o=Date.now();r.forEach(i=>{let n=V[i.alias];n&&(n.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+n.params.interval:o);}),Object.values(V).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=o);}),Fe=setInterval(So,a$1.seconds(1));}}async function So(){let e=Date.now();await F("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(V).forEach(async r=>{let{params:o,state:i}=r;if(i.isRunning){i.startTs&&i.startTs+o.timeout<e&&(i.isRunning=false);return}i.scheduledRunTs&&i.scheduledRunTs<=e&&await Ro(r);});}async function Ro(e){let{alias:t,params:r,handler:o,state:i}=e;i.isRunning=true,i.startTs=Date.now(),await Ve.updateOne({alias:t},{$set:{lastStartDate:new Date(i.startTs)}});let n=l$1("cron",`cron:${t}`);try{await o(),lr(i,r),n.end("success");}catch(s){lr(i,r);let a=s instanceof Error?s:new Error(String(s));m$1(a),n.end("error"),console.error(`Error in cron job '${t}':`,s);}}function lr(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function mr(){return Object.values(V).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var pr=new a("_system.cron",{stores:[Ve]});function fr(e){let t=[...new Set(e)],r=new Map;for(let n of t){let s=n.getChainRoot();r.set(s,s.getChainTail());}let o=[...new Set(r.values())],i=new Map;for(let[n,s]of r){let a=s.getName(),c=i.get(a);if(c!==void 0&&c!==n)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);i.set(a,n);}return {storesToInit:t,effectiveStores:o}}var ze=new a("_system.lock",{stores:[H]});var ie=new b("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function Be(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await F("migrations")){j$2("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let r=e.map(({version:s})=>s),o=await ie.fetch({version:{$in:r}}),i=new Set(o.map(({version:s})=>s)),n=e.filter(({version:s})=>!i.has(s));if(n.length===0)return;j$2(`Running migrations (${n.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of n){j$2(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),p=15*1024*1024,b=d.length>p?d.slice(0,p)+`
15
+ [Output truncated - exceeded size limit]`:d;await ie.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:b,appliedAt:new Date}}),j$2(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await ie.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),j$2(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await oe("migrations");}}}function gr(e){setTimeout(()=>{Be(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var hr=new a("_system.migration",{stores:[ie]});var wr=new a("_system.rateLimit",{stores:[re]});async function yr({filePath:e,contentType:t,visibility:r}){return await q("/api/files/upload","POST",JSON.stringify({filePath:e,contentType:t,visibility:r}),{"Content-Type":"application/json"})}async function br(e){await q("/api/files/delete","POST",JSON.stringify({filePath:e}),{"Content-Type":"application/json"});}async function Er(e){return await q("/api/files/download","POST",JSON.stringify({filePath:e}),{"Content-Type":"application/json"})}async function vr(e){return await q("/api/files/url","POST",JSON.stringify({filePath:e}),{"Content-Type":"application/json"})}var Cr=new a("_system.files",{queries:{async downloadFile({filePath:e}){return Er(e)},async getFileUrl({filePath:e}){return vr(e)}},mutations:{async getUploadUrl({filePath:e,contentType:t,visibility:r}){return yr({filePath:e,contentType:t,visibility:r})},async deleteFile({filePath:e}){return br(e)}}});var ne="./.modelence/build/client".replace(/\\/g,"/"),_o="./.modelence/build/ssr".replace(/\\/g,"/"),Rr="/index.tsx",kr=/<div id="root">\s*<\/div>/,Po="</head>",Je=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await $o(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config)),this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:r}=await import('./transport-ZSBKZIXH.js');r(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,r=[U.static(ne,t)];return this.config?.publicDir&&r.push(U.static(this.config.publicDir,t)),r}async handler(t,r){if(this.ssrEnabled&&Mo(t)){try{await this.handleSsr(t,r);}catch(o){if(this.isDev()&&this.viteServer&&o instanceof Error&&this.viteServer.ssrFixStacktrace(o),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:o}),r.headersSent){r.end();return}this.serveStaticShell(r);}return}if(this.ssrEnabled){r.status(404).end();return}this.serveStaticShell(r);}async handleSsr(t,r){let o=await this.getTemplate(t.originalUrl),i=await this.captureSsrSnapshot();if(!i)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:n},{getCallContext:s},a]=await Promise.all([import('./render-DLVPZOA6.js'),import('./server-GALICT5J.js'),import('./collectCss-4V7I3QV3.js')]),c=await s(t,r),l=this.collectCssAssets(a);To(r,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:p,getQueryState:b}=await n({callContext:c,loadingElement:i.loadingElement,routesElement:i.routesElement,router:i.router,location:t.originalUrl});if(!kr.test(o))throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let[S,E]=Io(o),A=Uo(S,a.renderStylesheetLinks(l));r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.status(200),r.write(A),r.write(`<script id="__MODELENCE_STATE__" type="application/json">${Ar(d)}</script>`),r.write('<div id="root">'),await p(r),r.write("</div>"),r.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${Ar(b())}</script>`),r.end(E);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,Rr):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ne)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let r=W.resolve(process.cwd(),"src/client/index.html"),o=qe.readFileSync(r,"utf-8");return this.viteServer&&(o=await this.viteServer.transformIndexHtml(t,o)),o}if(!this.prodTemplateCache){let r=W.resolve(process.cwd(),ne,"index.html");this.prodTemplateCache=qe.readFileSync(r,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-KKWGQKMM.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(Rr),t()}return this.prodEntryLoaded||(await import(W.resolve(process.cwd(),_o,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(r){console.error("Error serving index.html:",r),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:ne});}isDev(){return process.env.NODE_ENV!=="production"}};function Mo(e){if(e.method!=="GET"&&e.method!=="HEAD"||!(e.get("accept")??"").includes("text/html"))return false;let r=(e.path??e.url??"").split("?")[0];if(r.startsWith("/api/"))return false;let o=r.split("/").pop()??"",i=o.lastIndexOf(".");if(i>0){let n=o.slice(i).toLowerCase();if(n!==".html"&&n!==".htm")return false}return true}function Ar(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Io(e){let t=e.match(kr);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let r=e.slice(0,t.index),o=e.slice(t.index+t[0].length);return [r,o]}function Uo(e,t){if(!t)return e;let r=e.lastIndexOf(Po);return r===-1?t+e:e.slice(0,r)+t+e.slice(r)}function To(e,t){if(t.length===0)return;let r=e;if(typeof r.writeEarlyHints=="function")try{r.writeEarlyHints({link:t});}catch(o){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",o);}}async function No(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function Do(e,t){let r=mergeConfig(e,t);if(r.plugins&&Array.isArray(r.plugins)){let o=new Set;r.plugins=r.plugins.flat().filter(i=>{if(!i||typeof i!="object"||Array.isArray(i))return true;let n=i.name;return !n||o.has(n)?false:(o.add(n),true)}).reverse(),r.plugins.reverse();}return r}async function $o(e,t={}){let r=process.cwd(),o=await No(),i=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>qe.existsSync(W.join(r,a))),n=[Lo(),jo()];if(i){let a=(await import('vite-plugin-eslint')).default;n.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:r,overrideConfigFile:W.resolve(r,i)}));}let s=defineConfig({plugins:n,build:{outDir:ne,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":W.resolve(r,"src").replace(/\\/g,"/")}}});return Do(s,o)}function jo(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var ye=new Je;var We=Object.freeze({});function xr(e){We=Object.freeze(Object.assign({},We,e));}function Or(){return We}var Ke=Object.freeze({});function Lr(e){Ke=Object.freeze(Object.assign({},Ke,e));}function be(){return Ke}async function Vo({modules:e=[],roles:t={},defaultRoles:r={},server:o$1=ye,migrations:i=[],email:n={},auth:s={},security:a={},websocket:c={}}){_r.config(),_r.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT;ei().then(()=>{}).catch(()=>{});let d=[De,j$1,pr,hr,wr,Z,ze,Cr],p=[...d,...e];f$1(),Bo(d),zo(e),o(t,r);let b=Yo(p);e$1(b);let S=qo(p),E=Jo(p);Xo(p),De.rateLimits=Ne(s.rateLimits);let A=Wo(p);zt(A);let{storesToInit:Re,effectiveStores:T}=fr(S);if(l){let{configs:O,environmentId:Ae,appAlias:Nr,environmentAlias:Dr,telemetry:$r}=await Zt({configSchema:b,cronJobsMetadata:mr(),stores:T,roles:t});He(O),g$1({environmentId:Ae,appAlias:Nr,environmentAlias:Dr,telemetry:$r});}else c$1(we(b));if(Nt(n),Dt(s),xr(a),Lr({...c,provider:c.provider||xt}),D()){await At();let O=[...new Set([...Re,...T])];Zo(O),await Qo(T,i);}else gr(i);l&&(await h$2(),rr()),ur().catch(console.error),o$1===ye&&(await a$3().catch(()=>null))?.ssr&&ye.enableSsr(),await Pr(o$1,{combinedModules:p,channels:E});}function zo(e){for(let t$1 of e){for(let[r,o]of Object.entries(t$1.queries))t(`${t$1.name}.${r}`,o);for(let[r,o]of Object.entries(t$1.mutations))u(`${t$1.name}.${r}`,o);}}function Bo(e){for(let t of e){for(let[r,o]of Object.entries(t.queries))v(`${t.name}.${r}`,o);for(let[r,o]of Object.entries(t.mutations))w$1(`${t.name}.${r}`,o);}}function qo(e){return e.flatMap(t=>t.stores)}function Jo(e){return e.flatMap(t=>t.channels)}function Wo(e){return e.flatMap(t=>t.rateLimits)}function Ko(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var Qe="migrations";async function Qo(e,t){if(!await F(Qe,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let o,i;try{o=e.filter(a=>a.getIndexCreationMode()==="blocking"),i=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of o)await Ye(a,"full");for(let a of i)await Ye(a,"drop-only");}catch(a){throw await oe(Qe),a}let n=(async()=>{for(let a of i)await Ye(a,"create-only");})(),s=Be(t,{lockMode:"skip"});Promise.allSettled([n,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await oe(Qe);});}async function Ye(e,t="full"){let r=e.getName();try{await e.createIndexes(t);}catch(o){Ko(r,o);}}function Yo(e){let t={};for(let r of e)for(let[o,i]of Object.entries(r.configSchema)){let n=`${r.name}.${o}`;if(n in t)throw new Error(`Duplicate config schema key: ${n} (${r.name})`);t[n]=i;}return t}function Xo(e){for(let t of e)for(let[r,o]of Object.entries(t.cronJobs))dr(`${t.name}.${r}`,o);}function Zo(e){let t=me();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let r of e)r.init(t);}async function ei(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",r=process.env.MODELENCE_ENVIRONMENT_ID,o=await ti(),i=await import('./package-VG7P4LRW.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:o.name,version:i.default.version,localHostname:fo.hostname(),environmentId:r})});}}async function ti(){try{let e=W.join(process.cwd(),"package.json"),t=await Ho.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function Mr(e){await m.deleteMany({userId:e}),await n.deleteMany({userId:e});}async function oi(e){await Mr(e),await k.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function ii(e){await Mr(e),await k.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Xe=class{constructor(t,r){this.category=t,this.canAccessChannel=r||null;}broadcast(t,r){let o=be().provider;if(!o){k$1("Websockets provider should be added to startApp",{});return}o.broadcast({category:this.category,id:t,data:r});}};function ni(e){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(e)}function h(e,t,r){let o=y(),i=e.status(t);if(o.errorComponent)try{let n=o.errorComponent({error:r,statusCode:t});if(n)return i.send(n)}catch(n){console.error("Unhandled error in authConfig.errorComponent:",n);}return i.json({error:r})}async function Ze(e,t){let{authToken:r}=await g(t);h$1(e,r),e.status(302),e.redirect("/");}async function ai(e,t,r,o,i){let n=y();try{if(r.status==="disabled"||r.status==="deleted"){h(e,400,"User account is not active.");return}let s={};r.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),r.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),r.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=r;Object.keys(s).length>0&&(await k.updateOne({_id:r._id},{$set:s}),a={...r,...s}),await Ze(e,r._id),n.onAfterLogin?.({provider:t.providerName,user:a,session:o,connectionInfo:i}),n.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(n.login?.onError?.(s),n.onLoginError?.({provider:t.providerName,error:s,session:o,connectionInfo:i})),s}}async function ci(e,t,r,o,i){let n=y();if((n.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(r.status==="disabled"||r.status==="deleted"){h(e,400,"User account is not active.");return}if(!r.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){h(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...r.firstName===void 0&&t.firstName&&{firstName:t.firstName},...r.lastName===void 0&&t.lastName&&{lastName:t.lastName},...r.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await k.updateOne({_id:r._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){h(e,400,"User with this email already exists. Please log in instead.");return}await Ze(e,r._id);let p={...r,...c,authMethods:{...r.authMethods,[t.providerName]:{id:t.id}}};n.onAfterLogin?.({provider:t.providerName,user:p,session:o,connectionInfo:i}),n.login?.onSuccess?.(p);return}catch(c){throw c instanceof Error&&(n.login?.onError?.(c),n.onLoginError?.({provider:t.providerName,error:c,session:o,connectionInfo:i})),c}}h(e,400,"User with this email already exists. Please log in instead.");}async function li(e,t,r,o){let i=y();try{let n;if(i.generateHandle){let l=await i.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});n=await j(l,t.email,{throwOnConflict:!1});}else n=await j(void 0,t.email);let s={handle:n,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await k.insertOne(s);await Ze(e,a.insertedId);let c=await k.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(i.onAfterSignup?.({provider:t.providerName,user:c,session:r,connectionInfo:o}),i.signup?.onSuccess?.(c));}catch(n){throw n instanceof Error&&(i.onSignupError?.({provider:t.providerName,error:n,session:r,connectionInfo:o}),i.signup?.onError?.(n)),n}}function Q(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Ee(e,t,r){let o=await k.findOne({[`authMethods.${r.providerName}.id`]:r.id}),{session:i,connectionInfo:n}=await se(e,t);if(o)return ai(t,r,o,i,n);if(!r.email){h(t,400,`Email address is required for ${r.providerName} authentication.`);return}let s;try{s=await k.findOne({"emails.address":r.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=y();c.onSignupError?.({provider:r.providerName,error:a,session:i,connectionInfo:n}),c.signup?.onError?.(a);}throw a}return s?ci(t,r,s,i,n):li(t,r,i,n)}function C(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function K(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function ve(e,t,r){let o=e.query.state,i=e.cookies[r],[n,s]=(i||"").split(":");return !o||!i||o!==n?(h(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(r),s||"login")}async function Ce(e,t,r){let o=y(),{session:i,connectionInfo:n}=await se(e,t);if(!i?.userId){C(t),h(t,401,"You must be signed in to link a provider.");return}let s=i.userId;try{let a=`authMethods.${r.providerName}.id`;if((await k.updateOne({_id:s,status:{$nin:["deleted","disabled"]},$or:[{[a]:{$exists:!1}},{[a]:r.id}]},{$set:{[a]:r.id}})).matchedCount===0){let d=await k.findOne({_id:s});if(!d||d.status==="deleted"||d.status==="disabled"){K(()=>o.onOAuthLinkError?.({provider:r.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:n})),C(t),h(t,400,"User account is not active.");return}let p=d?.authMethods?.[r.providerName]?.id;if(p&&p!==r.id){K(()=>o.onOAuthLinkError?.({provider:r.providerName,error:new Error(`User already has a different ${r.providerName} account linked`),session:i,connectionInfo:n})),C(t),h(t,400,`You have already linked a different ${r.providerName} account.`);return}K(()=>o.onOAuthLinkError?.({provider:r.providerName,error:new Error(`Unexpected OAuth linking state for ${r.providerName}`),session:i,connectionInfo:n})),C(t),h(t,400,`Unable to link ${r.providerName} account.`);return}let l=await k.findOne({_id:s},{readPreference:"primary"});l&&K(()=>o.onAfterOAuthLink?.({provider:r.providerName,user:l,session:i,connectionInfo:n})),C(t),t.status(302).redirect("/");}catch(a){if(a instanceof MongoServerError&&a.code===11e3){K(()=>o.onOAuthLinkError?.({provider:r.providerName,error:a,session:i,connectionInfo:n})),C(t),h(t,400,`This ${r.providerName} account is already linked to a different user.`);return}if(a instanceof Error&&K(()=>o.onOAuthLinkError?.({provider:r.providerName,error:a,session:i,connectionInfo:n})),C(t),!t.headersSent)throw a}}function Se(e){return !e||typeof e!="string"?null:e}async function mi(e,t,r,o){let i=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:r,redirect_uri:o,grant_type:"authorization_code"})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function pi(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function fi(e,t){let r=Se(e.query.code);if(!r){h(t,400,"Missing authorization code");return}let o=ve(e,t,"authStateGoogle");if(!o)return;let i=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret")),s=Q("google");try{let a=await mi(r,i,n,s),c=await pi(a.access_token),l={id:c.id,email:c.email,emailVerified:c.verified_email,providerName:"google",firstName:c.given_name||void 0,lastName:c.family_name||void 0,avatarUrl:c.picture||void 0};o==="link"?await Ce(e,t,l):await Ee(e,t,l);}catch(a){console.error("Google OAuth error:",a),o==="link"&&C(t),h(t,500,"Authentication failed");}}function gi(){let e=Router(),t=(r,o,i)=>{let n=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!n||!s||!a){h(o,503,"Google authentication is not configured");return}i();};return e.get("/api/_internal/auth/google",t,(r,o)=>{let i=String(a$2("_system.user.auth.google.clientId")),n=Q("google"),s=randomBytes(32).toString("hex"),a=r.query.mode==="link"?"link":"login";o.cookie("authStateGoogle",`${s}:${a}`,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let c=new URL("https://accounts.google.com/o/oauth2/v2/auth");c.searchParams.append("client_id",i),c.searchParams.append("redirect_uri",n),c.searchParams.append("response_type","code"),c.searchParams.append("scope","profile email"),c.searchParams.append("access_type","online"),c.searchParams.append("state",s),o.redirect(c.toString());}),e.get("/api/_internal/auth/google/callback",t,fi),e}var Ir=gi;async function yi(e,t,r,o){let i=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:r,code:e,redirect_uri:o})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function bi(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function Ei(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function vi(e,t){return e.email?e.email:(await Ei(t)).find(o=>o.primary&&o.verified)?.email??null}async function Ci(e,t){let r=Se(e.query.code);if(!r){h(t,400,"Missing authorization code");return}let o=ve(e,t,"authStateGithub");if(!o)return;let i=String(a$2("_system.user.auth.github.clientId")),n=String(a$2("_system.user.auth.github.clientSecret")),s=Q("github");try{let a=await yi(r,i,n,s),c=await bi(a.access_token),l=await vi(c,a.access_token);if(!l){o==="link"&&C(t),h(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let d=c.name?c.name.trim().split(/\s+/):[],p=d[0]||void 0,b=d.length>1?d.slice(1).join(" "):void 0,S={id:String(c.id),email:l,emailVerified:!0,providerName:"github",firstName:p,lastName:b,avatarUrl:c.avatar_url||void 0};o==="link"?await Ce(e,t,S):await Ee(e,t,S);}catch(a){console.error("GitHub OAuth error:",a),o==="link"&&C(t),h(t,500,"Authentication failed");}}function Si(){let e=Router(),t=(r,o,i)=>{let n=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!n||!s||!a){h(o,503,"GitHub authentication is not configured");return}i();};return e.get("/api/_internal/auth/github",t,(r,o)=>{let i=String(a$2("_system.user.auth.github.clientId")),n=Q("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(p=>p.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=r.query.mode==="link"?"link":"login";o.cookie("authStateGithub",`${c}:${l}`,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://github.com/login/oauth/authorize");d.searchParams.append("client_id",i),d.searchParams.append("redirect_uri",n),d.searchParams.append("scope",a),d.searchParams.append("state",c),o.redirect(d.toString());}),e.get("/api/_internal/auth/github/callback",t,Ci),e}var Ur=Si;function Tr(e,t,r){return async(o,i,n)=>{let s=o.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&D())try{let{session:l,user:d}=await q$1(s);a={session:l,user:d};}catch{}let c=l$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:o.query,body:o.body,params:o.params});try{let l=await r({query:o.query,body:o.body,params:o.params,headers:o.headers,cookies:o.cookies,rawBody:Buffer.isBuffer(o.body)?o.body:void 0,req:o,res:i,next:n},a);c.end(),l&&(i.status(l.status||200),l.redirect&&i.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([d,p])=>{i.setHeader(d,p);}),i.send(l.data));}catch(l){c.end("error"),l instanceof a$5?i.status(l.status).send(l.message):(console.error(`Error in route handler: ${o.path}`),console.error(l),i.status(500).send(String(l)));}}}function ki(e){let t=[];if(!e)return t.push(U.json({limit:"16mb"})),t.push(U.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let r=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(U.json(r));}if(e.urlencoded!==false){let r=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(U.urlencoded(r));}if(e.raw){let r=typeof e.raw=="object"?e.raw:{},o={limit:r.limit||"16mb",type:r.type||"*/*"};t.push(U.raw(o));}return t}function xi(e,t){for(let r of t)for(let o of r.routes){let{path:i,handlers:n,body:s}=o,a=ki(s);Object.entries(n).forEach(([c,l])=>{e[c](i,...a,Tr(c,i,l));});}}async function Pr(e,{combinedModules:t,channels:r}){let o=U();o.use(Ri()),o.use(_i()),xi(o,t),o.use(U.json({limit:"16mb"})),o.use(U.urlencoded({extended:true,limit:"16mb"})),o.use(Ir()),o.use(Ur()),o.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await se(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}c.cookie("oauthLinkToken",l.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),c.json({ok:true});}),o.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await se(a,c);try{let p=a$4(await x(l,a.body.args,d));c.json({data:p,typeMap:b$1(p)});}catch(p){Oi(c,l,p);}});let i=Ai.createServer(o);await e.init({httpServer:i}),e.middlewares&&o.use(e.middlewares()),o.all("*",(a,c,l)=>{Promise.resolve(e.handler(a,c)).catch(l);}),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=be()?.provider;n&&n.init({httpServer:i,channels:r});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;i.listen(s,()=>{j$2("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
16
+ Application started on ${a}
17
+ `);});}async function se(e,t=null){let r=(e.path??e.url??"").split("?")[0],o=r.startsWith("/api/_internal/auth/")&&r.endsWith("/callback"),i=e.body??{},n=I.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(o?e.cookies.oauthLinkToken:null)||i.authToken),s=I.object({screenWidth:I.number(),screenHeight:I.number(),windowWidth:I.number(),windowHeight:I.number(),pixelRatio:I.number(),orientation:I.string().nullable()}).nullish().parse(i.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:Pi(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:e.protocol+"://"+e.get("host")};if(!!D()){let{session:l,user:d,roles:p}=await q$1(n);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:p,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:p(),req:e,res:t}}function Oi(e,t,r){if(r instanceof a$5){r.status>=500&&r.status<600&&console.error(`Error calling ${t}:`,r),e.status(r.status).send(r.message);return}if(r instanceof Error&&r?.constructor?.name==="ZodError"&&"errors"in r){let o="";try{o=Li(r);}catch(i){console.error(`Error parsing Zod error in ${t}:`,i),o="Validation failed";}e.status(400).send(o);return}console.error(`Error calling ${t}:`,r),e.status(500).send(r instanceof Error?r.message:String(r));}function Li(e){let t=e.flatten(),r=Object.entries(t.fieldErrors).map(([n,s])=>`${n}: ${(s??[]).join(", ")}`),o=t.formErrors;return [...r,...o].filter(Boolean).join("; ")}function _i(){let{frameAncestors:e}=Or(),t=e&&e.length>0,r=t?["'self'",...e].join(" "):"'self'";return (o,i,n)=>{i.setHeader("Content-Security-Policy",`frame-ancestors ${r}`),t||i.setHeader("X-Frame-Options","SAMEORIGIN"),n();}}function Pi(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let r=e.ip||e.socket?.remoteAddress;if(r)return r.startsWith("::ffff:")?r.substring(7):r}
18
+ export{R as a,yr as b,br as c,Er as d,vr as e,Pr as f,se as g,Vo as h,oi as i,ii as j,Xe as k,ni as l};//# sourceMappingURL=chunk-TJ626QWY.js.map
19
+ //# sourceMappingURL=chunk-TJ626QWY.js.map