modelence 0.23.0-setup.dev.0 → 0.23.0-setup.dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/modelence.js +4 -3
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-CQJPKRJ5.js → chunk-SJJHHXWI.js} +5 -5
- package/dist/{chunk-CQJPKRJ5.js.map → chunk-SJJHHXWI.js.map} +1 -1
- package/dist/{chunk-DDX25HLK.js → chunk-Y7D7TAYT.js} +3 -3
- package/dist/{chunk-DDX25HLK.js.map → chunk-Y7D7TAYT.js.map} +1 -1
- package/dist/{package-PTZXMZL3.js → package-XC3L6HIE.js} +2 -2
- package/dist/{package-PTZXMZL3.js.map → package-XC3L6HIE.js.map} +1 -1
- package/dist/server-Y64JROCD.js +2 -0
- package/dist/{server-ECQ5GFE4.js.map → server-Y64JROCD.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/server-ECQ5GFE4.js +0 -2
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import
|
|
3
|
-
`);await promises.
|
|
4
|
-
`)
|
|
2
|
+
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import D,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import z$1 from'open';import B from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import me from'archiver';async function E(e,{pickEnvironment:t=false,appId:o}={}){let i=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!i.ok)throw new Error("Failed to create CLI authentication code");let{code:s,verificationUrl:r}=await i.json(),a=new URLSearchParams({...t?{pick:"environment"}:{},...o?{appId:o}:{}}),n=a.size>0?`${r}&${a}`:r;return console.log(`Please visit ${n} to authenticate`),console.log(`Code: ${s}`),await z$1(n),{token:await J(e,s)}}async function J(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let r=await q(e,t);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function q(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:i}=await o.json();return i}var x=".modelence.env",y=".modelence",C="project.json";async function K(e,t){let o="setupToken"in t?{"X-Modelence-Setup-Token":t.setupToken}:{Authorization:`Bearer ${t.cliToken}`},i=await fetch(`${e}/api/setup`,{method:"GET",headers:o});if(!i.ok){let s=await i.text();throw new Error(s||`Request failed with status ${i.status}`)}return i.json()}async function X(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${x} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function Y(e){return String(e).replace(/"/g,'\\"')}async function H(){try{let e=await promises.readFile(join(process.cwd(),y,C),"utf8"),{appId:t}=JSON.parse(e);return typeof t=="string"&&t?t:void 0}catch{return}}async function Q(e){let t=join(process.cwd(),y),o=join(t,C),i={};try{i=JSON.parse(await promises.readFile(o,"utf8"));}catch{}await promises.mkdir(t,{recursive:true}),await promises.writeFile(o,JSON.stringify({...i,appId:e},null,2)+`
|
|
3
|
+
`);}async function Z(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function O(e){try{let t=join(process.cwd(),x),o={},i=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),i=!0,await Z(t),await X()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:c}=await E(e.host,{pickEnvironment:!0,appId:await H()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await K(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},n=Object.entries(a).map(([c,f])=>`${c}="${Y(f)}"`).join(`
|
|
4
|
+
`);if(await promises.writeFile(t,n.trim()+`
|
|
5
|
+
`),console.log(`Successfully configured ${x} file`),r.appId)try{await Q(r.appId),console.log(`Recorded the app ID in ${y}/${C}`);}catch(c){console.warn(`Failed to record the app ID in ${y}/${C}:`,c);}i&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.");}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var oe=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function $(){let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");return oe.parse(o)}var k=null,P=null;function ie(){if(!k)throw new Error("Environment variables not loaded");return k}function j(){if(!P)throw new Error("Configuration not loaded");return P}function M(e){return `${ie().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:t}=j();return join(e,t).replace(/\\/g,"/")}function I(){return j().postBuildCommand}function S(e){let t=T("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function u(e){return join(process.cwd(),e).replace(/\\/g,"/")}function T(e){let t=u(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function w(){try{P=await $();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await B.readFile(join(process.cwd(),".modelence.env"),"utf-8");k=parse(e);}catch(e){if(e.code==="ENOENT")k={};else throw e}}async function ce(){let e=I();if(e){console.log("Running post-build command..."),execSync(e);return}await le(),await de();}async function le(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:D.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function de(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:D.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:D.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},o,true));}async function pe(){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,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function N(){console.log("Building Modelence project...");try{let e=S();await B.rm(e,{recursive:!0,force:!0}),await pe(),await ce(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await B.access(T());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function L(e){let t=process.cwd(),o=join(t,".modelence"),i=join(o,"tmp","bundle.zip"),s=e.host||M("");await N(),await fe(i);let{token:r}=await E(s),{bundleName:a}=await ge(e.app,e.env,i,r,s);await promises.unlink(i),await we(e.app,e.env,a,join(".modelence","build","app.mjs"),r,s);}async function fe(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=me("zip",{zlib:{level:9}});o.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),o.on("error",n=>{throw n});let i=new Promise((n,c)=>{t.on("close",n),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],r=["public","server",join(".modelence","build"),".next"];for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&o.file(u(n),{name:n});for(let n of r)await promises.access(u(n)).then(()=>true).catch(()=>false)&&o.directory(u(n),n);await o.finalize(),await i;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ge(e,t,o,i,s){let r=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:a,bundleName:n}=await r.json(),c=await promises.readFile(o),f=await fetch(a,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!f.ok)throw new Error(`Failed to upload bundle: ${f.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function we(e,t,o,i,s,r){let a=await fetch(`${r}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:i})});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 U(){console.log("Starting Modelence dev server...");let e=p(),t=D.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function A(){console.log("Starting Modelence production server...");let e=p(),t=D.basename(e,D.extname(e)),o=S(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Ne=fileURLToPath(import.meta.url),xe=dirname(Ne),Pe=JSON.parse(readFileSync(join(xe,"../../package.json"),"utf-8")),m=new Command().name("modelence").description("Modelence CLI tool").version(Pe.version);m.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await O(e);});m.command("build").description("Build the application").action(async()=>{await w(),await N();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await w(),await L(e);});m.command("dev").description("Start development server").action(async()=>{await w(),U();});m.command("start").description("Start production server").action(async()=>{await w(),A();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
5
6
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","setup","options","join","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","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":";wdAaA,eAAsBA,CAAAA,CACpBC,CAAAA,CACA,CAAE,eAAA,CAAAC,CAAAA,CAAkB,KAAM,CAAA,CAAmC,EAAC,CAClC,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGF,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,CAAA,CAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAMJ,CAAAA,CAAkB,CAAA,EAAGG,CAAe,CAAA,iBAAA,CAAA,CAAsBA,CAAAA,CAEtE,OAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBC,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,QAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,CAAA,CAAE,CAAA,CAE3B,MAAMG,CAAAA,CAAKD,CAAG,CAAA,CAIP,CAAE,KAAA,CAFK,MAAME,CAAAA,CAAYP,CAAAA,CAAMG,CAAI,CAE3B,CACjB,CAEA,eAAeI,CAAAA,CAAYP,CAAAA,CAAcG,CAAAA,CAA+B,CAGtE,IAAMK,CAAAA,CAAe,IAAA,CAAK,GAAA,EAAI,CAAI,GAAA,CAClC,KAAO,KAAK,GAAA,EAAI,CAAIA,CAAAA,EAAc,CAChC,GAAI,CAC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AQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false }: { pickEnvironment?: boolean } = {}\n): Promise<{ token: string }> {\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 const url = pickEnvironment ? `${verificationUrl}&pick=environment` : verificationUrl;\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(url);\n\n const token = await waitForAuth(host, code);\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 { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\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 let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\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 let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, { pickEnvironment: true });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\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\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","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});\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","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 { 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';\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 // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\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 // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\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 void 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 { 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 .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\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/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","hintParams","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","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":";0dAkBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAI,gBAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,EAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAa,IAAI,gBAAgB,CACrC,GAAIL,CAAAA,CAAkB,CAAE,IAAA,CAAM,aAAc,EAAI,EAAC,CACjD,GAAIC,CAAAA,CAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CAAC,CAAA,CACKK,CAAAA,CAAMD,CAAAA,CAAW,IAAA,CAAO,CAAA,CAAI,CAAA,EAAGD,CAAe,CAAA,CAAA,EAAIC,CAAU,CAAA,CAAA,CAAKD,EAEvE,OAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBE,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,QAAQ,GAAA,CAAI,CAAA,MAAA,EAASH,CAAI,CAAA,CAAE,CAAA,CAE3B,MAAMI,IAAKD,CAAG,CAAA,CAIP,CAAE,KAAA,CAFK,MAAME,CAAAA,CAAYT,EAAMI,CAAI,CAE3B,CACjB,CAEA,eAAeK,CAAA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ACd4C,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n\n `appId` is the hint from .modelence/project.json: the approval page uses it\n to preselect the app this project was last connected to. Purely a\n convenience for the picker — the user can still choose any app, and an\n unresolvable ID is simply ignored.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false, appId }: { pickEnvironment?: boolean; appId?: string } = {}\n): Promise<{ token: string }> {\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 const hintParams = new URLSearchParams({\n ...(pickEnvironment ? { pick: 'environment' } : {}),\n ...(appId ? { appId } : {}),\n });\n const url = hintParams.size > 0 ? `${verificationUrl}&${hintParams}` : verificationUrl;\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(url);\n\n const token = await waitForAuth(host, code);\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 { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\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\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like cache/ are\n temporary), so the whole team gets it. It's a hint in the git-remote sense —\n connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\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 let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\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 let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\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\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","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});\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","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 { 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';\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 // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\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 // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\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 void 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 { 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 .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\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,4 +1,4 @@
|
|
|
1
|
-
import {s as s$1}from'./chunk-
|
|
1
|
+
import {s as s$1}from'./chunk-Y7D7TAYT.js';import {a,b as b$1,c,d,q,r,s,t,u,m,n,e,z as z$2,l,k,o,j,p,v as v$1,A,B,C as C$1,D,f as f$1,E,x as x$1,w as w$1,g as g$1,H,F as F$1,G}from'./chunk-WHC2SP5P.js';import {c as c$1,b as b$2,d as d$1,a as a$4}from'./chunk-VYR7VQMQ.js';import {a as a$2,f,e as e$1,g,c as c$2,i,m as m$1,l as l$1,d as d$2,k as k$1,n as n$1,j as j$1,o as o$1}from'./chunk-B5WLEHNH.js';import {a as a$3,b as b$3}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import ar from'dotenv';import Tn from'fs/promises';import Yr from'os';import Q from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoServerError,MongoClient,MongoError,ObjectId}from'mongodb';export{ObjectId as m}from'mongodb';import xr from'bcrypt';import V,{z as z$1}from'zod';import {randomBytes,randomInt,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import hn from'@vitejs/plugin-react';import _e from'fs';import B$1,{Router}from'express';import gi from'cookie-parser';import hi from'http';var le=new a("_system",{queries:{setupStatus:async()=>({setupRequired:b$1()})},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 F=null;async function qt(){if(F)return F;let e=N();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");F=new MongoClient(e,{driverInfo:{name:"Modelence",version:s$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await F.connect(),await F.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),F}catch(o){throw console.error(o),F=null,o}}function N(){return le.getConfig("mongodbUri")||void 0}function be(){return F}var de=null,vr="_modelenceSocketio",zt=60;async function kr({httpServer:e,channels:t}){let o=be(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(vr);try{await n.createIndex({createdAt:1},{expireAfterSeconds:zt,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:zt,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:",i);}}de=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),de.on("error",i=>{console.error("Socket.IO error:",i);}),de.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await x$1(a),s();}catch(c){s(c instanceof Error?c:new Error(String(c)));}}),de.on("connection",i=>{i.on("disconnect",()=>{H(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>F$1(i,s)),i.on("unsubscribeLiveQuery",s=>G(i,s));}),console.log("Socket.IO server initialized");}function Cr({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var Wt={init:kr,broadcast:Cr};async function ve(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await r.findOne({domain:o})}var Jt={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 o=(await e.text()).split(`
|
|
2
2
|
`).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r$1=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await r.insertMany(s.map(a=>({domain:a,addedAt:r$1})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var ke=3,z=50,Kt=8,Yt=128,Qt=254,Xt=e=>z$1.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`}),Ge=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),Sr=z$1.object({firstName:Ge({max:50}),lastName:Ge({max:50}),avatarUrl:Ge({max:400}),handle:Xt({min:ke,max:z})}).strict();function Ce(e){let t=Sr.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function Se(e){return z$1.string().min(Kt,{message:`Password must contain at least ${Kt} characters`}).max(Yt,{message:`Password must be at most ${Yt} characters`}).parse(e)}function O(e){return z$1.string().max(Qt,{message:`Email must be at most ${Qt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Zt(e){return Xt({min:ke,max:z}).parse(e)}function Ae(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function Re(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function ee(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 eo(e){let t=e.slice(0,z);try{if(!await q.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o=51;for(let n=2;n<=o;n++){let i=`_${n}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.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 L(e,t,{throwOnConflict:o=true}={}){if(e!=null&&String(e).trim()!==""){let n=Zt(String(e).trim());if(o){if(await q.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return eo(n)}let r=t.split("@")[0].padEnd(ke,"_").slice(0,z);return eo(r)}var Fe=Object.freeze({});function Ve(e){Fe=Object.freeze(Object.assign({},Fe,e));}function w(){return Fe}var Be=Object.freeze({});function to(e){Be=Object.freeze(Object.assign({},Be,e));}function b(){return Be}function _r(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}async function ro(e,{user:t,session:o,connectionInfo:r,res:n$1}){try{if(!o)throw new Error("Session is not initialized");if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let i=r?.ip;i&&await C({bucket:"signin",type:"ip",value:i});let s=O(e.email),a=z$1.string().parse(e.password),c=await q.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=c?.authMethods?.password?.hash;if(!l)throw oo();if(!c.emails?.find(f=>f.address.toLowerCase()===s)?.verified&&_r())throw new b$2("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");if(!await xr.compare(a,l))throw oo();return await j(o.authToken,c._id),n$1&&n(n$1,o.authToken),b().onAfterLogin?.({provider:"email",user:c,session:o,connectionInfo:r}),b().login?.onSuccess?.(c),{user:ee(c),session:{authToken:o.authToken}}}catch(i){throw i instanceof Error&&(b().onLoginError?.({provider:"email",error:i,session:o,connectionInfo:r}),b().login?.onError?.(i)),i}}async function no(e,{session:t,res:o$1}){if(!t)throw new Error("Session is not initialized");await k(t.authToken),o$1&&o(o$1);}function oo(){return new Error("Incorrect email/password combination")}async function io(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{}),firstName:o.firstName??void 0,lastName:o.lastName??void 0,avatarUrl:o.avatarUrl??void 0}}async function so(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id),r=Ce(e);if(await b().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await q.findOne({handle:r.handle,_id:{$ne:o._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await q.updateOne({_id:o._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o={...o,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:ee(o)}}var qe=["google","github"];async function ao({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!qe.includes(e))throw new Error(`Invalid provider. Supported providers are: ${qe.join(", ")}.`);let o=await q.requireById(t.id),r=o.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await q.updateOne({_id:o._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var me=new c("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user","email"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var ze=[];function co(e){if(ze.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");ze=e;}async function C(e){let{bucket:t,type:o,value:r,message:n}=e,i=ze.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d$1(n):void 0;for(let a of i)await Lr(a,r,s);}async function Lr(e,t,o){let r=()=>o?o():new d$1(`Rate limit exceeded for ${e.bucket}`),n=await me.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?Tr(n,s,i):{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 r();await me.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Tr(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),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 lo({name:e,email:t,verificationUrl:o}){return `
|
|
3
3
|
<p>Hi${e?` ${e}`:""},</p>
|
|
4
4
|
<p>Please verify your email address ${t} by clicking the link below:</p>
|
|
@@ -26,12 +26,12 @@ ${e.window}`}function qr(){return [{bucket:"signup",type:"ip",window:a$1.minutes
|
|
|
26
26
|
|
|
27
27
|
This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
|
|
28
28
|
\u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
|
|
29
|
-
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-JPOZOWQ6.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[B$1.static(ge,t)];return this.config?.publicDir&&o.push(B$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&En(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)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:i},{getCallContext:s},a]=await Promise.all([import('./render-RN75WGWX.js'),import('./server-
|
|
29
|
+
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-JPOZOWQ6.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[B$1.static(ge,t)];return this.config?.publicDir&&o.push(B$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&En(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)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:i},{getCallContext:s},a]=await Promise.all([import('./render-RN75WGWX.js'),import('./server-Y64JROCD.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);kn(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:m,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:h,rootOpenTag:y,epilogue:k}=bn(r),P=vn(h,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(P),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${mt(d)}</script>`),o.write(y),await m(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${mt(f())}</script>`),o.end(k);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,or):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ge)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Q.resolve(process.cwd(),"src/client/index.html"),r=_e.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Q.resolve(process.cwd(),ge,"index.html");this.prodTemplateCache=_e.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-DDIZBBPN.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(or),t()}return this.prodEntryLoaded||(await import(Q.resolve(process.cwd(),tr,"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(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:ge});}isDev(){return process.env.NODE_ENV!=="production"}};function En(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function bn(e){let t=e.match(wn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function vn(e,t){if(!t)return e;let o=e.lastIndexOf(yn);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function kn(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function Cn(){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 Sn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function An(e,t={}){let o=process.cwd(),r=await Cn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>_e.existsSync(Q.join(o,a))),i=[hn(),Rn()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:Q.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:ge,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Q.resolve(o,"src").replace(/\\/g,"/")}}});return Sn(s,r)}function Rn(){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 Le=new pt;function xn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function On(e){if(e)return Array.isArray(e)?e:[e]}function _n(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:xn(e.from),replyTo:On(e.replyTo)}}function Ln(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var rr={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await T("/api/email/send","POST",_n(e));}catch(t){throw Ln(t)}}};var ft=Object.freeze({});function nr(e){ft=Object.freeze(Object.assign({},ft,e));}function ir(){return ft}var gt=Object.freeze({});function sr(e){gt=Object.freeze(Object.assign({},gt,e));}function Te(){return gt}async function In({modules:e=[],roles:t={},defaultRoles:o={},server:r=Le,migrations:n=[],email:i$1={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===Le&&Le.enableSsr(),ar.config(),ar.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;qn().then(()=>{}).catch(()=>{});for(let D of e)if(D.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${D.name}'
|
|
30
30
|
|
|
31
31
|
The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
|
|
32
32
|
|
|
33
|
-
Rename your module to something that does not start with '_system.'`);let m=[nt,p,Jo,Qo,Xo,le,dt,Zo],f$1=[...m,...e];f(),Nn(m),Un(e),v$1(t,o);let h=Fn(f$1);e$1(h);let y=Dn(f$1),k=$n(f$1);Vn(f$1),nt.rateLimits=rt(s.rateLimits);let P=jn(f$1);co(P);let{storesToInit:M,effectiveStores:S}=Ko(y);if(d){let{configs:D,environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr}=await Io({configSchema:h,cronJobsMetadata:Wo(),stores:S,roles:t});st(D),g({environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr});}else c$2(Oe(h));if(d&&!i$1.provider?Ve({...i$1,provider:rr}):Ve(i$1),to(s),nr(a),sr({...c,provider:c.provider||Wt}),N()){await qt();let D=[...new Set([...M,...S])];Bn(D),await Gn(S,n);}else Yo(n);d&&(await i(),Do()),zo().catch(console.error),await cr(r,{combinedModules:f$1,channels:k});}function Un(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B(`${t.name}.${o}`,r);}}function Nn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))C$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))D(`${t.name}.${o}`,r);}}function Dn(e){return e.flatMap(t=>t.stores)}function $n(e){return e.flatMap(t=>t.channels)}function jn(e){return e.flatMap(t=>t.rateLimits)}function Hn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var ht="migrations";async function Gn(e,t){if(!await K(ht,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await wt(a,"full");for(let a of n)await wt(a,"drop-only");}catch(a){throw await pe(ht),a}let i=(async()=>{for(let a of n)await wt(a,"create-only");})(),s=ut(t,{lockMode:"skip"});Promise.allSettled([i,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 pe(ht);});}async function wt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Hn(o,r);}}function Fn(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function Vn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))qo(`${t.name}.${o}`,r);}function Bn(e){let t=be();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function qn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await zn(),n=await import('./package-PTZXMZL3.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Yr.hostname(),environmentId:o})});}}async function zn(){try{let e=Q.join(process.cwd(),"package.json"),t=await Tn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function lr(e){await s.deleteMany({userId:e}),await t.deleteMany({userId:e});let t$1=await q.findOne({_id:e}),o=Array.from(new Set((t$1?.emails??[]).map(r=>r.address?.toLowerCase()).filter(r=>!!r)));o.length>0&&await u.deleteMany({email:{$in:o}});}async function Jn(e){await lr(e),await q.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Kn(e){await lr(e),await q.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var yt=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Te().provider;if(!r){m$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function Yn(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)}async function Pe(e){return !e||typeof e!="string"?null:g$1(e)}function v(e,t,o){let r=b(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function Et(e,t){let{authToken:o}=await m(t);n(e,o),e.status(302),e.redirect("/");}async function Xn(e,t,o,r,n){let i=b();try{if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o;Object.keys(s).length>0&&(await q.updateOne({_id:o._id},{$set:s}),a={...o,...s}),await Et(e,o._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function Zn(e,t,o,r,n){let i=b();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}if(!o.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await q.updateOne({_id:o._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)){v(e,400,"User with this email already exists. Please log in instead.");return}await Et(e,o._id);let m={...o,...c,authMethods:{...o.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:m,session:r,connectionInfo:n}),i.login?.onSuccess?.(m);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function ei(e,t,o,r){let n=b();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await L(l,t.email,{throwOnConflict:!1});}else i=await L(void 0,t.email);let s={handle:i,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 q.insertOne(s);await Et(e,a.insertedId);let c=await q.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Me(e,t,o){let r=await q.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return Xn(t,o,r,n,i);if(!o.email){v(t,400,`Email address is required for ${o.providerName} authentication.`);return}let s;try{s=await q.findOne({"emails.address":o.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=b();c.onSignupError?.({provider:o.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?Zn(t,o,s,n,i):ei(t,o,n,i)}function x(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Ie(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Ue(e,t,o,r){let n=b(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){x(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){x(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o.providerName}.id`;if((await q.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o.id}]},{$set:{[l]:o.id}})).matchedCount===0){let f=await q.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),x(t),v(t,400,"User account is not active.");return}let h=f?.authMethods?.[o.providerName]?.id;if(h&&h!==o.id){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`User already has a different ${o.providerName} account linked`),session:i,connectionInfo:s})),x(t),v(t,400,`You have already linked a different ${o.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`Unexpected OAuth linking state for ${o.providerName}`),session:i,connectionInfo:s})),x(t),v(t,400,`Unable to link ${o.providerName} account.`);return}let m=await q.findOne({_id:c},{readPreference:"primary"});m&&oe(()=>n.onAfterOAuthLink?.({provider:o.providerName,user:m,session:i,connectionInfo:s})),x(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),v(t,400,`This ${o.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),!t.headersSent)throw l}}function Ne(e){return !e||typeof e!="string"?null:e}async function ri(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ni(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 ii(e,t){let o=Ne(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ie(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await ri(o,s,a,c),d=await ni(l.access_token),m={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Ue(e,t,m,i):await Me(e,t,m);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function si(){let e=Router(),t=(o,r,n)=>{let i=!!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(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Pe(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,ii),e}var ur=si;async function li(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function di(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 ui(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 mi(e,t){return e.email?e.email:(await ui(t)).find(r=>r.primary&&r.verified)?.email??null}async function pi(e,t){let o=Ne(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ie(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await li(o,s,a,c),d=await di(l.access_token),m=await mi(d,l.access_token);if(!m){n==="link"&&x(t),v(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 f=d.name?d.name.trim().split(/\s+/):[],h=f[0]||void 0,y=f.length>1?f.slice(1).join(" "):void 0,k={id:String(d.id),email:m,emailVerified:!0,providerName:"github",firstName:h,lastName:y,avatarUrl:d.avatar_url||void 0};n==="link"?await Ue(e,t,k,i):await Me(e,t,k);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function fi(){let e=Router(),t=(o,r,n)=>{let i=!!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(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(h=>h.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Pe(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let m=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",m,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,pi),e}var mr=fi;function pr(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await x$1(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j$1(r.query),body:j$1(r.body),params:j$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.contentType&&n.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,m])=>{n.setHeader(d,m);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function wi(e){let t=[];if(!e)return t.push(B$1.json({limit:"16mb"})),t.push(B$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(B$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(B$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(B$1.raw(r));}return t}function yi(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=wi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,pr(c,n,l));});}}async function cr(e,{combinedModules:t,channels:o}){let r=B$1();r.use(gi()),r.use(vi()),yi(r,t),r.use(B$1.json({limit:"16mb"})),r.use(B$1.urlencoded({extended:true,limit:"16mb"})),r.use(ur()),r.use(mr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await ne(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});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await f$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await ne(a,c);try{let m=a$3(await E(l,a.body.args,d));c.json({data:m,typeMap:b$3(m)});}catch(m){Ei(c,l,m);}});let n=hi.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.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 i=Te()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{l$1("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
|
|
33
|
+
Rename your module to something that does not start with '_system.'`);let m=[nt,p,Jo,Qo,Xo,le,dt,Zo],f$1=[...m,...e];f(),Nn(m),Un(e),v$1(t,o);let h=Fn(f$1);e$1(h);let y=Dn(f$1),k=$n(f$1);Vn(f$1),nt.rateLimits=rt(s.rateLimits);let P=jn(f$1);co(P);let{storesToInit:M,effectiveStores:S}=Ko(y);if(d){let{configs:D,environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr}=await Io({configSchema:h,cronJobsMetadata:Wo(),stores:S,roles:t});st(D),g({environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr});}else c$2(Oe(h));if(d&&!i$1.provider?Ve({...i$1,provider:rr}):Ve(i$1),to(s),nr(a),sr({...c,provider:c.provider||Wt}),N()){await qt();let D=[...new Set([...M,...S])];Bn(D),await Gn(S,n);}else Yo(n);d&&(await i(),Do()),zo().catch(console.error),await cr(r,{combinedModules:f$1,channels:k});}function Un(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B(`${t.name}.${o}`,r);}}function Nn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))C$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))D(`${t.name}.${o}`,r);}}function Dn(e){return e.flatMap(t=>t.stores)}function $n(e){return e.flatMap(t=>t.channels)}function jn(e){return e.flatMap(t=>t.rateLimits)}function Hn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var ht="migrations";async function Gn(e,t){if(!await K(ht,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await wt(a,"full");for(let a of n)await wt(a,"drop-only");}catch(a){throw await pe(ht),a}let i=(async()=>{for(let a of n)await wt(a,"create-only");})(),s=ut(t,{lockMode:"skip"});Promise.allSettled([i,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 pe(ht);});}async function wt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Hn(o,r);}}function Fn(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function Vn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))qo(`${t.name}.${o}`,r);}function Bn(e){let t=be();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function qn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await zn(),n=await import('./package-XC3L6HIE.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Yr.hostname(),environmentId:o})});}}async function zn(){try{let e=Q.join(process.cwd(),"package.json"),t=await Tn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function lr(e){await s.deleteMany({userId:e}),await t.deleteMany({userId:e});let t$1=await q.findOne({_id:e}),o=Array.from(new Set((t$1?.emails??[]).map(r=>r.address?.toLowerCase()).filter(r=>!!r)));o.length>0&&await u.deleteMany({email:{$in:o}});}async function Jn(e){await lr(e),await q.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Kn(e){await lr(e),await q.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var yt=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Te().provider;if(!r){m$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function Yn(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)}async function Pe(e){return !e||typeof e!="string"?null:g$1(e)}function v(e,t,o){let r=b(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function Et(e,t){let{authToken:o}=await m(t);n(e,o),e.status(302),e.redirect("/");}async function Xn(e,t,o,r,n){let i=b();try{if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o;Object.keys(s).length>0&&(await q.updateOne({_id:o._id},{$set:s}),a={...o,...s}),await Et(e,o._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function Zn(e,t,o,r,n){let i=b();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}if(!o.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await q.updateOne({_id:o._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)){v(e,400,"User with this email already exists. Please log in instead.");return}await Et(e,o._id);let m={...o,...c,authMethods:{...o.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:m,session:r,connectionInfo:n}),i.login?.onSuccess?.(m);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function ei(e,t,o,r){let n=b();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await L(l,t.email,{throwOnConflict:!1});}else i=await L(void 0,t.email);let s={handle:i,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 q.insertOne(s);await Et(e,a.insertedId);let c=await q.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Me(e,t,o){let r=await q.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return Xn(t,o,r,n,i);if(!o.email){v(t,400,`Email address is required for ${o.providerName} authentication.`);return}let s;try{s=await q.findOne({"emails.address":o.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=b();c.onSignupError?.({provider:o.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?Zn(t,o,s,n,i):ei(t,o,n,i)}function x(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Ie(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Ue(e,t,o,r){let n=b(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){x(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){x(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o.providerName}.id`;if((await q.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o.id}]},{$set:{[l]:o.id}})).matchedCount===0){let f=await q.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),x(t),v(t,400,"User account is not active.");return}let h=f?.authMethods?.[o.providerName]?.id;if(h&&h!==o.id){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`User already has a different ${o.providerName} account linked`),session:i,connectionInfo:s})),x(t),v(t,400,`You have already linked a different ${o.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`Unexpected OAuth linking state for ${o.providerName}`),session:i,connectionInfo:s})),x(t),v(t,400,`Unable to link ${o.providerName} account.`);return}let m=await q.findOne({_id:c},{readPreference:"primary"});m&&oe(()=>n.onAfterOAuthLink?.({provider:o.providerName,user:m,session:i,connectionInfo:s})),x(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),v(t,400,`This ${o.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),!t.headersSent)throw l}}function Ne(e){return !e||typeof e!="string"?null:e}async function ri(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ni(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 ii(e,t){let o=Ne(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ie(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await ri(o,s,a,c),d=await ni(l.access_token),m={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Ue(e,t,m,i):await Me(e,t,m);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function si(){let e=Router(),t=(o,r,n)=>{let i=!!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(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Pe(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,ii),e}var ur=si;async function li(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function di(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 ui(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 mi(e,t){return e.email?e.email:(await ui(t)).find(r=>r.primary&&r.verified)?.email??null}async function pi(e,t){let o=Ne(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ie(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await li(o,s,a,c),d=await di(l.access_token),m=await mi(d,l.access_token);if(!m){n==="link"&&x(t),v(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 f=d.name?d.name.trim().split(/\s+/):[],h=f[0]||void 0,y=f.length>1?f.slice(1).join(" "):void 0,k={id:String(d.id),email:m,emailVerified:!0,providerName:"github",firstName:h,lastName:y,avatarUrl:d.avatar_url||void 0};n==="link"?await Ue(e,t,k,i):await Me(e,t,k);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function fi(){let e=Router(),t=(o,r,n)=>{let i=!!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(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(h=>h.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Pe(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let m=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",m,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,pi),e}var mr=fi;function pr(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await x$1(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j$1(r.query),body:j$1(r.body),params:j$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.contentType&&n.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,m])=>{n.setHeader(d,m);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function wi(e){let t=[];if(!e)return t.push(B$1.json({limit:"16mb"})),t.push(B$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(B$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(B$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(B$1.raw(r));}return t}function yi(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=wi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,pr(c,n,l));});}}async function cr(e,{combinedModules:t,channels:o}){let r=B$1();r.use(gi()),r.use(vi()),yi(r,t),r.use(B$1.json({limit:"16mb"})),r.use(B$1.urlencoded({extended:true,limit:"16mb"})),r.use(ur()),r.use(mr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await ne(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});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await f$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await ne(a,c);try{let m=a$3(await E(l,a.body.args,d));c.json({data:m,typeMap:b$3(m)});}catch(m){Ei(c,l,m);}});let n=hi.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.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 i=Te()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{l$1("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
|
|
34
34
|
Application started on ${a}
|
|
35
35
|
`);});}async function ne(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=V.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=V.object({screenWidth:V.number(),screenHeight:V.number(),windowWidth:V.number(),windowHeight:V.number(),pixelRatio:V.number(),orientation:V.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:Ci(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:ki(e)};if(!!N()){let{session:l,user:d,roles:m}=await x$1(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:m,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:w$1(),req:e,res:t}}function Ei(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=bi(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function bi(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function vi(){let{frameAncestors:e}=ir(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function ki(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function Ci(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
|
|
36
|
-
export{C as a,cn as b,ln as c,dn as d,un as e,cr as f,ne as g,In as h,Jn as i,Kn as j,yt as k,Yn as l};//# sourceMappingURL=chunk-
|
|
37
|
-
//# sourceMappingURL=chunk-
|
|
36
|
+
export{C as a,cn as b,ln as c,dn as d,un as e,cr as f,ne as g,In as h,Jn as i,Kn as j,yt as k,Yn as l};//# sourceMappingURL=chunk-SJJHHXWI.js.map
|
|
37
|
+
//# sourceMappingURL=chunk-SJJHHXWI.js.map
|