modelence 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/modelence.js +2 -2
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-KUL6YKKP.js → chunk-3YAV3UUU.js} +3 -3
- package/dist/{chunk-KUL6YKKP.js.map → chunk-3YAV3UUU.js.map} +1 -1
- package/dist/{package-IIELPLTY.js → package-3YQBVIVQ.js} +2 -2
- package/dist/{package-IIELPLTY.js.map → package-3YQBVIVQ.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {s}from'../chunk-
|
|
2
|
+
import {s}from'../chunk-3YAV3UUU.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import M,{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 R(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 U(){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 V(e){return String(e).replace(/"/g,'\\"')}async function z(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 k(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await z(o),await U()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await R(e.token,e.host),s={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},i=Object.entries(s).map(([a,n])=>`${a}="${V(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
|
|
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 W(){if(!h)throw new Error("Environment variables not loaded");return h}function D(){if(!N)throw new Error("Configuration not loaded");return N}function O(e){return `${W().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=D();return join(e,o).replace(/\\/g,"/")}function P(){return D().postBuildCommand}function E(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){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()}).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 Z(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}await ee();}async function ee(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:M.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function oe(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[p()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=E();await T.rm(e,{recursive:!0,force:!0}),await oe(),await Z(),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 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 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 $(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await v(),await le(r);let{token:i}=await j(s),{bundleName:a}=await pe(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 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,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 pe(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),S=await fetch(a,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!S.ok)throw new Error(`Failed to upload bundle: ${S.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 B(){console.log("Starting Modelence dev server...");let e=p(),o=M.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function _(){console.log("Starting Modelence production server...");let e=p(),o=M.basename(e,M.extname(e)),t=E(`${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 k(e);});u.command("build").description("Build the application").action(async()=>{await m(),await v();});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 m(),await $(e);});u.command("dev").description("Start development server").action(async()=>{await m(),B();});u.command("start").description("Start production server").action(async()=>{await m(),_();});u.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/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","package_default","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";4gBAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,EAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,MAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,CAAA,CAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CACD,CAAA,SAAA,EAAYP,CAAkB,CAAA,oDAAA,CAAA,CAC7BU,CAAAA,EAAW,CACVH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,CAAAA,CAAO,aAAY,GAAM,GAAG,EACtC,CACF,EACF,CAAC,CACH,CAEA,SAASC,C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AA,CACrD,OAAO,mBAAA,CAAqB,gBAAgB,EAC5C,MAAA,CAAO,MAAOtF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,EAAQ,CACd,MAAM4B,CAAAA,CAAOnD,CAAO,EACtB,CAAC,CAAA,CAEHsF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM/D,CAAAA,EAAQ,CACdsD,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\nimport pkg from '../../package.json';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
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","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","package_default","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";mhBAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CA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CAAQ,QAAQ,CAAA,CAChB,YAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAA,CAAmB,mBAAmB,EACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,oBAAqB,gBAAgB,CAAA,CAC5C,OAAO,MAAOzF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,EAAQ,CACd,MAAM4B,EAAOnD,CAAO,EACtB,CAAC,CAAA,CAEHyF,CAAAA,CACG,QAAQ,KAAK,CAAA,CACb,YAAY,0BAA0B,CAAA,CACtC,OAAO,SAAY,CAClB,MAAMlE,CAAAA,EAAQ,CACdsD,IACF,CAAC,CAAA,CAEHY,CAAAA,CACG,QAAQ,OAAO,CAAA,CACf,YAAY,yBAAyB,CAAA,CACrC,OAAO,SAAY,CAClB,MAAMlE,CAAAA,EAAQ,CACdyD,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\nimport pkg from '../../package.json';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","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,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",o="0.
|
|
2
|
-
export{s as a,i as b,o as c,r as d,n as e,p as f,c as g,d as h,l as i,m as j,a as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var s="module",i="modelence",o="0.8.0",r="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="https://modelence.com",h={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",jest:"^30.2.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},v={react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:o,description:r,main:n,types:p,exports:c,files:d,bin:l,scripts:m,repository:a,author:y,license:u,bugs:j,homepage:g,devDependencies:h,dependencies:x,peerDependencies:v};
|
|
2
|
+
export{s as a,i as b,o as c,r as d,n as e,p as f,c as g,d as h,l as i,m as j,a as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-3YAV3UUU.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-3YAV3UUU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,QACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,eACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,eAAA,CAClB,IAAA,CAAQ,6CAAA,CACR,YAAA,CA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,SAAA,CACzB,GAAA,CAAO,UACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,CAAA,CAlGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,EACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAaA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,QACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,eACP,MAAA,CA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IAAA,CAAQ,SACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,IAAA,CAAQ,QAAA,CACR,qBAAsB,QAAA,CACtB,OAAA,CAAW,SAAA,CACX,uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,UACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,CAAA,CAlGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,EACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAaA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-3YAV3UUU.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.8.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"jest\": \"^30.2.0\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=package-
|
|
1
|
+
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-3YAV3UUU.js';//# sourceMappingURL=package-3YQBVIVQ.js.map
|
|
2
|
+
//# sourceMappingURL=package-3YQBVIVQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-3YQBVIVQ.js"}
|
package/dist/server.js
CHANGED
|
@@ -14,6 +14,6 @@ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UES
|
|
|
14
14
|
`}var ye={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function lt(t,{connectionInfo:e}){let o=L(t.email),n=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ye;let r=b().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=Date.now(),a$1=new Date(s),c=new Date(s+a.hours(1));await x.insertOne({userId:n._id,token:i,createdAt:a$1,expiresAt:c});let d=process.env.MODELENCE_SITE_URL||e?.baseUrl,u=`${Co(d,b().passwordReset?.redirectUrl)}?token=${i}`,C=(b()?.passwordReset?.template||xo)({email:o,resetUrl:u,name:""}),F=te(C);return await r.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:F,html:C}),ye}async function dt(t,{}){let e=z$1.string().parse(t.token),o=ne(t.password),n=await x.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await x.deleteOne({token:e}),new Error("Reset token has expired");let r=await p.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await fo.hash(o,10);return await p.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await x.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var ut=new S("_system.user",{stores:[p,W,D,x],queries:{getOwnProfile:st},mutations:{signupWithPassword:ct,loginWithPassword:rt,logout:it,sendResetPasswordToken:lt,resetPassword:dt},cronJobs:{updateDisposableEmailList:Qe},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:et}}]});async function mt({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await we("/api/connect","POST",{hostname:To.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function pt(){return await we("/api/configs","GET")}async function ft(){return await we("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function we(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var be=false,vo=a.seconds(10);function ht(){setInterval(async()=>{if(!be){be=true;try{await ft();}catch(t){console.error("Error syncing status",t);}try{await Do();}catch(t){console.error("Error syncing config",t);}be=false;}},vo);}async function Do(){let{configs:t}=await pt();c(t);}var H=new w("_modelenceLocks",{schema:{resource:l.string(),instanceId:l.string(),acquiredAt:l.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var N={},gt=a.seconds(10),yt=randomBytes(32).toString("base64url"),ko=a.seconds(30);async function re(t,{lockDuration:e=ko,successfulLockCacheDuration:o=gt,failedLockCacheDuration:n=gt,instanceId:r=yt}={}){let i=Date.now();if(N[t]&&i<N[t].expiresAt)return N[t].value;let s=new Date(i-e);h(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:r});try{let a=await H.upsertOne({$or:[{resource:t,instanceId:r},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:r,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return N[t]={value:c,expiresAt:i+(c?o:n)},c?h(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:r}):h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),c}catch{return N[t]={value:false,expiresAt:i+n},h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),false}}async function wt(t,{instanceId:e=yt}={}){let o=await H.deleteOne({resource:t,instanceId:e});return delete N[t],o.deletedCount>0}var Oo=a.minutes(1),P={},Se=null,Ee=new w("_modelenceCronJobs",{schema:{alias:l.string(),lastStartDate:l.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function St(t,{description:e="",interval:o,timeout:n=Oo,handler:r}){if(P[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(Se)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);P[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Et(){if(Se)throw new Error("Cron jobs already started");let t=Object.keys(P);if(t.length>0){let e={alias:{$in:t}},o=await Ee.fetch(e),n=Date.now();o.forEach(r=>{let i=P[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:n);}),Object.values(P).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=n);}),Se=setInterval(Ro,a.seconds(1));}}async function Ro(){let t=Date.now();await re("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(P).forEach(async o=>{let{params:n,state:r}=o;if(r.isRunning){r.startTs&&r.startTs+n.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await Mo(o);});}async function Mo(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now(),await Ee.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});let i=k$1("cron",`cron:${e}`);try{await n(),bt(r,o),i.end("success");}catch(s){bt(r,o);let a=s instanceof Error?s:new Error(String(s));l$1(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function bt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Ct(){return Object.values(P).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var xt=new S("_system.cron",{stores:[Ee]});var Ce={};function xe(t,e){return A(),_t(t),ie("query",t,e)}function Tt(t,e){return A(),_t(t),ie("mutation",t,e)}function vt(t,e){return A(),kt(t),ie("query",t,e)}function Dt(t,e){return A(),kt(t),ie("mutation",t,e)}function _t(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function kt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function ie(t,e,o){if(A(),Ce[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];Ce[e]={type:t,name:e,handler:n,permissions:r};}async function Ot(t,e,o){A();let n=Ce[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=k$1("method",`method:${t}`,{type:r,args:e}),a;try{Ge(o.roles,n.permissions),a=await i(e,o);}catch(c){throw s.end("error"),c}return s.end(),a}var Te=new S("_system.lock",{stores:[H]});var V=new w("_modelenceMigrations",{schema:{version:l.number(),status:l.enum(["completed","failed"]),description:l.string().optional(),output:l.string().optional(),appliedAt:l.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function Ao(t){if(t.length===0)return;if(!await re("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),n=await V.fetch({version:{$in:o}}),r=new Set(n.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!r.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let f=(await c()||"").toString().trim(),u=15*1024*1024,E=f.length>u?f.slice(0,u)+`
|
|
15
15
|
[Output truncated - exceeded size limit]`:f;await V.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:E,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(d){d instanceof Error&&(await V.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:d.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${d.message}`,{source:"migrations"}));}}await wt("migrations");}}function Rt(t){setTimeout(()=>{Ao(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Mt=new S("_system.migration",{stores:[V]});var At=new S("_system.rateLimit",{stores:[G]});var It=new S("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var De=class{async init(){this.config=await Fo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[O.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(O.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function No(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function zo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Fo(){let t=process.cwd(),e=await No(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Lo.existsSync(ve.join(t,i))),n=[$o(),qo()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:ve.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":ve.resolve(t,"src").replace(/\\/g,"/")}}});return zo(r,e)}function qo(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t}}}var jt=new De;async function Ut(t,e){let{authToken:o}=await pe(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function z(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function se(t,e,o){let n=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await _e(t);try{if(n){await Ut(e,n._id),y().onAfterLogin?.({user:n,session:r,connectionInfo:i}),y().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(y().login?.onError?.(s),y().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Ut(e,a.insertedId);let c=await p.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(y().onAfterSignup?.({user:c,session:r,connectionInfo:i}),y().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(y().onSignupError?.({error:s,session:r,connectionInfo:i}),y().signup?.onError?.(s)),s}}function ae(t){return !t||typeof t!="string"?null:t}async function Wo(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Jo(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Go(t,e){let o=ae(t.query.code),n=t.query.state,r=t.cookies.authStateGoogle;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!n||!r||n!==r){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGoogle");let i=String(a$1("_system.user.auth.google.clientId")),s=String(a$1("_system.user.auth.google.clientSecret")),a=z("google");try{let c=await Wo(o,i,s,a),d=await Jo(c.access_token),f={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google"};await se(t,e,f);}catch(c){console.error("Google OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function Ho(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=z("google"),s=randomBytes(32).toString("hex");n.cookie("authStateGoogle",s,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let a$2=new URL("https://accounts.google.com/o/oauth2/v2/auth");a$2.searchParams.append("client_id",r),a$2.searchParams.append("redirect_uri",i),a$2.searchParams.append("response_type","code"),a$2.searchParams.append("scope","profile email"),a$2.searchParams.append("access_type","online"),a$2.searchParams.append("state",s),n.redirect(a$2.toString());}),t.get("/api/_internal/auth/google/callback",e,Go),t}var $t=Ho;async function Qo(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function Yo(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Xo(t,e){let o=ae(t.query.code),n=t.query.state,r=t.cookies.authStateGithub;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!n||!r||n!==r){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGithub");let i=String(a$1("_system.user.auth.github.clientId")),s=String(a$1("_system.user.auth.github.clientSecret")),a=z("github");try{let c=await Qo(o,i,s,a),d=await Yo(c.access_token),f=d.email||"";if(!f){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let u={id:String(d.id),email:f,emailVerified:!0,providerName:"github"};await se(t,e,u);}catch(c){console.error("GitHub OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function en(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=z("github"),s=a$1("_system.user.auth.github.scopes"),a$2=s?String(s).split(",").map(f=>f.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex");n.cookie("authStateGithub",c,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let d=new URL("https://github.com/login/oauth/authorize");d.searchParams.append("client_id",r),d.searchParams.append("redirect_uri",i),d.searchParams.append("scope",a$2),d.searchParams.append("state",c),n.redirect(d.toString());}),t.get("/api/_internal/auth/github/callback",e,Xo),t}var Lt=en;function Nt(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&M())try{let{session:d,user:f}=await R(s);a={session:d,user:f};}catch{}let c=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let d=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,rawBody:Buffer.isBuffer(n.body)?n.body:void 0,req:n,res:r,next:i},a);c.end(),d&&(r.status(d.status||200),d.redirect&&r.redirect(d.redirect),d.headers&&Object.entries(d.headers).forEach(([f,u])=>{r.setHeader(f,u);}),r.send(d.data));}catch(d){c.end("error"),d instanceof a$3?r.status(d.status).send(d.message):(console.error(`Error in route handler: ${n.path}`),console.error(d),r.status(500).send(String(d)));}}}var ke=Object.freeze({});function zt(t){ke=Object.freeze(Object.assign({},ke,t));}function ce(){return ke}function nn(t){let e=[];if(!t)return e.push(O.json({limit:"16mb"})),e.push(O.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(O.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(O.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},n={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(O.raw(n));}return e}function rn(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i,body:s}=n,a=nn(s);Object.entries(i).forEach(([c,d])=>{t[c](r,...a,Nt(c,r,d));});}}async function Ft(t,{combinedModules:e,channels:o}){let n=O();n.use(tn()),rn(n,e),n.use(O.json({limit:"16mb"})),n.use(O.urlencoded({extended:true,limit:"16mb"})),n.use($t()),n.use(Lt()),n.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:d}=a.params,f=await _e(a);try{let u=await Ot(d,a.body.args,f);c.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${d}:`,u),u instanceof a$3)c.status(u.status).send(u.message);else if(u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let C=u.flatten(),F=Object.entries(C.fieldErrors).map(([q,de])=>`${q}: ${(de??[]).join(", ")}`).join("; "),le=C.formErrors.join("; "),K=[F,le].filter(Boolean).join("; ");c.status(400).send(K);}else c.status(500).send(u instanceof Error?u.message:String(u));}}),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,c)=>t.handler(a,c)),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 r=on.createServer(n),i$1=ce()?.provider;i$1&&i$1.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
|
|
16
16
|
Application started on ${a}
|
|
17
|
-
`);});}async function _e(t){let e=k.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=k.object({screenWidth:k.number(),screenHeight:k.number(),windowWidth:k.number(),windowHeight:k.number(),pixelRatio:k.number(),orientation:k.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:sn(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!M()){let{session:i,user:s,roles:a}=await R(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:X()}}function sn(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function dn({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=jt,migrations:r=[],email:i={},auth:s={},websocket:a={}}){qt.config(),qt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";Cn().then(()=>{}).catch(()=>{});let f$1=[ut,Ze,xt,Mt,At,It,Te],u=[...f$1,...t];e(),mn(f$1),un(t),We(e$1,o);let E=gn(u);d$1(E);let C=pn(u),F=fn(u);d&&yn(u);let le=hn(u);if(at(le),c$1){let{configs:q,environmentId:de,appAlias:Bt,environmentAlias:Wt,telemetry:Jt}=await mt({configSchema:E,cronJobsMetadata:d?Ct():void 0,stores:C});c(q),f({environmentId:de,appAlias:Bt,environmentAlias:Wt,telemetry:Jt});}else c(En(E));Ye(i),ot(s),zt({...a,provider:a.provider||Ve});let K=M();if(K&&(await He(),wn(C)),d&&Rt(r),K)for(let q of C)q.createIndexes();c$1&&(await g(),ht()),d&&Et().catch(console.error),await Ft(n,{combinedModules:u,channels:F});}function un(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Tt(`${e.name}.${o}`,n);}}function mn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))vt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Dt(`${e.name}.${o}`,n);}}function pn(t){return t.flatMap(e=>e.stores)}function fn(t){return t.flatMap(e=>e.channels)}function hn(t){return t.flatMap(e=>e.rateLimits)}function gn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function yn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))St(`${e.name}.${o}`,n);}function wn(t){let e=ee();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var bn={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Sn(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function En(t){let e=[];for(let[o,n]of Object.entries(bn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:Sn(r,s)});}}return e}async function Cn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await xn(),r=await import('./package-
|
|
17
|
+
`);});}async function _e(t){let e=k.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=k.object({screenWidth:k.number(),screenHeight:k.number(),windowWidth:k.number(),windowHeight:k.number(),pixelRatio:k.number(),orientation:k.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:sn(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!M()){let{session:i,user:s,roles:a}=await R(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:X()}}function sn(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function dn({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=jt,migrations:r=[],email:i={},auth:s={},websocket:a={}}){qt.config(),qt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";Cn().then(()=>{}).catch(()=>{});let f$1=[ut,Ze,xt,Mt,At,It,Te],u=[...f$1,...t];e(),mn(f$1),un(t),We(e$1,o);let E=gn(u);d$1(E);let C=pn(u),F=fn(u);d&&yn(u);let le=hn(u);if(at(le),c$1){let{configs:q,environmentId:de,appAlias:Bt,environmentAlias:Wt,telemetry:Jt}=await mt({configSchema:E,cronJobsMetadata:d?Ct():void 0,stores:C});c(q),f({environmentId:de,appAlias:Bt,environmentAlias:Wt,telemetry:Jt});}else c(En(E));Ye(i),ot(s),zt({...a,provider:a.provider||Ve});let K=M();if(K&&(await He(),wn(C)),d&&Rt(r),K)for(let q of C)q.createIndexes();c$1&&(await g(),ht()),d&&Et().catch(console.error),await Ft(n,{combinedModules:u,channels:F});}function un(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Tt(`${e.name}.${o}`,n);}}function mn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))vt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Dt(`${e.name}.${o}`,n);}}function pn(t){return t.flatMap(e=>e.stores)}function fn(t){return t.flatMap(e=>e.channels)}function hn(t){return t.flatMap(e=>e.rateLimits)}function gn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function yn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))St(`${e.name}.${o}`,n);}function wn(t){let e=ee();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var bn={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Sn(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function En(t){let e=[];for(let[o,n]of Object.entries(bn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:Sn(r,s)});}}return e}async function Cn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await xn(),r=await import('./package-3YQBVIVQ.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:To.hostname(),environmentId:o})});}}async function xn(){try{let t=ve.join(process.cwd(),"package.json"),e=await an.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Zt(t){await D.deleteMany({userId:t}),await x.deleteMany({userId:t});}async function vn(t){await Zt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function Dn(t){await Zt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Oe=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=ce().provider;if(!n){j("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function _n(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
|
|
18
18
|
export{S as Module,Oe as ServerChannel,w as Store,R as authenticate,I as consumeRateLimit,xe as createQuery,p as dbUsers,Dn as deleteUser,vn as disableUser,l as schema,_n as sendEmail,dn as startApp};//# sourceMappingURL=server.js.map
|
|
19
19
|
//# sourceMappingURL=server.js.map
|