modelence 0.4.10 → 0.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/modelence.js +3 -10
- package/dist/bin/modelence.js.map +1 -1
- package/dist/client.d.ts +18 -11
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/package-DF3VLPXG.js +3 -0
- package/dist/package-DF3VLPXG.js.map +1 -0
- package/dist/server.d.ts +42 -0
- package/dist/server.js +3 -3
- package/dist/server.js.map +1 -1
- package/package.json +2 -1
package/dist/bin/modelence.js
CHANGED
|
@@ -1,12 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import
|
|
3
|
-
`);await promises.writeFile(
|
|
4
|
-
`),console.log(`Successfully configured ${v} file`);}catch(
|
|
5
|
-
Successfully created ${e}!
|
|
6
|
-
|
|
7
|
-
Get started by typing:
|
|
8
|
-
|
|
9
|
-
cd ${e}
|
|
10
|
-
npm run dev
|
|
11
|
-
`);}catch(r){throw c.existsSync(n)&&c.removeSync(n),r.status===404?new Error(`Template "${o}" not found in ${ge}`):r}}async function I(e,t,o,n){for(let r of t){let s=S.join(n,r.name);if(r.type==="dir"){c.mkdirSync(s);let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});Array.isArray(a.data)&&await I(e,a.data,`${o}/${r.name}`,s);}else {let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});if("content"in a.data&&typeof a.data.content=="string"){let i=Buffer.from(a.data.content,"base64").toString();await c.writeFile(s,i);}}}}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.command("create-app <project-name>").description("Create a new Modelence application").option("-t, --template <template-name>","Template to use (from examples repository)").action(async(e,t)=>{await j(e,{template:t.template});});m.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 $(e);});m.command("build").description("Build the application").action(async()=>{await h(),await E();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await h(),await M(e);});m.command("dev").description("Start development server").action(async()=>{await h(),B();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
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 v=".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 _(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${v} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function F(e){return String(e).replace(/"/g,'\\"')}async function L(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(),v),t={};try{let c=await promises.readFile(o,"utf8");t=parse(c),await L(o),await _()||(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(([c,n])=>`${c}="${F(n)}"`).join(`
|
|
3
|
+
`);await promises.writeFile(o,s.trim()+`
|
|
4
|
+
`),console.log(`Successfully configured ${v} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var y=null,C=null;function z(){if(!y)throw new Error("Environment variables not loaded");return y}function k(){if(!C)throw new Error("Configuration not loaded");return C}function d(e){let o=z().MODELENCE_SERVICE_ENDPOINT;if(!o)throw new Error("MODELENCE_SERVICE_ENDPOINT not found in environment variables");return `${o}${e}`}function g(){let{serverDir:e,serverEntry:o}=k();return join(e,o)}function D(){return k().postBuildCommand}function S(e){let o=b("build");return o}function u(e){return join(process.cwd(),e)}function b(e){let o=u(".modelence");return e?join(o,e):o}async function w(){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");C=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");y=parse(e);}catch(e){if(e.code!=="ENOENT")throw e}}async function X(){let e=D();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:[g()],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 E(){console.log("Building Modelence project...");try{let e=S();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(b());}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 P(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await E(),await ie(r);let{token:i}=await T(),{bundleName:s}=await se(e.env,r,i);await promises.unlink(r),await ce(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,N)=>{o.on("close",n),o.on("error",N),t.on("error",N);});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 c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function se(e,o,t){let r=await fetch(d(`/api/environments/${e}/upload`),{method:"POST",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:i,bundleName:s}=await r.json(),c=await promises.readFile(o),n=await fetch(i,{method:"PUT",body:c,headers:{"Content-Type":"application/zip"}});if(!n.ok)throw new Error(`Failed to upload bundle: ${n.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${s}`),{bundleName:s}}async function ce(e,o,t,r){let i=await fetch(d(`/api/environments/${e}/deploy`),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({bundleName:o,entryPoint:t})});if(!i.ok)throw new Error(`Failed to trigger deployment: ${i.statusText}`);let{deploymentUrl:s}=await i.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${s}`);}function B(){console.log("Starting Modelence dev server...");let e=g(),o=G.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.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);});m.command("build").description("Build the application").action(async()=>{await w(),await E();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await w(),await P(e);});m.command("dev").description("Start development server").action(async()=>{await w(),B();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
12
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/create-app.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","studioBaseUrl","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","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","EXAMPLES_REPO","DEFAULT_TEMPLATE","createApp","projectName","template","projectPath","octokit","Octokit","downloadTemplateFiles","packageJsonPath","packageJson","contents","templateName","targetPath","item","itemPath","dirContents","fileContent","content","program","Command"],"mappings":";8eAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAA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,CAAQ,OAAO,CAAA,CACf,WAAY,CAAA,uCAAuC,CACnD,CAAA,cAAA,CAAe,sBAAuB,uBAAuB,CAAA,CAC7D,MAAO,CAAA,mBAAA,CAAqB,gBAAkB,CAAA,6BAA6B,CAC3E,CAAA,MAAA,CAAO,MAAOnG,CAAY,EAAA,CACzB,MAAMD,CAAAA,CAAMC,CAAO,EACrB,CAAC,CAAA,CAEHmG,CACG,CAAA,OAAA,CAAQ,OAAO,CAAA,CACf,WAAY,CAAA,uBAAuB,CACnC,CAAA,MAAA,CAAO,SAAY,CAClB,MAAM3E,CAAQ,EAAA,CACd,MAAMmB,CAAAA,GACR,CAAC,EAEHwD,CACG,CAAA,OAAA,CAAQ,QAAQ,CAAA,CAChB,WAAY,CAAA,2BAA2B,CACvC,CAAA,cAAA,CAAe,kBAAmB,gCAAgC,CAAA,CAClE,MAAO,CAAA,MAAOnG,CAAY,EAAA,CACzB,MAAMwB,CAAAA,EACN,CAAA,MAAM6B,CAAOrD,CAAAA,CAAO,EACtB,CAAC,CAEHmG,CAAAA,CAAAA,CACG,QAAQ,KAAK,CAAA,CACb,WAAY,CAAA,0BAA0B,CACtC,CAAA,MAAA,CAAO,SAAY,CAClB,MAAM3E,CAAQ,EAAA,CACdqD,CAAI,GACN,CAAC,CAAA,CAEHsB,CAAQ,CAAA,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;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\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 } 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: { 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.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(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(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\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(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\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","import { Octokit } from '@octokit/rest';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nconst EXAMPLES_REPO = 'modelence/examples';\nconst DEFAULT_TEMPLATE = 'empty-project';\n\ninterface CreateAppOptions {\n template?: string;\n}\n\nexport async function createApp(projectName: string, options: CreateAppOptions = {}) {\n const template = options.template || DEFAULT_TEMPLATE;\n \n console.log(`Creating new Modelence app: ${projectName}`);\n console.log(`Using template: ${template}`);\n\n // Validate project name\n if (!/^[a-zA-Z0-9-_]+$/.test(projectName)) {\n throw new Error('Project name can only contain letters, numbers, dashes and underscores');\n }\n\n const projectPath = path.resolve(process.cwd(), projectName);\n\n // Check if directory already exists\n if (fs.existsSync(projectPath)) {\n throw new Error(`Directory ${projectName} already exists`);\n }\n\n try {\n // Initialize Octokit\n const octokit = new Octokit();\n\n // Get template contents from GitHub\n const response = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: template,\n });\n\n if (!Array.isArray(response.data)) {\n throw new Error('Invalid template structure');\n }\n\n // Create project directory\n fs.mkdirSync(projectPath);\n\n // Download and extract template files\n await downloadTemplateFiles(octokit, response.data, template, projectPath);\n\n // Update package.json\n const packageJsonPath = path.join(projectPath, 'package.json');\n const packageJson = await fs.readJson(packageJsonPath);\n packageJson.name = projectName;\n await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });\n\n // Install dependencies\n console.log('Installing dependencies...');\n execSync('npm install', { cwd: projectPath, stdio: 'inherit' });\n\n console.log(`\nSuccessfully created ${projectName}!\n\nGet started by typing:\n\n cd ${projectName}\n npm run dev\n `);\n\n } catch (error: any) {\n // Clean up on error\n if (fs.existsSync(projectPath)) {\n fs.removeSync(projectPath);\n }\n\n if (error.status === 404) {\n throw new Error(`Template \"${template}\" not found in ${EXAMPLES_REPO}`);\n }\n throw error;\n }\n}\n\nasync function downloadTemplateFiles(octokit: Octokit, contents: any[], templateName: string, targetPath: string) {\n for (const item of contents) {\n const itemPath = path.join(targetPath, item.name);\n\n if (item.type === 'dir') {\n fs.mkdirSync(itemPath);\n const dirContents = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n if (Array.isArray(dirContents.data)) {\n await downloadTemplateFiles(octokit, dirContents.data, `${templateName}/${item.name}`, itemPath);\n }\n } else {\n const fileContent = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n \n if ('content' in fileContent.data && typeof fileContent.data.content === 'string') {\n const content = Buffer.from(fileContent.data.content, 'base64').toString();\n await fs.writeFile(itemPath, content);\n }\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 { createApp } from './create-app';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\n// Commands that don't need config\nprogram\n .command('create-app <project-name>')\n .description('Create a new Modelence application')\n .option('-t, --template <template-name>', 'Template to use (from examples repository)')\n .action(async (projectName, options) => {\n await createApp(projectName, {\n template: options.template\n });\n });\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('-e, --env <env>', 'Environment (deployment 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","studioBaseUrl","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","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";wbAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAKC,CAAAA,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAQ,CAAA,KAAA,CACf,MAAQ,CAAA,OAAA,CAAQ,MAClB,CAAC,CAED,CAAA,OAAO,IAAI,OAAA,CAASC,CAAY,EAAA,CAC9BF,CAAG,CAAA,QAAA,CAAS,CAAYP,SAAAA,EAAAA,CAAkB,uDAAyDU,CAAW,EAAA,CAC5GH,CAAG,CAAA,KAAA,EACHE,CAAAA,CAAAA,CAAQC,CAAO,CAAA,WAAA,EAAkB,GAAA,GAAG,EACtC,CAAC,EACH,CAAC,CACH,CAEA,SAASC,CAAAA,CAAeC,CAAgC,CAAA,CAEtD,OAAO,M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OAAO,CAAA,CAElBD,EACG,OAAQ,CAAA,OAAO,EACf,WAAY,CAAA,uCAAuC,EACnD,cAAe,CAAA,qBAAA,CAAuB,uBAAuB,CAAA,CAC7D,OAAO,mBAAqB,CAAA,gBAAA,CAAkB,6BAA6B,CAAA,CAC3E,OAAO,MAAOhF,CAAAA,EAAY,CACzB,MAAMD,EAAMC,CAAO,EACrB,CAAC,CAAA,CAEHgF,EACG,OAAQ,CAAA,OAAO,CACf,CAAA,WAAA,CAAY,uBAAuB,CACnC,CAAA,MAAA,CAAO,SAAY,CAClB,MAAMxD,CAAQ,EAAA,CACd,MAAMmB,CAAAA,GACR,CAAC,CAAA,CAEHqC,CACG,CAAA,OAAA,CAAQ,QAAQ,CAChB,CAAA,WAAA,CAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAmB,CAAA,gCAAgC,CAClE,CAAA,MAAA,CAAO,MAAOhF,CAAY,EAAA,CACzB,MAAMwB,CAAAA,GACN,MAAM6B,CAAAA,CAAOrD,CAAO,EACtB,CAAC,CAEHgF,CAAAA,CAAAA,CACG,OAAQ,CAAA,KAAK,EACb,WAAY,CAAA,0BAA0B,CACtC,CAAA,MAAA,CAAO,SAAY,CAClB,MAAMxD,CAAQ,EAAA,CACdqD,IACF,CAAC,EAEHG,CAAQ,CAAA,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;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\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 } 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: { 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.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(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(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\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(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\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('-e, --env <env>', 'Environment (deployment 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"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { a as ConfigKey } from './types-RXrmChkk.js';
|
|
2
2
|
import React from 'react';
|
|
3
|
+
import * as _tanstack_react_query from '@tanstack/react-query';
|
|
3
4
|
|
|
4
5
|
declare function getConfig(key: ConfigKey): string | number | boolean;
|
|
5
6
|
|
|
@@ -12,12 +13,21 @@ declare function renderApp({ loadingElement, routesElement, favicon, errorHandle
|
|
|
12
13
|
errorHandler?: ErrorHandler;
|
|
13
14
|
}): void;
|
|
14
15
|
|
|
16
|
+
/**
|
|
17
|
+
* @group React Hooks
|
|
18
|
+
* Client-side React hooks for data fetching and mutations
|
|
19
|
+
*/
|
|
15
20
|
type Args = Record<string, unknown>;
|
|
16
21
|
type MethodResult<T> = {
|
|
17
22
|
isFetching: boolean;
|
|
18
23
|
error: Error | null;
|
|
19
24
|
data: T | null;
|
|
20
25
|
};
|
|
26
|
+
type PlaceholderData<T> = T | ((prev: T | null) => T);
|
|
27
|
+
type QueryOptions<T> = {
|
|
28
|
+
enabled?: boolean;
|
|
29
|
+
placeholderData?: PlaceholderData<T>;
|
|
30
|
+
};
|
|
21
31
|
declare function callMethod<T = unknown>(methodName: string, args?: Args): Promise<T>;
|
|
22
32
|
/**
|
|
23
33
|
* React hook for executing a query method.
|
|
@@ -51,9 +61,7 @@ declare function callMethod<T = unknown>(methodName: string, args?: Args): Promi
|
|
|
51
61
|
* }
|
|
52
62
|
* ```
|
|
53
63
|
*/
|
|
54
|
-
declare function useQuery<T = unknown>(methodName: string, args?: Args, options?: {
|
|
55
|
-
enabled?: boolean;
|
|
56
|
-
}): MethodResult<T> & {
|
|
64
|
+
declare function useQuery<T = unknown>(methodName: string, args?: Args, options?: QueryOptions<T>): MethodResult<T> & {
|
|
57
65
|
/** Function to manually trigger a refetch of the query with optional new arguments */
|
|
58
66
|
refetch: (args?: Args) => void;
|
|
59
67
|
};
|
|
@@ -81,14 +89,13 @@ declare function useQuery<T = unknown>(methodName: string, args?: Args, options?
|
|
|
81
89
|
* updateTodo({ id: '123', name: 'New Name' });
|
|
82
90
|
* ```
|
|
83
91
|
*/
|
|
84
|
-
declare function useMutation<T = unknown>(methodName: string, args?: Args):
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
mutateAsync: (args?: Args) => Promise<T>;
|
|
92
|
+
declare function useMutation<T = unknown>(methodName: string, args?: Args): {
|
|
93
|
+
data: NonNullable<T> | null;
|
|
94
|
+
error: Error | null;
|
|
95
|
+
isFetching: boolean;
|
|
96
|
+
isPending: boolean;
|
|
97
|
+
mutate: _tanstack_react_query.UseMutateFunction<T, Error, Args | undefined, unknown>;
|
|
98
|
+
mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<T, Error, Args | undefined, unknown>;
|
|
92
99
|
};
|
|
93
100
|
|
|
94
101
|
type User$1 = {
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a}from'./chunk-R7MPLJMA.js';import
|
|
1
|
+
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import M,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {QueryClient,QueryClientProvider,useQuery,useMutation}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';import J from'react-dom/client';function g(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function m(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var h=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function w(e){h=e;}function y(e,r){return h(e,r)}async function n(e,r={}){try{return await b(`/api/_internal/method/${e}`,r)}catch(t){throw y(t,e),t}}async function b(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:g()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!t.ok){let s=await t.text();throw new Error(s)}let o=await t.text(),i=o?JSON.parse(o):void 0;if(!i)throw new Error("Invalid response from server");return b$1(i.data,i.typeMap)}function k(e,r={},t){let o=useQuery({queryKey:[e,r],queryFn:()=>n(e,r),enabled:t?.enabled??true,placeholderData:t?.placeholderData});return {data:o.data??null,error:o.error,isFetching:o.isFetching,refetch:()=>o.refetch()}}function L(e,r={}){let t=useMutation({mutationFn:(o={})=>n(e,{...r,...o})});return {data:t.data??null,error:t.error,isFetching:t.isPending,isPending:t.isPending,mutate:t.mutate,mutateAsync:t.mutateAsync}}var a={};function O(e){if(!(e in a))throw new Error(`Unknown config: ${e}`);return a[e]?.value}function S(e){a=e;}var u=create(e=>({user:null,setUser:r=>e({user:r})})),E=false,I=a$1.seconds(30);async function T(){if(E)return;E=true;let{configs:e,session:r,user:t}=await n("_system.session.init");S(e),m(r);let o=t?Object.freeze(z$1.object({id:z$1.string(),handle:z$1.string()}).parse(t)):null;u.getState().setUser(o),await x();}async function x(){await n("_system.session.heartbeat"),setTimeout(x,I);}function c(e){u.getState().setUser(e);}function N(){return {user:u(r=>r.user)}}var P=false,K=new QueryClient;function d({children:e,loadingElement:r}){let[t,o]=useState(true);return useEffect(()=>{async function i(){P||(P=true,await T(),o(false));}i();},[]),t?r??jsx("div",{children:"Loading..."}):jsx(QueryClientProvider,{client:K,children:e})}function j({loadingElement:e,routesElement:r,favicon:t,errorHandler:o}){if(o&&w(o),window.addEventListener("unload",()=>{}),J.createRoot(document.getElementById("root")).render(jsx(M.StrictMode,{children:jsx(v,{loadingElement:e,children:r})})),t){let i=document.querySelector("link[rel~='icon']");if(i)i.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}async function z({email:e,password:r}){await n("_system.user.signupWithPassword",{email:e,password:r}),await R({email:e,password:r});}async function R({email:e,password:r}){let{user:t}=await n("_system.user.loginWithPassword",{email:e,password:r});return c(t),t}async function $(){await n("_system.user.logout"),c(null);}var v="useClient"in M?M.useClient(d):d;export{v as AppProvider,n as callMethod,O as getConfig,R as loginWithPassword,$ as logout,j as renderApp,z as signupWithPassword,L as useMutation,k as useQuery,N as useSession};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","triggerMethod","useMethod","useMutation","stableArgs","useMemo","stableOptions","setResult","useState","data","useEffect","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","initConfig","jsx","Fragment","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"qQAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAQ,CAAA,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAASC,MAAAA,CAAAA,CAAG,CACV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CACdA,EAAQ,IAAOJ,CAAAA,CAAAA,CACf,SAAS,IAAK,CAAA,WAAA,CAAYI,CAAO,EACnC,CAGF,CACF,CC/BA,eAAsBC,CAAAA,CAAmB,CAAE,KAAAC,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CACjG,MAAMxD,CAAAA,CAAW,iCAAmC,CAAA,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAC,EAGvE,MAAMC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,EAC7C,CAEA,eAAsBC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CAChG,GAAM,CAAE,KAAA5B,CAAK,CAAA,CAAI,MAAM5B,CAA2B,CAAA,gCAAA,CAAkC,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,CAAA,CACvG,OAAApB,CAAeR,CAAAA,CAAI,EACZA,CACT,CAEA,eAAsB8B,CAAS,EAAA,CAC7B,MAAM1D,CAAAA,CAAW,qBAAqB,CAAA,CACtCoC,EAAe,IAAI,EACrB,CClBaG,IAAAA,CAAAA,CAAc,cAAeY,CAEtCA,CAAAA,CAAAA,CAAM,SAAUZ,CAAAA,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { useState, useEffect, useMemo } from 'react';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(methodName: string, args: Args = {}, options?: { enabled?: boolean }): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: options?.enabled ?? true });\n return {\n ...result,\n refetch: (args?: Args) => triggerMethod(args),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}): MethodResult<T> & {\n /** Function to trigger the mutation with optional arguments */\n mutate: (args?: Args) => void,\n /** \n * Async version of mutate that returns a promise with the result.\n * Useful when you need to wait for the mutation to complete.\n */\n mutateAsync: (args?: Args) => Promise<T>\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: false });\n return {\n ...result,\n mutate: (args?: Args) => triggerMethod(args),\n mutateAsync: triggerMethod,\n };\n}\n\nexport function useMethod<T>(methodName: string, args: Args = {}, options: { enabled: boolean }): {\n result: MethodResult<T>,\n triggerMethod: (args?: Args) => Promise<T>\n} {\n // Memoize the args object to maintain reference stability and prevent infinite re-renders\n const stableArgs = useMemo(() => args, [JSON.stringify(args)]);\n const stableOptions = useMemo(() => options, [JSON.stringify(options)]);\n\n const [result, setResult] = useState<MethodResult<T>>({\n isFetching: options.enabled,\n error: null,\n data: null,\n });\n\n const triggerMethod = async (args: Args = stableArgs) => {\n setResult({ isFetching: true, error: null, data: result.data });\n try {\n const data = await callMethod<T>(methodName, args);\n setResult({ isFetching: false, error: null, data });\n return data;\n } catch (error) {\n setResult({ isFetching: false, error: error as Error, data: null });\n throw error;\n }\n };\n\n // TODO: switch to React Query (TanStack Query)\n useEffect(() => {\n if (!options.enabled) {\n return;\n }\n\n triggerMethod();\n }, [methodName, stableArgs, stableOptions]);\n\n return { result, triggerMethod };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return <>{children}</>;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","query","useTanQuery","useMutation","mutation","useTanMutation","newArgs","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","queryClient","QueryClient","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","QueryClientProvider","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"oVAAO,SAASA,CAAyB,EAAA,CACvC,IAAMC,CAAc,CAAA,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,EAAc,IAAK,CAAA,KAAA,CAAMA,CAAW,CAAI,CAAA,IACjD,OAASC,CAAG,CAAA,CACV,OAAQ,OAAA,CAAA,KAAA,CAAM,0CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAuBC,CAAAA,CAAAA,CAAiB,CACtD,YAAA,CAAa,QAAQ,mBAAqB,CAAA,IAAA,CAAK,UAAUA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAA6B,CAAA,CAACC,EAAOC,CAAe,GAAA,CACtD,MAAM,IAAI,KAAA,CAAM,yBAAyBA,CAAU,CAAA,GAAA,EAAMD,EAAM,QAAS,EAAC,EAAE,CAC7E,CAAA,CAEO,SAASE,CAAgBC,CAAAA,CAAAA,CAAuB,CACrDJ,CAAeI,CAAAA,EACjB,CAEO,SAASC,EAAYJ,CAAcC,CAAAA,CAAAA,CAAoB,CAC5D,OAAOF,CAAAA,CAAaC,EAAOC,CAAU,CACvC,CCsBA,eAAsBI,EAAwBJ,CAAoBK,CAAAA,CAAAA,CAAa,EAAgB,CAAA,CAC7F,GAAI,CACF,OAAO,MAAMC,CAAAA,CAAQ,yBAAyBN,CAAU,CAAA,CAAA,CAAIK,CAAI,CAClE,CAAA,MAASN,EAAO,CACd,MAAAI,EAAYJ,CAAgBC,CAAAA,CAAU,EAChCD,CACR,CACF,CAEA,eAAeO,CAAAA,CAAkBC,EAAkBF,CAAwB,CAAA,CACzE,IAAMG,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ChG,GAAM,CAAE,IAAA,CAAAhC,CAAK,CAAI,CAAA,MAAMxB,EAA2B,gCAAkC,CAAA,CAAE,MAAAuD,CAAO,CAAA,QAAA,CAAAC,CAAS,CAAC,CAAA,CACvG,OAAAxB,CAAeR,CAAAA,CAAI,CACZA,CAAAA,CACT,CAEA,eAAsBkC,CAAAA,EAAS,CAC7B,MAAM1D,CAAAA,CAAW,qBAAqB,CACtCgC,CAAAA,CAAAA,CAAe,IAAI,EACrB,KClBaK,CAAc,CAAA,WAAA,GAAec,EAEtCA,CAAM,CAAA,SAAA,CAAUd,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/**\n * @group React Hooks\n * Client-side React hooks for data fetching and mutations\n */\n\n/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { useQuery as useTanQuery, useMutation as useTanMutation } from '@tanstack/react-query';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\ntype PlaceholderData<T> = T | ((prev: T | null) => T);\n\ntype QueryOptions<T> = {\n enabled?: boolean;\n placeholderData?: PlaceholderData<T>;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(\n methodName: string, \n args: Args = {}, \n options?: QueryOptions<T>\n): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n type QueryKey = [string, Args];\n \n const query = useTanQuery<T, Error, T, QueryKey>({\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n enabled: options?.enabled ?? true,\n placeholderData: options?.placeholderData as any\n });\n\n return {\n data: query.data ?? null,\n error: query.error as Error | null,\n isFetching: query.isFetching,\n refetch: () => query.refetch(),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}) {\n const mutation = useTanMutation({\n mutationFn: (newArgs: Args = {}) => callMethod<T>(methodName, { ...args, ...newArgs }),\n });\n\n return {\n data: mutation.data ?? null,\n error: mutation.error as Error | null,\n isFetching: mutation.isPending, // Legacy\n isPending: mutation.isPending,\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport const queryClient = new QueryClient();\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return (\n <QueryClientProvider client={queryClient}>\n {children}\n </QueryClientProvider>\n );\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var s="module",i="modelence",n="0.4.12",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./mongodb":"./dist/mongo.js"},d=["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/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@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",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@tanstack/react-query":"^5.76.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",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",tsup:"^8.3.6",tsx:"^4.19.3",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:n,description:o,main:p,types:r,exports:c,files:d,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,o as description,b as devDependencies,c as exports,d as files,h as homepage,g as license,p as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-DF3VLPXG.js.map
|
|
3
|
+
//# sourceMappingURL=package-DF3VLPXG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,QAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,WAAA,CAAa,iBACf,CAAA,CACAC,EAAS,CACP,MAAA,CACA,UACF,CACAC,CAAAA,CAAAA,CAAO,CACL,SAAa,CAAA,yBACf,EACAC,CAAW,CAAA,CACT,MAAS,MACT,CAAA,GAAA,CAAO,eACP,cAAkB,CAAA,eAAA,CAClB,KAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CAAA,CACAC,EAAc,CACZ,IAAA,CAAQ,MACR,GAAO,CAAA,gDACT,EACAC,CAAU,CAAA,WAAA,CACVC,EAAW,wBACXC,CAAAA,CAAAA,CAAQ,CACN,GAAO,CAAA,+CACT,EACAC,CAAY,CAAA,uBAAA,CACZC,EAAmB,CACjB,iBAAA,CAAmB,QACnB,CAAA,eAAA,CAAiB,SACjB,gBAAkB,CAAA,QAAA,CAClB,kBAAmB,SACnB,CAAA,aAAA,CAAe,UACf,cAAgB,CAAA,SAAA,CAChB,mBAAoB,SACpB,CAAA,kCAAA,CAAoC,UACpC,2BAA6B,CAAA,SAAA,CAC7B,MAAS,SACT,CAAA,WAAA,CAAa,UACb,UAAc,CAAA,QAChB,CACAC,CAAAA,CAAAA,CAAgB,CACd,eAAiB,CAAA,SAAA,CACjB,wBAAyB,SACzB,CAAA,sBAAA,CAAwB,SACxB,QAAY,CAAA,QAAA,CACZ,OAAU,QACV,CAAA,SAAA,CAAa,UACb,MAAU,CAAA,SAAA,CACV,mBAAoB,QACpB,CAAA,OAAA,CAAW,UACX,UAAY,CAAA,SAAA,CACZ,IAAQ,CAAA,QAAA,CACR,QAAW,QACX,CAAA,IAAA,CAAQ,UACR,IAAQ,CAAA,QAAA,CACR,IAAO,SACP,CAAA,IAAA,CAAQ,SACR,oBAAsB,CAAA,QAAA,CACtB,QAAW,SACX,CAAA,uBAAA,CAAyB,UACzB,GAAO,CAAA,SAAA,CACP,QAAW,QACb,CAAA,CACAC,CAAoB,CAAA,CAClB,MAAS,UACT,CAAA,WAAA,CAAa,UACf,CA7EFC,CAAAA,CAAAA,CAAA,CACE,IAAAlB,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,OAAA,CAAAC,EACA,WAAAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAMA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAuBA,iBAAAC,CAIF","file":"package-DF3VLPXG.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.4.12\",\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 \"./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/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\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 \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@tanstack/react-query\": \"^5.76.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\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 \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\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.d.ts
CHANGED
|
@@ -315,17 +315,59 @@ type RouteDefinition = {
|
|
|
315
315
|
errorHandler?: RouteHandler;
|
|
316
316
|
};
|
|
317
317
|
|
|
318
|
+
/** Array of Store instances that will be provisioned when the module is loaded */
|
|
318
319
|
type Stores = Store<any, any>[];
|
|
320
|
+
/** Record of query methods that can be called from the client */
|
|
319
321
|
type Queries = Record<string, MethodDefinition<any>>;
|
|
322
|
+
/** Record of mutation methods that can be called from the client */
|
|
320
323
|
type Mutations = Record<string, MethodDefinition<any>>;
|
|
324
|
+
/**
|
|
325
|
+
* The Module class is a core building block of a Modelence application that encapsulates related functionality.
|
|
326
|
+
* Modules can contain stores, queries, mutations, routes, cron jobs and configurations.
|
|
327
|
+
*
|
|
328
|
+
* @category Module
|
|
329
|
+
*
|
|
330
|
+
* @example
|
|
331
|
+
* ```ts
|
|
332
|
+
* const todoModule = new Module('todo', {
|
|
333
|
+
* stores: [dbTodos],
|
|
334
|
+
* queries: {
|
|
335
|
+
* async getAll() {
|
|
336
|
+
* // Fetch and return all Todo items
|
|
337
|
+
* }
|
|
338
|
+
* },
|
|
339
|
+
* mutations: {
|
|
340
|
+
* async create({ title }, { user }) {
|
|
341
|
+
* // Create a new Todo item
|
|
342
|
+
* }
|
|
343
|
+
* }
|
|
344
|
+
* });
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
321
347
|
declare class Module {
|
|
348
|
+
/** @internal */
|
|
322
349
|
readonly name: string;
|
|
350
|
+
/** @internal */
|
|
323
351
|
readonly stores: Stores;
|
|
352
|
+
/** @internal */
|
|
324
353
|
readonly queries: Queries;
|
|
354
|
+
/** @internal */
|
|
325
355
|
readonly mutations: Mutations;
|
|
356
|
+
/** @internal */
|
|
326
357
|
readonly routes: RouteDefinition[];
|
|
358
|
+
/** @internal */
|
|
327
359
|
readonly cronJobs: Record<string, CronJobInputParams>;
|
|
360
|
+
/** @internal */
|
|
328
361
|
readonly configSchema: ConfigSchema;
|
|
362
|
+
/**
|
|
363
|
+
* Creates a new Module instance
|
|
364
|
+
*
|
|
365
|
+
* @param name - The unique name of the module.
|
|
366
|
+
* This name is used to namespace queries, mutations,
|
|
367
|
+
* cron jobs and configuration values with a prefix (e.g. "todo.create")
|
|
368
|
+
*
|
|
369
|
+
* @param options - Module configuration options
|
|
370
|
+
*/
|
|
329
371
|
constructor(name: string, { stores, queries, mutations, routes, cronJobs, configSchema }: {
|
|
330
372
|
stores?: Stores;
|
|
331
373
|
queries?: Queries;
|