modelence 0.5.13-dev.1 → 0.5.14-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -2
- package/dist/bin/modelence.js +1 -1
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{package-4AVYWVZ4.js → package-4RSIRWA5.js} +3 -3
- package/dist/{package-4AVYWVZ4.js.map → package-4RSIRWA5.js.map} +1 -1
- package/dist/server.js +6 -6
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<img alt="Y Combinator S25" src="https://img.shields.io/badge/Combinator-S25-orange?logo=ycombinator&labelColor=white" />
|
|
11
11
|
</h1>
|
|
12
12
|
|
|
13
|
-
[Website](https://modelence.com) | [Documentation](https://docs.modelence.com) | [API Reference](https://docs.modelence.com/api-reference)
|
|
13
|
+
[Website](https://modelence.com) | [Documentation](https://docs.modelence.com) | [API Reference](https://docs.modelence.com/api-reference) | [Modelence Cloud](https://cloud.modelence.com)
|
|
14
14
|
|
|
15
15
|

|
|
16
16
|
<a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg" /></a>
|
|
@@ -20,4 +20,29 @@
|
|
|
20
20
|
## Getting Started
|
|
21
21
|
Modelence is an all-in-one TypeScript framework for startups shipping production apps, with the mission to eliminate all boilerplate for standard features that modern web applications need, like authentication, database setup, cron jobs, AI observability, email and more.
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
### Quick Start
|
|
24
|
+
|
|
25
|
+
#### 1. Create a new project
|
|
26
|
+
```bash
|
|
27
|
+
npx create-modelence-app@latest my-app
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
#### 2. Install dependencies
|
|
31
|
+
```bash
|
|
32
|
+
cd my-app
|
|
33
|
+
npm install
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
#### 3. Start the development server
|
|
37
|
+
```bash
|
|
38
|
+
npm run dev
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Your app will be available at [http://localhost:3000](http://localhost:3000)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
For a more detailed guide, check out the [Todo App tutorial](https://docs.modelence.com/tutorial).
|
|
45
|
+
|
|
46
|
+
### Examples
|
|
47
|
+
|
|
48
|
+
For more examples on how to use Modelence, check out https://github.com/modelence/examples
|
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import G,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import re from'archiver';import Q from'open';var C=".modelence.env";async function I(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function F(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${C} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function L(e){return String(e).replace(/"/g,'\\"')}async function _(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function x(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await _(o),await F()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${L(n)}"`).join(`
|
|
3
3
|
`);await promises.writeFile(o,s.trim()+`
|
|
4
|
-
`),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,b=null;function z(){if(!w)throw new Error("Environment variables not loaded");return w}function k(){if(!b)throw new Error("Configuration not loaded");return b}function d(e){return `${z().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function h(){let{serverDir:e,serverEntry:o}=k();return join(e,o)}function S(){return k().postBuildCommand}function D(e){let o=N("build");return o}function u(e){return join(process.cwd(),e)}function N(e){let o=u(".modelence");return e?join(o,e):o}async function E(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");b=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function X(){let e=S();if(e){console.log("Running post-build command..."),execSync(e);return}await Y();}async function Y(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:G.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function H(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[h()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=D();await O.rm(e,{recursive:!0,force:!0}),await H(),await X(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function T(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Q(t);let r=await oe(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function oe(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await te(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function te(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function B(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await v(),await ie(r);let{token:i}=await T(),{bundleName:s}=await se(e.app,e.env,r,i);await promises.unlink(r),await ae(e.app,e.env,s,join(".modelence","build","app.mjs"),i);}async function ie(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=re("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,p)=>{o.on("close",n),o.on("error",p),t.on("error",p);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.file(u(n),{name:n});for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.directory(u(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function se(e,o,t,r){let i=await fetch(d("/api/upload-bundle"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:s,bundleName:a}=await i.json(),n=await promises.readFile(t),p=await fetch(s,{method:"PUT",body:n,headers:{"Content-Type":"application/zip"}});if(!p.ok)throw new Error(`Failed to upload bundle: ${p.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${a}`),{bundleName:a}}async function ae(e,o,t,r,i){let s=await fetch(d("/api/deploy"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!s.ok)throw new Error(`Failed to trigger deployment: ${s.statusText}`);let{deploymentUrl:a}=await s.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${a}`);}function P(){console.log("Starting Modelence dev server...");let e=h(),o=G.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var f=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");f.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await x(e);});f.command("build").description("Build the application").action(async()=>{await E(),await v();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").action(async e=>{await E(),await B(e);});f.command("dev").description("Start development server").action(async()=>{await E(),P();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
4
|
+
`),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,b=null;function z(){if(!w)throw new Error("Environment variables not loaded");return w}function k(){if(!b)throw new Error("Configuration not loaded");return b}function d(e){return `${z().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function h(){let{serverDir:e,serverEntry:o}=k();return join(e,o).replace(/\\/g,"/")}function S(){return k().postBuildCommand}function D(e){let o=N("build");return o.replace(/\\/g,"/")}function u(e){return join(process.cwd(),e).replace(/\\/g,"/")}function N(e){let o=u(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function E(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");b=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function X(){let e=S();if(e){console.log("Running post-build command..."),execSync(e);return}await Y();}async function Y(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:G.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function H(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[h()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=D();await O.rm(e,{recursive:!0,force:!0}),await H(),await X(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function T(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Q(t);let r=await oe(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function oe(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await te(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function te(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function B(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await v(),await ie(r);let{token:i}=await T(),{bundleName:s}=await se(e.app,e.env,r,i);await promises.unlink(r),await ae(e.app,e.env,s,join(".modelence","build","app.mjs"),i);}async function ie(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=re("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,p)=>{o.on("close",n),o.on("error",p),t.on("error",p);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.file(u(n),{name:n});for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.directory(u(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function se(e,o,t,r){let i=await fetch(d("/api/upload-bundle"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:s,bundleName:a}=await i.json(),n=await promises.readFile(t),p=await fetch(s,{method:"PUT",body:n,headers:{"Content-Type":"application/zip"}});if(!p.ok)throw new Error(`Failed to upload bundle: ${p.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${a}`),{bundleName:a}}async function ae(e,o,t,r,i){let s=await fetch(d("/api/deploy"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!s.ok)throw new Error(`Failed to trigger deployment: ${s.statusText}`);let{deploymentUrl:a}=await s.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${a}`);}function P(){console.log("Starting Modelence dev server...");let e=h(),o=G.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var f=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");f.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await x(e);});f.command("build").description("Build the application").action(async()=>{await E(),await v();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").action(async e=>{await E(),await B(e);});f.command("dev").description("Start development server").action(async()=>{await E(),P();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
5
5
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";wbAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MA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,MAAA,CAAO,SAAY,CAClB,MAAMzD,CAAAA,EAAQ,CACdsD,IACF,CAAC,EAEHG,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\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\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(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(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(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.app, options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\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 = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\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(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(appAlias: string, envAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/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: 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(appAlias: string, envAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";wbAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,CAAA,CAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CAAS,CAAA,SAAA,EAAYP,CAAkB,uDAAyDU,CAAAA,EAAW,CAC5GH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,CAAAA,CAAO,WAAA,EAAY,GAAM,GAAG,EACtC,CAAC,EACH,CAAC,CACH,CAEA,SAASC,CAAAA,CAAeC,C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as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\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\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(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(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(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.app, options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\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 = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\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(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(appAlias: string, envAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/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: 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(appAlias: string, envAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",o="0.5.
|
|
2
|
-
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-
|
|
3
|
-
//# sourceMappingURL=package-
|
|
1
|
+
var s="module",i="modelence",o="0.5.14-dev.0",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0"},v={"@modelence/types":"^1.0.3","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.0",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-4RSIRWA5.js.map
|
|
3
|
+
//# sourceMappingURL=package-4RSIRWA5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,cAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,YAAa,iBACf,CAAA,CACAC,EAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,EACAC,CAAAA,CAAW,CACT,MAAS,MAAA,CACT,GAAA,CAAO,eACP,cAAA,CAAkB,eAAA,CAClB,KAAQ,2CAAA,CACR,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,yBACXC,CAAAA,CAAQ,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBAAA,CACZC,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,QAAA,CACnB,gBAAiB,QAAA,CACjB,sBAAA,CAAwB,SACxB,gBAAA,CAAkB,QAAA,CAClB,kBAAmB,SAAA,CACnB,aAAA,CAAe,UACf,gCAAA,CAAkC,SAAA,CAClC,eAAgB,SAAA,CAChB,kBAAA,CAAoB,UACpB,kCAAA,CAAoC,SAAA,CACpC,4BAA6B,SAAA,CAC7B,KAAA,CAAS,SAAA,CACT,WAAA,CAAa,SACf,CAAA,CACAC,EAAgB,CACd,kBAAA,CAAoB,SACpB,sBAAA,CAAwB,QAAA,CACxB,SAAY,QAAA,CACZ,MAAA,CAAU,SACV,SAAA,CAAa,SAAA,CACb,gBAAiB,QAAA,CACjB,MAAA,CAAU,UACV,kBAAA,CAAoB,QAAA,CACpB,QAAW,SAAA,CACX,UAAA,CAAY,UACZ,IAAA,CAAQ,QAAA,CACR,QAAW,QAAA,CACX,IAAA,CAAQ,UACR,QAAA,CAAY,QAAA,CACZ,0BAA2B,QAAA,CAC3B,IAAA,CAAQ,SACR,GAAA,CAAO,SAAA,CACP,WAAc,QAAA,CACd,IAAA,CAAQ,SACR,oBAAA,CAAsB,QAAA,CACtB,QAAW,SAAA,CACX,uBAAA,CAAyB,UACzB,GAAA,CAAO,SAAA,CACP,QAAW,QACb,CAAA,CACAC,EAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,EAlFFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAeA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,cAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,YAAa,iBACf,CAAA,CACAC,EAAS,CACP,MAAA,C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FFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAeA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-4RSIRWA5.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.14-dev.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\n },\n \"dependencies\": {\n \"@modelence/types\": \"^1.0.3\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/server.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d as d$1,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$2,c,f as f$1,g as g$1,a as a$2,h as h$1,j
|
|
2
|
-
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await
|
|
1
|
+
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d as d$1,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$2,c,f as f$1,g as g$1,a as a$2,h as h$1,j as j$1,k}from'./chunk-2QLNYYBR.js';export{a as getConfig}from'./chunk-2QLNYYBR.js';import ft from'dotenv';import ho from'fs/promises';import Jt from'os';import ie from'path';import {randomBytes}from'crypto';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import E,{z as z$1}from'zod';import Ot from'bcrypt';import {createServer,defineConfig,loadConfigFromFile}from'vite';import Yt from'@vitejs/plugin-react';import Xt from'fs';import ce,{Router}from'express';import ae from'passport';import {Strategy}from'passport-google-oauth20';import co from'cookie-parser';import lo from'http';var ye=new Map,M={authenticated:null,unauthenticated:null};function be(t,e){M.authenticated=e.authenticated,M.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ye.set(o,n);}function J(){return M.unauthenticated?[M.unauthenticated]:[]}function Ee(){return M.authenticated?[M.authenticated]:[]}function Ce(t,e){let o=e.find(n=>!wt(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function wt(t,e){for(let o of t){let n=ye.get(o);if(n&&n.permissions.includes(e))return true}return false}var g=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:u=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=u;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var yt=z$1.string.bind(z$1),bt=z$1.number.bind(z$1),Et=z$1.date.bind(z$1),Ct=z$1.boolean.bind(z$1),xt=z$1.array.bind(z$1),St=z$1.object.bind(z$1),Rt=z$1.enum.bind(z$1),a={string:yt,number:bt,date:Et,boolean:Ct,array:xt,object:St,enum:Rt,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var v=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function xe(t){let e=t?await v.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Z()}async function Se(t,e){await v.updateOne({authToken:t},{$set:{userId:e}});}async function Re(t){await v.updateOne({authToken:t},{$set:{userId:null}});}async function Z(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a$1.days(7));return await v.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Mt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await v.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var De=new g("_system.session",{stores:[v],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await Mt(e);}}});var d=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),A=new f("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]}),_=new f("_modelenceEmailVerificationTokens",{schema:{userId:a.objectId(),email:a.string().optional(),token:a.string(),createdAt:a.date(),expiresAt:a.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),x=new f("_modelenceResetPasswordTokens",{schema:{userId:a.objectId(),token:a.string(),createdAt:a.date(),expiresAt:a.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});async function Me(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await A.findOne({domain:o})}var ve={interval:a$1.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
|
|
2
|
+
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await A.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var Q=Object.freeze({});function _e(t){Q=Object.freeze(Object.assign({},Q,t));}function h(){return Q}function vt(){return typeof window!="object"}function S(){if(!vt())throw new Error("This function can only be called on the server")}function q(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function Te({name:t,email:e,verificationUrl:o}){return `
|
|
3
3
|
<p>Hi${t?` ${t}`:""},</p>
|
|
4
4
|
<p>Please verify your email address ${e} by clicking the link below:</p>
|
|
5
5
|
<p><a href="${o}">${o}</a></p>
|
|
6
6
|
<p>If you did not request this, please ignore this email.</p>
|
|
7
|
-
`}async function
|
|
7
|
+
`}async function Oe(t){let e=process.env.MODELENCE_SITE_URL,o=h().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),i=await _.findOne({token:n,expiresAt:{$gt:new Date}});if(!i)throw new Error("Invalid or expired verification token");if(!await d.findOne({_id:i.userId}))throw new Error("User not found");let s=i.email;if(!s)throw new Error("Email not found in token");if((await d.updateOne({_id:i.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await d.findOne({_id:i.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await _.deleteOne({_id:i._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function B({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(h().provider){let n=h().provider,i=randomBytes(32).toString("hex"),r=new Date(Date.now()+a$1.hours(24));await _.insertOne({userId:t,email:e,token:i,createdAt:new Date,expiresAt:r});let s=`${o}/api/_internal/auth/verify-email?token=${i}`,u=(h()?.verification?.template||Te)({name:"",email:e,verificationUrl:s}),l=q(u);await n?.sendEmail({to:e,from:h()?.from||"noreply@modelence.com",subject:h()?.verification?.subject||"Verify your email address",text:l,html:u});}}function z(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function T(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}async function Ae(t,{user:e,session:o,connectionInfo:n}){if(!o)throw new Error("Session is not initialized");let i=n?.ip;i&&await R({bucket:"signin",type:"ip",value:i});let r=T(t.email),s=z$1.string().parse(t.password),c=await d.findOne({"emails.address":r},{collation:{locale:"en",strength:2}}),u=c?.authMethods?.password?.hash;if(!u)throw ke();if(!c.emails?.find(w=>w.address===r)?.verified&&h()?.provider){if(i)try{await R({bucket:"verification",type:"user",value:c._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await B({userId:c?._id,email:r,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await Ot.compare(s,u))throw ke();return await Se(o.authToken,c._id),{user:{id:c._id,handle:c.handle}}}async function Pe(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await Re(o.authToken);}function ke(){return new Error("Incorrect email/password combination")}async function Le(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await d.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var P=new f("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Y=[];function je(t){if(Y.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Y=t;}async function R(t){let{bucket:e,type:o,value:n}=t,i=Y.filter(r=>r.bucket===e&&r.type===o);for(let r of i)await kt(r,n);}async function kt(t,e,o){let n=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),i=await P.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:u}=i?At(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await P.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},u);}function At(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function $e(t,{user:e,connectionInfo:o}){let n=T(t.email),i=z(t.password),r=o?.ip;if(r&&await R({bucket:"signupAttempt",type:"ip",value:r}),await Me(n))throw new Error("Please use a permanent email address");let s=await d.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(s){let l=s.emails?.find(y=>y.address===n);throw new Error(`User with email already exists: ${l?.address}`)}r&&await R({bucket:"signup",type:"ip",value:r});let c=await Ot.hash(i,10),u=await d.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}});return await B({userId:u?.insertedId,email:n,baseUrl:o?.baseUrl}),u.insertedId}function Ut(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function Nt({email:t,resetUrl:e}){return `
|
|
8
8
|
<p>Hi,</p>
|
|
9
9
|
<p>We received a request to reset your password for ${t}.</p>
|
|
10
10
|
<p>Click the link below to reset your password:</p>
|
|
11
11
|
<p><a href="${e}">${e}</a></p>
|
|
12
12
|
<p>This link will expire in 1 hour.</p>
|
|
13
13
|
<p>If you did not request this password reset, please ignore this email.</p>
|
|
14
|
-
`}async function $e(t,{connectionInfo:e}){let o=z$1.string().email().parse(t.email),n=await d.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n)return {success:true,message:"If an account with that email exists, a password reset link has been sent"};if(!n.authMethods?.password)return {success:true,message:"If an account with that email exists, a password reset link has been sent"};let i=h().provider;if(!i)throw new Error("Email provider is not configured");let r=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(1));await x.insertOne({userId:n._id,token:r,createdAt:new Date,expiresAt:s});let c=process.env.MODELENCE_SITE_URL||e?.baseUrl,l=`${Lt(c,h().passwordReset?.redirectUrl)}?token=${r}`,w=(h()?.passwordReset?.template||jt)({email:o,resetUrl:l,name:""}),v=J(w);return await i.sendEmail({to:o,from:h()?.from||"noreply@modelence.com",subject:h()?.passwordReset?.subject||"Reset your password",text:v,html:w}),{success:true,message:"If an account with that email exists, a password reset link has been sent"}}async function Ue(t,{}){let e=z$1.string().parse(t.token),o=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),n=await x.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await x.deleteOne({token:e}),new Error("Reset token has expired");let i=await d.findOne({_id:n.userId});if(!i)throw new Error("User not found");let r=await vt.hash(o,10);return await d.updateOne({_id:i._id},{$set:{"authMethods.password.hash":r}}),await x.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Ne=new g("_system.user",{stores:[d,k,T,x],queries:{getOwnProfile:Ae},mutations:{signupWithPassword:je,loginWithPassword:Ie,logout:ke,sendResetPasswordToken:$e,resetPassword:Ue},cronJobs:{updateDisposableEmailList:De},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.minutes(15),limit:3},{bucket:"verification",type:"user",window:a$1.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Te}}]});async function Je({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await Y("/api/connect","POST",{hostname:$t.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function qe(){return await Y("/api/configs","GET")}async function Be(){return await Y("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Y(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var X=false,Ut=a$1.seconds(10);function ze(){setInterval(async()=>{if(!X){X=true;try{await Be();}catch(t){console.error("Error syncing status",t);}try{await Nt();}catch(t){console.error("Error syncing config",t);}X=false;}},Ut);}async function Nt(){let{configs:t}=await qe();c(t);}var Jt=a$1.minutes(1),qt=a$1.seconds(10),D={},ee,P=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ve(t,{description:e="",interval:o,timeout:n=Jt,handler:i}){if(D[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ee)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);D[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function We(){if(ee)throw new Error("Cron jobs already started");let t=Object.keys(D);if(t.length>0){let e={alias:{$in:t}},o=await P.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(r=>P.upsertOne({alias:r},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Bt(qt);let n=await P.fetch(e),i=Date.now();n.forEach(r=>{let s=D[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(D).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),ee=setInterval(zt,a$1.seconds(1));}}function Bt(t){return new Promise(e=>setTimeout(e,t))}async function zt(){let t=Date.now();Object.values(D).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Ft(e);});}async function Ft(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Fe(i,o),r.end("success");}).catch(s=>{Fe(i,o),k$1(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await P.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Fe(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function He(){return Object.values(D).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ke=new g("_system.cron",{stores:[P]});var b=null;async function Ge(){if(b)return b;let t=L();if(!t)throw new Error("MongoDB URI is not set");b=new MongoClient(t,{maxPoolSize:20});try{return await b.connect(),await b.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),b}catch(e){throw console.error(e),b=null,e}}function L(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ze(){return b}var te={};function oe(t,e){return S(),et(t),B("query",t,e)}function Qe(t,e){return S(),et(t),B("mutation",t,e)}function Ye(t,e){return S(),tt(t),B("query",t,e)}function Xe(t,e){return S(),tt(t),B("mutation",t,e)}function et(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function tt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function B(t,e,o){if(S(),te[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];te[e]={type:t,name:e,handler:n,permissions:i};}async function ot(t,e,o){S();let n=te[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{be(o.roles,n.permissions),c=await r(e,o);}catch(u){throw s.end("error"),u}return s.end(),c}var z=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function nt(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await z.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await z.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var rt=new g("_system.migration",{stores:[z]});var it=new g("_system.rateLimit",{stores:[A]});var re=class{async init(){this.config=await Yt(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(this.config),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[se.static("./.modelence/build/client")];return this.config?.publicDir&&e.push(se.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Qt(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}async function Yt(){let t=process.cwd(),e=await Qt(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Zt.existsSync(ne.join(t,i))),n=[Gt(),Xt()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:ne.resolve(t,o)}));}return {plugins:n,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":ne.resolve(t,"src")}},publicDir:e.publicDir}}function Xt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var at=new re;async function ct(t,e){let{authToken:o}=await K(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function oo(t,e){let o=t.user,n=await d.findOne({"authMethods.google.id":o.id});if(n){await ct(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await d.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await d.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await ct(e,s.insertedId);}function no(){let t=Router(),e=!!a$2("_system.user.auth.google.enabled"),o=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret"));return !e||!o||!n||(ie.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",ie.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",ie.authenticate("google",{session:false}),oo)),t}var lt=no;function mt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function dt(t){let e=await Ee(t),o=e.userId?await d.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?ye():N();return {user:n,session:e,roles:i}}function co(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,mt(c));});}}async function ut(t,{combinedModules:e}){let o=se();o.use(se.json()),o.use(se.urlencoded({extended:true})),o.use(io()),o.use(ie.initialize()),o.use(lt()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,u=await lo(r);try{let l=await ot(c,r.body.args,u);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let w=l.flatten(),v=Object.entries(w.fieldErrors).map(([F,V])=>`${F}: ${(V??[]).join(", ")}`).join("; "),j=w.formErrors.join("; "),O=[v,j].filter(Boolean).join("; ");s.status(400).send(O);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),co(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=so.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`
|
|
14
|
+
`}var X={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Ue(t,{connectionInfo:e}){let o=T(t.email),n=await d.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return X;let i=h().provider;if(!i)throw new Error("Email provider is not configured");let r=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(1));await x.insertOne({userId:n._id,token:r,createdAt:new Date,expiresAt:s});let c=process.env.MODELENCE_SITE_URL||e?.baseUrl,l=`${Ut(c,h().passwordReset?.redirectUrl)}?token=${r}`,w=(h()?.passwordReset?.template||Nt)({email:o,resetUrl:l,name:""}),O=q(w);return await i.sendEmail({to:o,from:h()?.from||"noreply@modelence.com",subject:h()?.passwordReset?.subject||"Reset your password",text:O,html:w}),X}async function Ne(t,{}){let e=z$1.string().parse(t.token),o=z(t.password),n=await x.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await x.deleteOne({token:e}),new Error("Reset token has expired");let i=await d.findOne({_id:n.userId});if(!i)throw new Error("User not found");let r=await Ot.hash(o,10);return await d.updateOne({_id:i._id},{$set:{"authMethods.password.hash":r}}),await x.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Je=new g("_system.user",{stores:[d,A,_,x],queries:{getOwnProfile:Le},mutations:{signupWithPassword:$e,loginWithPassword:Ae,logout:Pe,sendResetPasswordToken:Ue,resetPassword:Ne},cronJobs:{updateDisposableEmailList:ve},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.minutes(15),limit:3},{bucket:"verification",type:"user",window:a$1.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Oe}}]});async function qe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await ee("/api/connect","POST",{hostname:Jt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Be(){return await ee("/api/configs","GET")}async function ze(){return await ee("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ee(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var te=false,qt=a$1.seconds(10);function Fe(){setInterval(async()=>{if(!te){te=true;try{await ze();}catch(t){console.error("Error syncing status",t);}try{await Bt();}catch(t){console.error("Error syncing config",t);}te=false;}},qt);}async function Bt(){let{configs:t}=await Be();c(t);}var zt=a$1.minutes(1),Ft=a$1.seconds(10),D={},oe,L=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function We(t,{description:e="",interval:o,timeout:n=zt,handler:i}){if(D[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(oe)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);D[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function He(){if(oe)throw new Error("Cron jobs already started");let t=Object.keys(D);if(t.length>0){let e={alias:{$in:t}},o=await L.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(r=>L.upsertOne({alias:r},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Vt(Ft);let n=await L.fetch(e),i=Date.now();n.forEach(r=>{let s=D[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(D).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),oe=setInterval(Wt,a$1.seconds(1));}}function Vt(t){return new Promise(e=>setTimeout(e,t))}async function Wt(){let t=Date.now();Object.values(D).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Ht(e);});}async function Ht(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j$1("cron",`cron:${e}`);n().then(()=>{Ve(i,o),r.end("success");}).catch(s=>{Ve(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await L.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Ve(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Ke(){return Object.values(D).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ge=new g("_system.cron",{stores:[L]});var b=null;async function Ze(){if(b)return b;let t=j();if(!t)throw new Error("MongoDB URI is not set");b=new MongoClient(t,{maxPoolSize:20});try{return await b.connect(),await b.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),b}catch(e){throw console.error(e),b=null,e}}function j(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Qe(){return b}var ne={};function re(t,e){return S(),tt(t),F("query",t,e)}function Ye(t,e){return S(),tt(t),F("mutation",t,e)}function Xe(t,e){return S(),ot(t),F("query",t,e)}function et(t,e){return S(),ot(t),F("mutation",t,e)}function tt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ot(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function F(t,e,o){if(S(),ne[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];ne[e]={type:t,name:e,handler:n,permissions:i};}async function nt(t,e,o){S();let n=ne[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j$1("method",`method:${t}`,{type:i,args:e}),c;try{Ce(o.roles,n.permissions),c=await r(e,o);}catch(u){throw s.end("error"),u}return s.end(),c}var V=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function rt(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await V.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await V.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var it=new g("_system.migration",{stores:[V]});var st=new g("_system.rateLimit",{stores:[P]});var se=class{async init(){this.config=await to(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(this.config),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ce.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ce.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function eo(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}async function to(){let t=process.cwd(),e=await eo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Xt.existsSync(ie.join(t,i))),n=[Yt(),oo()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:ie.resolve(t,o)}));}return {plugins:n,root:t,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":ie.resolve(t,"src").replace(/\\/g,"/")}},publicDir:e.publicDir}}function oo(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var ct=new se;async function lt(t,e){let{authToken:o}=await Z(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function io(t,e){let o=t.user,n=await d.findOne({"authMethods.google.id":o.id});if(n){await lt(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await d.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await d.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await lt(e,s.insertedId);}function so(){let t=Router(),e=!!a$2("_system.user.auth.google.enabled"),o=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret"));return !e||!o||!n||(ae.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",ae.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",ae.authenticate("google",{session:false}),io)),t}var mt=so;function dt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function ut(t){let e=await xe(t),o=e.userId?await d.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?Ee():J();return {user:n,session:e,roles:i}}function uo(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,dt(c));});}}async function pt(t,{combinedModules:e}){let o=ce();o.use(ce.json()),o.use(ce.urlencoded({extended:true})),o.use(co()),o.use(ae.initialize()),o.use(mt()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,u=await po(r);try{let l=await nt(c,r.body.args,u);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let w=l.flatten(),O=Object.entries(w.fieldErrors).map(([W,H])=>`${W}: ${(H??[]).join(", ")}`).join("; "),$=w.formErrors.join("; "),I=[O,$].filter(Boolean).join("; ");s.status(400).send(I);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),uo(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=lo.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`
|
|
15
15
|
Application started on http://localhost:${i}
|
|
16
|
-
`);});}async function
|
|
17
|
-
export{g as Module,f as Store,R as consumeRateLimit,
|
|
16
|
+
`);});}async function po(t){let e=E.string().nullish().transform(r=>r??null).parse(t.cookies.authToken||t.body.authToken),o=E.object({screenWidth:E.number(),screenHeight:E.number(),windowWidth:E.number(),windowHeight:E.number(),pixelRatio:E.number(),orientation:E.string().nullable()}).parse(t.body.clientInfo),n={ip:fo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!j()){let{session:r,user:s,roles:c}=await ut(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:J()}}function fo(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function yo({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=ct,migrations:i=[],email:r={}}){ft.config(),ft.config({path:".modelence.env"});let s=!!process.env.MODELENCE_SERVICE_ENDPOINT,c$1=process.env.MODELENCE_CRON_ENABLED==="true";To().then(()=>{}).catch(()=>{});let u=[Je,De,Ge,it,st],l=[...u,...t];e(),Eo(u),bo(t),be(e$1,o);let y=So(l);d$2(y);let w=Co(l);c$1&&Ro(l);let O=xo(l);if(je(O),s){let{configs:I,environmentId:W,appAlias:H,environmentAlias:ht,telemetry:gt}=await qe({configSchema:y,cronJobsMetadata:c$1?Ke():void 0,stores:w});c(I),f$1({environmentId:W,appAlias:H,environmentAlias:ht,telemetry:gt});}else c(_o(y));_e(r);let $=j();if($&&(await Ze(),Do(w)),c$1&&await rt(i),$)for(let I of w)I.createIndexes();s&&(await g$1(),Fe()),c$1&&He().catch(console.error),await pt(n,{combinedModules:l});}function bo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))re(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ye(`${e.name}.${o}`,n);}}function Eo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))et(`${e.name}.${o}`,n);}}function Co(t){return t.flatMap(e=>e.stores)}function xo(t){return t.flatMap(e=>e.rateLimits)}function So(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Ro(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))We(`${e.name}.${o}`,n);}function Do(t){let e=Qe();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Mo={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function vo(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function _o(t){let e=[];for(let[o,n]of Object.entries(Mo)){let i=process.env[o],r=t[n];if(i){let s=r?.type??"string";e.push({key:n,type:s,value:vo(i,s)});}}return e}async function To(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Oo(),i=await import('./package-4RSIRWA5.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:i.default.version,localHostname:Jt.hostname(),environmentId:o})});}}async function Oo(){try{let t=ie.join(process.cwd(),"package.json"),e=await ho.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}
|
|
17
|
+
export{g as Module,f as Store,R as consumeRateLimit,re as createQuery,d as dbUsers,a as schema,yo as startApp};//# sourceMappingURL=server.js.map
|
|
18
18
|
//# sourceMappingURL=server.js.map
|