modelence 0.25.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/bin/modelence.js +1 -1
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-BVJJCQ6Y.js → chunk-6CIFSSQP.js} +4 -4
- package/dist/chunk-6CIFSSQP.js.map +1 -0
- package/dist/{chunk-FXPFIA66.js → chunk-DAV46WE7.js} +3 -3
- package/dist/{chunk-FXPFIA66.js.map → chunk-DAV46WE7.js.map} +1 -1
- package/dist/{chunk-7JUFVY6Q.js → chunk-FF6FEX7U.js} +2 -2
- package/dist/{chunk-7JUFVY6Q.js.map → chunk-FF6FEX7U.js.map} +1 -1
- package/dist/{chunk-J3ZZEZIV.js → chunk-IKIOVFVD.js} +13 -13
- package/dist/chunk-IKIOVFVD.js.map +1 -0
- package/dist/chunk-K4PI6L5V.js +2 -0
- package/dist/chunk-K4PI6L5V.js.map +1 -0
- package/dist/{chunk-VKGZ35WJ.js → chunk-KJBMQRY6.js} +2 -2
- package/dist/{chunk-VKGZ35WJ.js.map → chunk-KJBMQRY6.js.map} +1 -1
- package/dist/{chunk-7MIBHVZS.js → chunk-NAWQYPGM.js} +3 -3
- package/dist/{chunk-7MIBHVZS.js.map → chunk-NAWQYPGM.js.map} +1 -1
- package/dist/{chunk-CAN2CWEI.js → chunk-S5OQYKNR.js} +2 -2
- package/dist/{chunk-CAN2CWEI.js.map → chunk-S5OQYKNR.js.map} +1 -1
- package/dist/client.js +1 -1
- package/dist/{package-PKGSNHLQ.js → package-GGPYIET6.js} +2 -2
- package/dist/{package-PKGSNHLQ.js.map → package-GGPYIET6.js.map} +1 -1
- package/dist/{render-GH7MWT27.js → render-WY23X5RN.js} +2 -2
- package/dist/{render-GH7MWT27.js.map → render-WY23X5RN.js.map} +1 -1
- package/dist/renderApp-FRZBJICP.js +2 -0
- package/dist/{renderApp-5P62J4NO.js.map → renderApp-FRZBJICP.js.map} +1 -1
- package/dist/server-J75POKU5.js +2 -0
- package/dist/{server-LBKWH4I3.js.map → server-J75POKU5.js.map} +1 -1
- package/dist/server.d.ts +3 -1
- package/dist/server.js +1 -1
- package/dist/transport-RJFMTIDK.js +2 -0
- package/dist/{transport-QMFZ67HR.js.map → transport-RJFMTIDK.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-5M6FUMUK.js +0 -2
- package/dist/chunk-5M6FUMUK.js.map +0 -1
- package/dist/chunk-BVJJCQ6Y.js.map +0 -1
- package/dist/chunk-J3ZZEZIV.js.map +0 -1
- package/dist/renderApp-5P62J4NO.js +0 -2
- package/dist/server-LBKWH4I3.js +0 -2
- package/dist/transport-QMFZ67HR.js +0 -2
package/README.md
CHANGED
|
@@ -40,6 +40,10 @@ For a more detailed guide, check out the [Quick Start](https://docs.modelence.co
|
|
|
40
40
|
|
|
41
41
|
If you want to contribute to Modelence itself (not just use it in an application), follow the steps below.
|
|
42
42
|
|
|
43
|
+
> Before you start, please read [CONTRIBUTING.md](https://github.com/modelence/modelence/blob/main/CONTRIBUTING.md).
|
|
44
|
+
> Bug fixes and small improvements are welcome as pull requests; changes to the core runtime or public API surface
|
|
45
|
+
> should start with an issue.
|
|
46
|
+
|
|
43
47
|
#### 1. Clone the repository
|
|
44
48
|
```bash
|
|
45
49
|
git clone https://github.com/modelence/modelence.git
|
package/dist/bin/modelence.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import L,{join,dirname}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import {execSync,spawnSync}from'child_process';import H from'open';import V from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import Se from'archiver';async function y(e,{pickEnvironment:t=false,appId:o}={}){let n=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!n.ok)throw new Error("Failed to create CLI authentication code");let{code:s,verificationUrl:r}=await n.json(),a=new URL(r);t&&a.searchParams.set("pick","environment"),o&&a.searchParams.set("appId",o),console.log(`Please visit ${a} to authenticate`),console.log(`Code: ${s}`);try{await H(a.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return {token:await X(e,s)}}async function X(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let r=await Q(e,t);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function Q(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:n}=await o.json();return n}var x=".modelence.env",C=".modelence",k="project.json";async function oe(e,t){let o="setupToken"in t?{"X-Modelence-Setup-Token":t.setupToken}:{Authorization:`Bearer ${t.cliToken}`},n=await fetch(`${e}/api/setup`,{method:"GET",headers:o});if(!n.ok){let s=await n.text();throw new Error(s||`Request failed with status ${n.status}`)}return n.json()}async function $(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{t.question(e,n=>{t.close(),o(n.trim());});})}async function ne(){return (await $(`Warning: ${x} already exists. Do you want to overwrite it? (y/N) `)).toLowerCase()==="y"}function re(e){return String(e).replace(/"/g,'\\"')}async function ie(){try{let e=await promises.readFile(join(process.cwd(),C,k),"utf8"),{appId:t}=JSON.parse(e);return typeof t=="string"&&t?t:void 0}catch{return}}async function se(e){let t=join(process.cwd(),C),o=join(t,k),n={};try{n=JSON.parse(await promises.readFile(o,"utf8"));}catch{}await promises.mkdir(t,{recursive:true}),await promises.writeFile(o,JSON.stringify({...n,appId:e},null,2)+`
|
|
3
3
|
`);}var j=".claude",w=join(j,"settings.json"),N="modelence@modelence",I="modelence/modelence",ae={modelence:{source:{source:"github",repo:I}}},ce="https://docs.modelence.com/ai-coding-agents",_=`Install the Modelence plugin for Claude Code by hand:
|
|
4
4
|
claude plugin marketplace add ${I}
|
|
5
|
-
claude plugin install ${N}
|
|
5
|
+
claude plugin install ${N} --scope project
|
|
6
6
|
Guide: ${ce}`;async function le(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch(n){if(n.code!=="ENOENT"){console.warn(`Could not read ${w}; leaving it unchanged.`);return}}let o={};if(t!==void 0)try{o=JSON.parse(t);}catch{console.warn(`Could not parse ${w}; leaving it unchanged.`);return}o.extraKnownMarketplaces={...o.extraKnownMarketplaces,...ae},o.enabledPlugins?.[N]===void 0&&(o.enabledPlugins={...o.enabledPlugins,[N]:true});try{await promises.mkdir(join(process.cwd(),j),{recursive:!0}),await promises.writeFile(e,JSON.stringify(o,null,2)+`
|
|
7
7
|
`),console.log(`Declared the Modelence Claude Code plugin in ${w}`);}catch(n){console.warn(`Failed to write ${w}:`,n);}}function T(e){return spawnSync("claude",e,{encoding:"utf8",shell:process.platform==="win32"})}async function de(){let e=T(["--version"]);if(e.error||e.status!==0){console.log(_);return}let t=(await $("Install the Modelence plugin for Claude Code? (Y/n) ")).toLowerCase();if(t&&t!=="y"&&t!=="yes")return;let o=T(["plugin","marketplace","add",I]),n=T(["plugin","install",N,"--scope","project"]);if(n.status===0)console.log("Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: run /mcp, choose modelence, then Authenticate.");else {let s=o.status!==0?o:n;console.warn(`Could not install the Modelence plugin: ${(s.stderr||s.stdout||"").trim()}`),console.warn(_);}}async function ue(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function R(e){try{let t=join(process.cwd(),x),o={},n=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),n=!0,await ue(t),await ne()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:c}=await y(e.host,{pickEnvironment:!0,appId:await ie()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await oe(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId,MODELENCE_RUNTIME:process.env.MODELENCE_RUNTIME||"local"},i=Object.entries(a).map(([c,g])=>`${c}="${re(g)}"`).join(`
|
|
8
8
|
`);if(await promises.writeFile(t,i.trim()+`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","ask","question","rl","createInterface","answer","confirmOverwrite","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACE_REPO","CLAUDE_MARKETPLACES","CLAUDE_PLUGIN_DOCS_URL","CLAUDE_PLUGIN_INSTALL_HINT","ensureClaudePluginEnabled","settingsPath","settings","runClaude","args","spawnSync","offerClaudePluginInstall","probe","marketplace","install","failed","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";keAkBA,eAAsBA,CAAAA,CACpBC,EACA,CAAE,eAAA,CAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,GAAGH,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,EAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,MAAM,0CAA0C,CAAA,CAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAM,IAAI,GAAA,CAAID,CAAe,CAAA,CAC/BJ,CAAAA,EACFK,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,MAAA,CAAQ,aAAa,CAAA,CAExCJ,CAAAA,EACFI,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAASJ,CAAK,CAAA,CAGrC,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBI,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,CAAA,CAAE,CAAA,CAE3B,GAAI,CACF,MAAMG,CAAAA,CAAKD,CAAAA,CAAI,QAAA,EAAU,EAC3B,CAAA,KAAQ,CAGN,OAAA,CAAQ,GAAA,CAAI,6EAA6E,EAC3F,CAIA,OAAO,CAAE,KAAA,CAFK,M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C,MAAA,CACC,YAAA,CACA,gFACF,CAAA,CACC,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACNyC,CAAAA,CAAIvE,CAAO,EACb,CAAC,CAAA,CAEHmF,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd4C,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n\n `appId` is the hint from .modelence/project.json: the approval page uses it\n to preselect the app this project was last connected to. Purely a\n convenience for the picker — the user can still choose any app, and an\n unresolvable ID is simply ignored.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false, appId }: { pickEnvironment?: boolean; appId?: string } = {}\n): Promise<{ token: string }> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = new URL(verificationUrl);\n if (pickEnvironment) {\n url.searchParams.set('pick', 'environment');\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { spawnSync } from 'child_process';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function ask(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const answer = await ask(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `\n );\n return answer.toLowerCase() === 'y';\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACE_REPO = 'modelence/modelence';\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: CLAUDE_MARKETPLACE_REPO } },\n};\nconst CLAUDE_PLUGIN_DOCS_URL = 'https://docs.modelence.com/ai-coding-agents';\nconst CLAUDE_PLUGIN_INSTALL_HINT =\n 'Install the Modelence plugin for Claude Code by hand:\\n' +\n ` claude plugin marketplace add ${CLAUDE_MARKETPLACE_REPO}\\n` +\n ` claude plugin install ${CLAUDE_PLUGIN_ID}\\n` +\n `Guide: ${CLAUDE_PLUGIN_DOCS_URL}`;\n\n/*\n Declares the Modelence Claude Code plugin in the project's settings.json,\n merging into an existing file rather than replacing it. An explicit\n `false` is a deliberate opt-out and is never flipped back on. The file is\n inert for people who don't use Claude Code, and failing to write it doesn't\n fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`Could not read ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n let settings: Record<string, any> = {};\n if (content !== undefined) {\n try {\n settings = JSON.parse(content);\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n // The marketplace is only a pointer, so it's always (re)declared — a file\n // with just enabledPlugins, as `claude plugin install --scope project`\n // leaves behind, can't be resolved by teammates without it. An explicit\n // `false` in enabledPlugins is the user's opt-out and is left alone.\n settings.extraKnownMarketplaces = { ...settings.extraKnownMarketplaces, ...CLAUDE_MARKETPLACES };\n if (settings.enabledPlugins?.[CLAUDE_PLUGIN_ID] === undefined) {\n settings.enabledPlugins = { ...settings.enabledPlugins, [CLAUDE_PLUGIN_ID]: true };\n }\n\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n console.log(`Declared the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to write ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n}\n\nfunction runClaude(args: string[]) {\n return spawnSync('claude', args, { encoding: 'utf8', shell: process.platform === 'win32' });\n}\n\n/*\n Installs the plugin through the Claude Code CLI — the one install path that\n behaves the same for the terminal, the IDE extensions and the desktop app,\n which all read the same plugin state. Touches the user's machine-wide Claude\n config, so it asks first, and it never fails the setup: without the CLI on\n PATH it prints the commands to run by hand.\n*/\nasync function offerClaudePluginInstall(): Promise<void> {\n const probe = runClaude(['--version']);\n if (probe.error || probe.status !== 0) {\n console.log(CLAUDE_PLUGIN_INSTALL_HINT);\n return;\n }\n\n const answer = (await ask('Install the Modelence plugin for Claude Code? (Y/n) ')).toLowerCase();\n if (answer && answer !== 'y' && answer !== 'yes') {\n return;\n }\n\n // Makes the install work before Claude Code has picked up the marketplace\n // declared in .claude/settings.json. Its result only matters if the install\n // then fails: a network or auth error here is the real cause, and the\n // install's own message wouldn't point at it.\n const marketplace = runClaude(['plugin', 'marketplace', 'add', CLAUDE_MARKETPLACE_REPO]);\n const install = runClaude(['plugin', 'install', CLAUDE_PLUGIN_ID, '--scope', 'project']);\n if (install.status === 0) {\n console.log(\n 'Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: ' +\n 'run /mcp, choose modelence, then Authenticate.'\n );\n } else {\n const failed = marketplace.status !== 0 ? marketplace : install;\n console.warn(\n `Could not install the Modelence plugin: ${(failed.stderr || failed.stdout || '').trim()}`\n );\n console.warn(CLAUDE_PLUGIN_INSTALL_HINT);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n // Interactive runs only: with --token (CI) or without a terminal there is\n // nobody to ask, and no Claude Code to set up.\n if (!options.token && process.stdin.isTTY) {\n await offerClaudePluginInstall();\n }\n\n if (fileExisted) {\n // The dev server reads the file at boot, and an open agent session may\n // still hold the old environment id in its context.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'package-lock.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = ['public', 'server', 'scripts', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","ask","question","rl","createInterface","answer","confirmOverwrite","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACE_REPO","CLAUDE_MARKETPLACES","CLAUDE_PLUGIN_DOCS_URL","CLAUDE_PLUGIN_INSTALL_HINT","ensureClaudePluginEnabled","settingsPath","settings","runClaude","args","spawnSync","offerClaudePluginInstall","probe","marketplace","install","failed","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";keAkBA,eAAsBA,CAAAA,CACpBC,EACA,CAAE,eAAA,CAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,GAAGH,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,EAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,MAAM,0CAA0C,CAAA,CAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAM,IAAI,GAAA,CAAID,CAAe,CAAA,CAC/BJ,CAAAA,EACFK,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,MAAA,CAAQ,aAAa,CAAA,CAExCJ,CAAAA,EACFI,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAASJ,CAAK,CAAA,CAGrC,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBI,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,CAAA,CAAE,CAAA,CAE3B,GAAI,CACF,MAAMG,CAAAA,CAAKD,CAAAA,CAAI,QAAA,EAAU,EAC3B,CAAA,KAAQ,CAGN,OAAA,CAAQ,GAAA,CAAI,6EAA6E,EAC3F,CAIA,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A,CACb,YAAY,0BAA0B,CAAA,CACtC,MAAA,CACC,YAAA,CACA,gFACF,CAAA,CACC,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACNyC,CAAAA,CAAIvE,CAAO,EACb,CAAC,CAAA,CAEHmF,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd4C,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n\n `appId` is the hint from .modelence/project.json: the approval page uses it\n to preselect the app this project was last connected to. Purely a\n convenience for the picker — the user can still choose any app, and an\n unresolvable ID is simply ignored.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false, appId }: { pickEnvironment?: boolean; appId?: string } = {}\n): Promise<{ token: string }> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = new URL(verificationUrl);\n if (pickEnvironment) {\n url.searchParams.set('pick', 'environment');\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { spawnSync } from 'child_process';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function ask(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const answer = await ask(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `\n );\n return answer.toLowerCase() === 'y';\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACE_REPO = 'modelence/modelence';\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: CLAUDE_MARKETPLACE_REPO } },\n};\nconst CLAUDE_PLUGIN_DOCS_URL = 'https://docs.modelence.com/ai-coding-agents';\nconst CLAUDE_PLUGIN_INSTALL_HINT =\n 'Install the Modelence plugin for Claude Code by hand:\\n' +\n ` claude plugin marketplace add ${CLAUDE_MARKETPLACE_REPO}\\n` +\n ` claude plugin install ${CLAUDE_PLUGIN_ID} --scope project\\n` +\n `Guide: ${CLAUDE_PLUGIN_DOCS_URL}`;\n\n/*\n Declares the Modelence Claude Code plugin in the project's settings.json,\n merging into an existing file rather than replacing it. An explicit\n `false` is a deliberate opt-out and is never flipped back on. The file is\n inert for people who don't use Claude Code, and failing to write it doesn't\n fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`Could not read ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n let settings: Record<string, any> = {};\n if (content !== undefined) {\n try {\n settings = JSON.parse(content);\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n // The marketplace is only a pointer, so it's always (re)declared — a file\n // with just enabledPlugins, as `claude plugin install --scope project`\n // leaves behind, can't be resolved by teammates without it. An explicit\n // `false` in enabledPlugins is the user's opt-out and is left alone.\n settings.extraKnownMarketplaces = { ...settings.extraKnownMarketplaces, ...CLAUDE_MARKETPLACES };\n if (settings.enabledPlugins?.[CLAUDE_PLUGIN_ID] === undefined) {\n settings.enabledPlugins = { ...settings.enabledPlugins, [CLAUDE_PLUGIN_ID]: true };\n }\n\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n console.log(`Declared the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to write ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n}\n\nfunction runClaude(args: string[]) {\n return spawnSync('claude', args, { encoding: 'utf8', shell: process.platform === 'win32' });\n}\n\n/*\n Installs the plugin through the Claude Code CLI — the one install path that\n behaves the same for the terminal, the IDE extensions and the desktop app,\n which all read the same plugin state. Touches the user's machine-wide Claude\n config, so it asks first, and it never fails the setup: without the CLI on\n PATH it prints the commands to run by hand.\n*/\nasync function offerClaudePluginInstall(): Promise<void> {\n const probe = runClaude(['--version']);\n if (probe.error || probe.status !== 0) {\n console.log(CLAUDE_PLUGIN_INSTALL_HINT);\n return;\n }\n\n const answer = (await ask('Install the Modelence plugin for Claude Code? (Y/n) ')).toLowerCase();\n if (answer && answer !== 'y' && answer !== 'yes') {\n return;\n }\n\n // Makes the install work before Claude Code has picked up the marketplace\n // declared in .claude/settings.json. Its result only matters if the install\n // then fails: a network or auth error here is the real cause, and the\n // install's own message wouldn't point at it.\n const marketplace = runClaude(['plugin', 'marketplace', 'add', CLAUDE_MARKETPLACE_REPO]);\n const install = runClaude(['plugin', 'install', CLAUDE_PLUGIN_ID, '--scope', 'project']);\n if (install.status === 0) {\n console.log(\n 'Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: ' +\n 'run /mcp, choose modelence, then Authenticate.'\n );\n } else {\n const failed = marketplace.status !== 0 ? marketplace : install;\n console.warn(\n `Could not install the Modelence plugin: ${(failed.stderr || failed.stdout || '').trim()}`\n );\n console.warn(CLAUDE_PLUGIN_INSTALL_HINT);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n // Interactive runs only: with --token (CI) or without a terminal there is\n // nobody to ask, and no Claude Code to set up.\n if (!options.token && process.stdin.isTTY) {\n await offerClaudePluginInstall();\n }\n\n if (fileExisted) {\n // The dev server reads the file at boot, and an open agent session may\n // still hold the old environment id in its context.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'package-lock.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = ['public', 'server', 'scripts', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,b,n,j as j$1,o as o$1}from'./chunk-UW37F3GV.js';import {a as a$2,b as b$1}from'./chunk-
|
|
2
|
-
`)}function Oe(n){let e=Object.keys(n.key),t=e.flatMap(i=>Ce(i).map(a=>({$unwind:{path:`$${a}`,preserveNullAndEmptyArrays:true}}))),r=Object.fromEntries(e.map(i=>[i.replace(/\./g,"_"),`$${i}`]));return [...n.partialFilterExpression?[{$match:n.partialFilterExpression}]:[],...t,{$group:{_id:r,ids:{$addToSet:"$_id"}}},{$match:{$expr:{$gt:[{$size:"$ids"},1]}}},{$limit:100}]}function Ce(n){let e=n.split(".");return e.map((t,r)=>e.slice(0,r+1).join("."))}var Ae=["background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","sparse","storageEngine","textIndexVersion","unique","weights","wildcardProjection","2dsphereIndexVersion"],H=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),_e=n=>n.startsWith("_modelence_"),X=n=>{let e={};for(let t of Ae){let r=n[t];r!==void 0&&(e[t]=r);}return e},ke=(n,e)=>{if(!H(n)||!H(e))return false;let t=Object.entries(n),r=Object.entries(e);return t.length!==r.length?false:t.every(([i,a],c)=>{let[d,h]=r[c]||[];return i===d&&isDeepStrictEqual(a,h)})},pe=(n,e)=>ke(n.key,e.key)?isDeepStrictEqual(X(n),X(e)):false,B=n=>H(n)?Object.entries(n).map(([e,t])=>`${e}:${JSON.stringify(t)}`).join("|"):null,ve=async n=>{try{return await n.listIndexes().toArray()}catch(e){if(e instanceof MongoError&&e.code===26)return [];throw e}},Ee=n=>Object.entries(n).map(([e,t])=>`${e}_${t}`).join("_"),Me=n=>{if(n.name){let t=n.name.startsWith("_modelence_")?n.name:`_modelence_${n.name}`;return {...n,name:t}}let e=Ee(n.key);return {...n,name:`_modelence_${e}`}},f=class n{constructor(e,t){this._chainParent=null;this._chainChild=null;this.name=e,this.schema=t.schema,this.methods=t.methods,this.indexes=t.indexes.map(Me),this.searchIndexes=t.searchIndexes||[],this.indexCreationMode=t.indexCreationMode??"background";}getName(){return this.name}getIndexCreationMode(){return this.indexCreationMode}getSchema(){return this.schema}getSerializedSchema(){return N(this.schema)}getIndexes(){return this.indexes}getSearchIndexes(){return this.searchIndexes}getChainTail(){let e=this;for(;e._chainChild;)e=e._chainChild;return e}getChainRoot(){let e=this;for(;e._chainParent;)e=e._chainParent;return e}extend(e){let t=this.getChainTail();if(this.client||t.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);let r={...t.schema,...e.schema||{}},i=[...t.indexes,...e.indexes||[]],a=[...t.searchIndexes,...e.searchIndexes||[]],c={...t.methods||{},...e.methods||{}},d=new n(this.name,{schema:r,methods:c,indexes:i,searchIndexes:a,indexCreationMode:e.indexCreationMode??t.indexCreationMode});return t._chainChild=d,d._chainParent=t,d}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(e="full"){let t=this.requireCollection(),r=e!=="create-only",i=e!=="drop-only",a=await ve(t),c=new Map,d=new Map,h=new Set,T=s=>{c.set(s.name,s);let l=B(s.key);if(!l)return;let u=d.get(l);u?u.add(s.name):d.set(l,new Set([s.name]));},D=s=>{let l=c.get(s);if(!l)return;c.delete(s);let u=B(l.key);if(!u)return;let x=d.get(u);x&&(x.delete(s),x.size===0&&d.delete(u));};for(let s of a)typeof s.name=="string"&&T({...s,name:s.name});let y=async s=>{if(!(s==="_id_"||h.has(s))){try{await t.dropIndex(s);}catch(l){if(!(l instanceof MongoError&&l.code===27))throw l}h.add(s),D(s);}};if(r){let s=new Set(this.indexes.map(u=>u.name).filter(u=>typeof u=="string")),l=[...c.values()].filter(u=>_e(u.name)&&!s.has(u.name));for(let u of l)await y(u.name);}if(this.indexes.length>0)for(let s of this.indexes){if(!s.name)continue;let l=false,u=c.get(s.name);u&&!pe(u,s)&&(r?await y(u.name):l=true);let x=B(s.key);if(x){let S=[...d.get(x)||[]];for(let C of S)C!==s.name&&(r?await y(C):l=true);}let E=c.get(s.name);if(!(!!E&&pe(E,s))&&i&&!l){try{await t.createIndexes([s]);}catch(S){throw s.unique&&le(S)&&console.error(ue(this.name,s,S)),S}T({name:s.name,key:s.key,...X(s)});}}if(i&&this.searchIndexes.length>0)for(let s of this.searchIndexes)try{await t.createSearchIndexes([s]);}catch(l){if(l instanceof MongoError&&l.code===68&&s.name)await t.dropSearchIndex(s.name),await t.createSearchIndexes([s]);else throw l}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,t){let r=await this.requireCollection().findOne(e,t);return r?this.wrapDocument(r):null}async requireOne(e,t,r){let i=await this.findOne(e,t);if(!i)throw r?r():new Error(`Record not found in ${this.name}`);return i}find(e,t){let r=this.requireCollection().find(e,t?.projection?{projection:t.projection}:void 0);return t?.sort&&r.sort(t.sort),t?.limit&&r.limit(t.limit),t?.skip&&r.skip(t.skip),r}async findById(e){let t=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(t)}async requireById(e,t){let r=await this.findById(e);if(!r)throw t?t():new Error(`Record with id ${e} not found in ${this.name}`);return r}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,t){return (await this.find(e,t).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e,t){return await this.requireCollection().insertOne(e,t)}async create(e,t){let r=$(this.schema,{_id:new ObjectId,...e});return await this.requireCollection().insertOne(r,t),this.wrapDocument(r)}async insertMany(e,t){return await this.requireCollection().insertMany(e,t)}async updateOne(e,t,r){return await this.requireCollection().updateOne(this.getSelector(e),t,r)}async upsertOne(e,t,r){return await this.requireCollection().updateOne(this.getSelector(e),t,{upsert:true,...r})}async updateMany(e,t,r){return await this.requireCollection().updateMany(e,t,r)}async upsertMany(e,t,r){return await this.requireCollection().updateMany(e,t,{upsert:true,...r})}async deleteOne(e,t){return await this.requireCollection().deleteOne(this.getSelector(e),t)}async deleteMany(e,t){return await this.requireCollection().deleteMany(e,t)}async findOneAndUpdate(e,t,r){let i=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,r??{});return i?this.wrapDocument(i):null}async findOneAndUpsert(e,t,r){let i=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,{upsert:true,...r,returnDocument:"after",includeResultMetadata:true});return {doc:i.value?this.wrapDocument(i.value):null,isNew:!!i.lastErrorObject?.upserted}}async findOneAndDelete(e,t){let r=await this.requireCollection().findOneAndDelete(this.getSelector(e),t??{});return r?this.wrapDocument(r):null}async findOneAndReplace(e,t,r){let i=await this.requireCollection().findOneAndReplace(this.getSelector(e),t,r??{});return i?this.wrapDocument(i):null}async replaceOne(e,t,r){return await this.requireCollection().replaceOne(this.getSelector(e),t,r)}async distinct(e,t,r){let i=t??{};return r!==void 0?await this.requireCollection().distinct(e,i,r):await this.requireCollection().distinct(e,i)}watch(e,t){return this.requireCollection().watch(e,t)}aggregate(e,t){return this.requireCollection().aggregate(e,t)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,t){let r=this.getDatabase();if(!this.collection||!r)throw new Error(`Store ${this.name} is not provisioned`);if((await r.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await r.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await r.collection(e).rename(this.name,t);}async vectorSearch({field:e,embedding:t,numCandidates:r,limit:i,projection:a,indexName:c}){return this.aggregate([{$vectorSearch:{index:c||e+"VectorSearch",path:e,queryVector:t,numCandidates:r||100,limit:i||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...a}}])}static vectorIndex({field:e,dimensions:t,similarity:r="cosine",indexName:i}){return {type:"vectorSearch",name:i||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:t,similarity:r}]}}}};var Re=z$1.string.bind(z$1),Ze=z$1.number.bind(z$1),Ne=z$1.date.bind(z$1),je=z$1.boolean.bind(z$1),Fe=z$1.array.bind(z$1),$e=z$1.object.bind(z$1),Pe=z$1.enum.bind(z$1),o={string:Re,number:Ze,date:Ne,boolean:je,array:Fe,object:$e,enum:Pe,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(n){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(n){return {}}};function g(n){return createHash("sha256").update(n).digest("hex")}var ee=new f("_modelenceLinkNonces",{schema:{nonce:o.string(),userId:o.string(),expiresAt:o.date()},indexes:[{key:{nonce:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});async function cn(n){let e=randomBytes(32).toString("hex");return await ee.insertOne({nonce:e,userId:n,expiresAt:new Date(Date.now()+a$1.minutes(10))}),e}async function dn(n){let e=await ee.findOneAndDelete({nonce:n});return e?e.userId:null}var te=new f("_modelenceOAuthExchangeCodes",{schema:{code:o.string(),userId:o.string(),provider:o.string(),codeChallenge:o.string().optional(),expiresAt:o.date()},indexes:[{key:{code:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),Ue=1;async function ln(n,e,t){let r=randomBytes(32).toString("hex");return await te.insertOne({code:g(r),userId:n,provider:e,codeChallenge:g(t),expiresAt:new Date(Date.now()+a$1.minutes(Ue))}),r}async function un(n,e){let t=await te.findOneAndDelete({code:g(n)});return !t||t.expiresAt<new Date||!t.codeChallenge||!e||!Le(g(e),t.codeChallenge)?null:{userId:t.userId,provider:t.provider}}function Le(n,e){return n.length!==e.length?false:timingSafeEqual(Buffer.from(n,"utf8"),Buffer.from(e,"utf8"))}var w=new f("_modelenceSessions",{schema:{authToken:o.string(),createdAt:o.date(),expiresAt:o.date(),userId:o.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0},{key:{userId:1}}]});async function me(n){if(n){let e=g(n),t=await w.findOne({authToken:e}),r=/^[0-9a-f]{64}$/i.test(n);if(!t&&!r&&(t=await w.findOne({authToken:n}),t&&await w.updateOne({_id:t._id},{$set:{authToken:e}})),t)return {authToken:n,expiresAt:new Date(t.expiresAt),userId:t.userId??null}}return await We()}async function pn(n,e){await w.updateOne({authToken:g(n)},{$set:{userId:e}});}async function hn(n){await w.updateOne({authToken:g(n)},{$set:{userId:null}});}async function mn(n){await w.deleteMany({userId:n});}async function We(n=null){let e=randomBytes(32).toString("base64url"),t=Date.now(),r=new Date(t+a$1.days(7));return await w.insertOne({authToken:g(e),createdAt:new Date(t),expiresAt:r,userId:n}),{authToken:e,expiresAt:r,userId:n}}async function Qe(n){let e=Date.now(),t=new Date(e+a$1.days(7));await w.updateOne({authToken:g(n.authToken)},{$set:{lastActiveDate:new Date(e),expiresAt:t}});}function Ke(n,e){n.cookie("authToken",e,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/",maxAge:a$1.days(7)});}function yn(n){n.clearCookie("authToken",{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/"});}var fn=new Z("_system.session",{stores:[w,ee,te],mutations:{init:async function(n,{session:e,user:t,res:r}){return r&&e?.userId&&Ke(r,e.authToken),{session:e,user:t,configs:b(),...se()?{setupRequired:true}:{}}},heartbeat:async function(n,{session:e}){e&&await Qe(e);}}});var ye=new f("_modelenceUsers",{schema:{handle:o.string(),emails:o.array(o.object({address:o.string(),verified:o.boolean()})).optional(),status:o.enum(["active","disabled","deleted"]).optional(),firstName:o.string().optional(),lastName:o.string().optional(),avatarUrl:o.string().optional(),createdAt:o.date(),disabledAt:o.date().optional(),deletedAt:o.date().optional(),roles:o.array(o.string()).optional(),authMethods:o.object({password:o.object({hash:o.string()}).optional(),google:o.object({id:o.string()}).optional(),github:o.object({id:o.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"emails.address":1},unique:true,collation:{locale:"en",strength:2},partialFilterExpression:{"emails.address":{$exists:true}}},{key:{"authMethods.google.id":1},sparse:true,unique:true},{key:{"authMethods.github.id":1},sparse:true,unique:true}]}),Sn=new f("_modelenceDisposableEmailDomains",{schema:{domain:o.string(),addedAt:o.date()},indexes:[{key:{domain:1},unique:true}]}),bn=new f("_modelenceEmailVerificationTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),wn=new f("_modelenceResetPasswordTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),Dn=new f("_modelenceMagicLinkTokens",{schema:{email:o.string(),token:o.string(),code:o.string(),attempts:o.number(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{email:1}},{key:{expiresAt:1},expireAfterSeconds:0}]});var fe=new Map,_={authenticated:null,unauthenticated:null};function On(n,e){_.authenticated=e.authenticated,_.unauthenticated=e.unauthenticated;for(let[t,r]of Object.entries(n))fe.set(t,r);}function ge(){return _.unauthenticated?[_.unauthenticated]:[]}function Te(){return _.authenticated?[_.authenticated]:[]}function ne(n,e){let t=e.find(r=>!Ve(n,r));if(t)throw new Error(`Access denied - missing permission: '${t}'`)}function Ve(n,e){for(let t of n)if(fe.get(t)?.permissions?.includes(e))return true;return false}async function xe(n){let e=await me(n),t=e.userId?await ye.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,r=t?{id:t._id.toString(),handle:t.handle,roles:t.roles||[],hasRole:a=>(t.roles||[]).includes(a),requireRole:a=>{if(!(t.roles||[]).includes(a))throw new Error(`Access denied - role '${a}' required`)},firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0}:null,i=r?Te():ge();return {user:r,session:e,roles:i}}var k=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function Je(){return typeof window!="object"}function O(){if(!Je())throw new Error("This function can only be called on the server")}function Rn(n){return n.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var v=new Map;function He(n){let e=v.get(n.id);return e||(e=new Map,v.set(n.id,e)),e}async function Xe(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({}),authToken:z$1.string().nullish(),clientInfo:z$1.object({screenWidth:z$1.number(),screenHeight:z$1.number(),windowWidth:z$1.number(),windowHeight:z$1.number(),pixelRatio:z$1.number(),orientation:z$1.string().nullable()}).optional()}).safeParse(e);if(!t.success){n.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${t.error.message}`});return}let{subscriptionId:r,method:i,args:a,authToken:c,clientInfo:d}=t.data,h=He(n),T=h.get(r);if(T)if(T.cleanup)try{T.cleanup();}catch(y){console.error("[LiveQuery] Error cleaning up existing subscription:",y);}else T.aborted=true;let D={cleanup:null};h.set(r,D);try{let{session:y,user:s,roles:l}=await xe(c??null),u={session:y,user:s,roles:l,clientInfo:d??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:n.handshake.address,userAgent:n.handshake.headers["user-agent"]},req:null,res:null},x=await Se(i,a,u),E=async()=>{let b=a$2(await x.fetch());D.aborted||n.emit("liveQueryData",{subscriptionId:r,data:b,typeMap:b$1(b)});},M=!0,S=!1,C=()=>{D.aborted||!M||S||(M=!1,S=!0,E().catch(b=>{D.aborted||(console.error(`[LiveQuery] Error fetching data for ${i}:`,b),n.emit("liveQueryError",{subscriptionId:r,error:b instanceof Error?b.message:String(b)}));}).finally(()=>{S=!1,C();}));},U=x.watch({publish:()=>{M=!0,C();}});if(D.aborted){if(U)try{U();}catch(b){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",b);}return}D.cleanup=U||null,C();}catch(y){h.delete(r),console.error(`[LiveQuery] Error in ${i}:`,y),n.emit("liveQueryError",{subscriptionId:r,error:y instanceof Error?y.message:String(y)});}}function Ge(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1)}).safeParse(e);if(!t.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${t.error.message}`);return}let{subscriptionId:r}=t.data,i=v.get(n.id);if(!i)return;let a=i.get(r);if(a){if(a.cleanup)try{a.cleanup();}catch(c){console.error("[LiveQuery] Error in cleanup:",c);}else a.aborted=true;i.delete(r);}}function Ye(n){let e=v.get(n.id);if(e){for(let t of e.values())if(t.cleanup)try{t.cleanup();}catch(r){console.error("[LiveQuery] Error in cleanup on disconnect:",r);}else t.aborted=true;v.delete(n.id);}}var q={};function Vn(n,e){return O(),be(n),z("query",n,e)}function Bn(n,e){return O(),be(n),z("mutation",n,e)}function Jn(n,e){return O(),we(n),z("query",n,e)}function Hn(n,e){return O(),we(n),z("mutation",n,e)}function be(n){if(n.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${n})`)}function we(n){if(!n.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${n})`)}function z(n,e,t){if(O(),q[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof t=="function"?t:t.handler,i=typeof t=="function"?[]:t.permissions??[];q[e]={type:n,name:e,handler:r,permissions:i};}async function Xn(n$1,e,t){O();let r=q[n$1];if(!r)throw new Error(`Method with name '${n$1}' is not defined.`);let{type:i,handler:a}=r,c=n("method",`method:${n$1}`,{type:i,args:j$1(e)}),d;try{ne(t.roles,r.permissions),d=await a(e,t);}catch(h){throw o$1(h instanceof Error?h:new Error(String(h))),c.end("error"),h}return c.end(),d}async function Se(n$1,e,t){O();let r=q[n$1];if(!r)throw new Error(`Method with name '${n$1}' is not defined.`);let{type:i,handler:a}=r;if(i!=="query")throw new Error("Live methods are only supported for queries");let c=n("method",`method:${n$1}:live`,{type:i,args:j$1(e)}),d;try{if(ne(t.roles,r.permissions),d=await a(e,t),!(d instanceof k))throw new Error(`Live query handler for '${n$1}' must return a LiveData object with fetch and watch functions. See https://docs.modelence.com/live-queries`)}catch(h){throw o$1(h instanceof Error?h:new Error(String(h))),c.end("error"),h}return c.end(),d}
|
|
3
|
-
export{k as A,Rn as B,Vn as C,Bn as D,Jn as E,Hn as F,Xn as G,Xe as H,Ge as I,Ye as J,Z as a,se as b,f as c,o as d,g as e,cn as f,dn as g,ln as h,un as i,w as j,me as k,pn as l,hn as m,mn as n,We as o,Ke as p,yn as q,fn as r,ye as s,Sn as t,bn as u,wn as v,Dn as w,On as x,ge as y,xe as z};//# sourceMappingURL=chunk-
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a,b,n,j as j$1,o as o$1}from'./chunk-UW37F3GV.js';import {a as a$2,b as b$1}from'./chunk-K4PI6L5V.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {isDeepStrictEqual}from'util';import {MongoError,ObjectId,MongoServerError}from'mongodb';import {z as z$1}from'zod';import {createHash,randomBytes,timingSafeEqual}from'crypto';var Z=class{constructor(e,{stores:t=[],queries:r={},mutations:i={},routes:a=[],cronJobs:c={},configSchema:d={},rateLimits:h=[],channels:T=[]}={}){this.name=e,this.stores=t,this.queries=r,this.mutations=i,this.routes=a,this.cronJobs=c,this.configSchema=d,this.rateLimits=h,this.channels=T;}getConfig(e){return a(`${this.name}.${e}`)}};function se(){return process.env.NODE_ENV==="development"&&!process.env.MODELENCE_SERVICE_ENDPOINT&&!a("_system.mongodbUri")}function I(n){let e=n._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:I(e.type)};if(e.typeName==="ZodObject"){let r=e.shape(),i={};for(let[a,c]of Object.entries(r))i[a]=I(c);return {type:"object",items:i}}if(e.typeName==="ZodOptional")return {...I(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...I(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(I)};if(e.typeName==="ZodEffects"){let t=e;return t.description?{type:"custom",typeName:t.description}:I(t.schema)}return {type:"custom",typeName:e.typeName}}function N(n){let e={};for(let[t,r]of Object.entries(n))Array.isArray(r)?e[t]=r.map(i=>typeof i=="object"&&"_def"in i?I(i):N(i)):typeof r=="object"&&"_def"in r?e[t]=I(r):e[t]=N(r);return e}var j=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),ae=n=>j(n)&&"_def"in n,V=n=>n._def,ce=n=>{let e=V(n);if(e.typeName==="ZodOptional"||e.typeName==="ZodNullable"||e.typeName==="ZodDefault"||e.typeName==="ZodCatch"||e.typeName==="ZodReadonly")return e.innerType;if(e.typeName==="ZodEffects")return e.schema;if(e.typeName==="ZodBranded")return e.type;if(e.typeName==="ZodPipeline")return e.out},de=n=>{let e=V(n);if(e.typeName==="ZodDefault")return {hasDefault:true,value:e.defaultValue()};let t=ce(n);return t?de(t):{hasDefault:false}},K=(n,e)=>{let t=V(n);if(t.typeName==="ZodObject"&&j(e))return $(t.shape(),e);if(t.typeName==="ZodArray"&&Array.isArray(e))return e.map(i=>K(t.type,i));let r=ce(n);return r?K(r,e):e},F=(n,e)=>ae(n)?K(n,e):Array.isArray(n)&&Array.isArray(e)?n.length===1?e.map(t=>F(n[0],t)):e.map((t,r)=>F(n[r],t)):j(n)&&j(e)?$(n,e):e,$=(n,e)=>{let t={...e};for(let[r,i]of Object.entries(n)){let a=t[r];if(a===void 0){if(ae(i)){let c=de(i);c.hasDefault&&(t[r]=F(i,c.value));}continue}t[r]=F(i,a);}return t};var Ie="[modelence:index-error]";function le(n){return n instanceof MongoServerError?n.code===11e3||n.message.includes("E11000"):false}function ue(n,e,t){let r={problem:"unique-index-violation",collection:n,index:{name:e.name??null,key:e.key,collation:e.collation??null,partialFilterExpression:e.partialFilterExpression??null},duplicateKey:t.keyValue??null,serverError:t.errmsg??t.message},i=e.collation?{collation:e.collation}:void 0,a=`db.getCollection(${JSON.stringify(n)}).aggregate(${JSON.stringify(Oe(e))}`+(i?`, ${JSON.stringify(i)}`:"")+")";return [`${Ie} Unique index '${e.name??JSON.stringify(e.key)}' on collection '${n}' could not be created because existing documents already violate it. Until this is resolved the constraint is NOT enforced, so new duplicates can still be written.`,`Details: ${JSON.stringify(r)}`,"Find the conflicting documents with:",` ${a}`,"Fix: merge, delete, or update the conflicting documents so each indexed value is unique, then restart the app \u2014 the index build is retried on startup."].join(`
|
|
2
|
+
`)}function Oe(n){let e=Object.keys(n.key),t=e.flatMap(i=>Ce(i).map(a=>({$unwind:{path:`$${a}`,preserveNullAndEmptyArrays:true}}))),r=Object.fromEntries(e.map(i=>[i.replace(/\./g,"_"),`$${i}`]));return [...n.partialFilterExpression?[{$match:n.partialFilterExpression}]:[],...t,{$group:{_id:r,ids:{$addToSet:"$_id"}}},{$match:{$expr:{$gt:[{$size:"$ids"},1]}}},{$limit:100}]}function Ce(n){let e=n.split(".");return e.map((t,r)=>e.slice(0,r+1).join("."))}var Ae=["background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","sparse","storageEngine","textIndexVersion","unique","weights","wildcardProjection","2dsphereIndexVersion"],H=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),_e=n=>n.startsWith("_modelence_"),X=n=>{let e={};for(let t of Ae){let r=n[t];r!==void 0&&(e[t]=r);}return e},ke=(n,e)=>{if(!H(n)||!H(e))return false;let t=Object.entries(n),r=Object.entries(e);return t.length!==r.length?false:t.every(([i,a],c)=>{let[d,h]=r[c]||[];return i===d&&isDeepStrictEqual(a,h)})},pe=(n,e)=>ke(n.key,e.key)?isDeepStrictEqual(X(n),X(e)):false,B=n=>H(n)?Object.entries(n).map(([e,t])=>`${e}:${JSON.stringify(t)}`).join("|"):null,ve=async n=>{try{return await n.listIndexes().toArray()}catch(e){if(e instanceof MongoError&&e.code===26)return [];throw e}},Ee=n=>Object.entries(n).map(([e,t])=>`${e}_${t}`).join("_"),Me=n=>{if(n.name){let t=n.name.startsWith("_modelence_")?n.name:`_modelence_${n.name}`;return {...n,name:t}}let e=Ee(n.key);return {...n,name:`_modelence_${e}`}},f=class n{constructor(e,t){this._chainParent=null;this._chainChild=null;this.name=e,this.schema=t.schema,this.methods=t.methods,this.indexes=t.indexes.map(Me),this.searchIndexes=t.searchIndexes||[],this.indexCreationMode=t.indexCreationMode??"background";}getName(){return this.name}getIndexCreationMode(){return this.indexCreationMode}getSchema(){return this.schema}getSerializedSchema(){return N(this.schema)}getIndexes(){return this.indexes}getSearchIndexes(){return this.searchIndexes}getChainTail(){let e=this;for(;e._chainChild;)e=e._chainChild;return e}getChainRoot(){let e=this;for(;e._chainParent;)e=e._chainParent;return e}extend(e){let t=this.getChainTail();if(this.client||t.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);let r={...t.schema,...e.schema||{}},i=[...t.indexes,...e.indexes||[]],a=[...t.searchIndexes,...e.searchIndexes||[]],c={...t.methods||{},...e.methods||{}},d=new n(this.name,{schema:r,methods:c,indexes:i,searchIndexes:a,indexCreationMode:e.indexCreationMode??t.indexCreationMode});return t._chainChild=d,d._chainParent=t,d}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(e="full"){let t=this.requireCollection(),r=e!=="create-only",i=e!=="drop-only",a=await ve(t),c=new Map,d=new Map,h=new Set,T=s=>{c.set(s.name,s);let l=B(s.key);if(!l)return;let u=d.get(l);u?u.add(s.name):d.set(l,new Set([s.name]));},D=s=>{let l=c.get(s);if(!l)return;c.delete(s);let u=B(l.key);if(!u)return;let x=d.get(u);x&&(x.delete(s),x.size===0&&d.delete(u));};for(let s of a)typeof s.name=="string"&&T({...s,name:s.name});let y=async s=>{if(!(s==="_id_"||h.has(s))){try{await t.dropIndex(s);}catch(l){if(!(l instanceof MongoError&&l.code===27))throw l}h.add(s),D(s);}};if(r){let s=new Set(this.indexes.map(u=>u.name).filter(u=>typeof u=="string")),l=[...c.values()].filter(u=>_e(u.name)&&!s.has(u.name));for(let u of l)await y(u.name);}if(this.indexes.length>0)for(let s of this.indexes){if(!s.name)continue;let l=false,u=c.get(s.name);u&&!pe(u,s)&&(r?await y(u.name):l=true);let x=B(s.key);if(x){let S=[...d.get(x)||[]];for(let C of S)C!==s.name&&(r?await y(C):l=true);}let E=c.get(s.name);if(!(!!E&&pe(E,s))&&i&&!l){try{await t.createIndexes([s]);}catch(S){throw s.unique&&le(S)&&console.error(ue(this.name,s,S)),S}T({name:s.name,key:s.key,...X(s)});}}if(i&&this.searchIndexes.length>0)for(let s of this.searchIndexes)try{await t.createSearchIndexes([s]);}catch(l){if(l instanceof MongoError&&l.code===68&&s.name)await t.dropSearchIndex(s.name),await t.createSearchIndexes([s]);else throw l}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,t){let r=await this.requireCollection().findOne(e,t);return r?this.wrapDocument(r):null}async requireOne(e,t,r){let i=await this.findOne(e,t);if(!i)throw r?r():new Error(`Record not found in ${this.name}`);return i}find(e,t){let r=this.requireCollection().find(e,t?.projection?{projection:t.projection}:void 0);return t?.sort&&r.sort(t.sort),t?.limit&&r.limit(t.limit),t?.skip&&r.skip(t.skip),r}async findById(e){let t=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(t)}async requireById(e,t){let r=await this.findById(e);if(!r)throw t?t():new Error(`Record with id ${e} not found in ${this.name}`);return r}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,t){return (await this.find(e,t).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e,t){return await this.requireCollection().insertOne(e,t)}async create(e,t){let r=$(this.schema,{_id:new ObjectId,...e});return await this.requireCollection().insertOne(r,t),this.wrapDocument(r)}async insertMany(e,t){return await this.requireCollection().insertMany(e,t)}async updateOne(e,t,r){return await this.requireCollection().updateOne(this.getSelector(e),t,r)}async upsertOne(e,t,r){return await this.requireCollection().updateOne(this.getSelector(e),t,{upsert:true,...r})}async updateMany(e,t,r){return await this.requireCollection().updateMany(e,t,r)}async upsertMany(e,t,r){return await this.requireCollection().updateMany(e,t,{upsert:true,...r})}async deleteOne(e,t){return await this.requireCollection().deleteOne(this.getSelector(e),t)}async deleteMany(e,t){return await this.requireCollection().deleteMany(e,t)}async findOneAndUpdate(e,t,r){let i=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,r??{});return i?this.wrapDocument(i):null}async findOneAndUpsert(e,t,r){let i=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,{upsert:true,...r,returnDocument:"after",includeResultMetadata:true});return {doc:i.value?this.wrapDocument(i.value):null,isNew:!!i.lastErrorObject?.upserted}}async findOneAndDelete(e,t){let r=await this.requireCollection().findOneAndDelete(this.getSelector(e),t??{});return r?this.wrapDocument(r):null}async findOneAndReplace(e,t,r){let i=await this.requireCollection().findOneAndReplace(this.getSelector(e),t,r??{});return i?this.wrapDocument(i):null}async replaceOne(e,t,r){return await this.requireCollection().replaceOne(this.getSelector(e),t,r)}async distinct(e,t,r){let i=t??{};return r!==void 0?await this.requireCollection().distinct(e,i,r):await this.requireCollection().distinct(e,i)}watch(e,t){return this.requireCollection().watch(e,t)}aggregate(e,t){return this.requireCollection().aggregate(e,t)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,t){let r=this.getDatabase();if(!this.collection||!r)throw new Error(`Store ${this.name} is not provisioned`);if((await r.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await r.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await r.collection(e).rename(this.name,t);}async vectorSearch({field:e,embedding:t,numCandidates:r,limit:i,projection:a,indexName:c}){return this.aggregate([{$vectorSearch:{index:c||e+"VectorSearch",path:e,queryVector:t,numCandidates:r||100,limit:i||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...a}}])}static vectorIndex({field:e,dimensions:t,similarity:r="cosine",indexName:i}){return {type:"vectorSearch",name:i||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:t,similarity:r}]}}}};var Re=z$1.string.bind(z$1),Ze=z$1.number.bind(z$1),Ne=z$1.date.bind(z$1),je=z$1.boolean.bind(z$1),Fe=z$1.array.bind(z$1),$e=z$1.object.bind(z$1),Pe=z$1.enum.bind(z$1),o={string:Re,number:Ze,date:Ne,boolean:je,array:Fe,object:$e,enum:Pe,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(n){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(n){return {}}};function g(n){return createHash("sha256").update(n).digest("hex")}var ee=new f("_modelenceLinkNonces",{schema:{nonce:o.string(),userId:o.string(),expiresAt:o.date()},indexes:[{key:{nonce:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});async function cn(n){let e=randomBytes(32).toString("hex");return await ee.insertOne({nonce:e,userId:n,expiresAt:new Date(Date.now()+a$1.minutes(10))}),e}async function dn(n){let e=await ee.findOneAndDelete({nonce:n});return e?e.userId:null}var te=new f("_modelenceOAuthExchangeCodes",{schema:{code:o.string(),userId:o.string(),provider:o.string(),codeChallenge:o.string().optional(),expiresAt:o.date()},indexes:[{key:{code:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),Ue=1;async function ln(n,e,t){let r=randomBytes(32).toString("hex");return await te.insertOne({code:g(r),userId:n,provider:e,codeChallenge:g(t),expiresAt:new Date(Date.now()+a$1.minutes(Ue))}),r}async function un(n,e){let t=await te.findOneAndDelete({code:g(n)});return !t||t.expiresAt<new Date||!t.codeChallenge||!e||!Le(g(e),t.codeChallenge)?null:{userId:t.userId,provider:t.provider}}function Le(n,e){return n.length!==e.length?false:timingSafeEqual(Buffer.from(n,"utf8"),Buffer.from(e,"utf8"))}var w=new f("_modelenceSessions",{schema:{authToken:o.string(),createdAt:o.date(),expiresAt:o.date(),userId:o.userId().nullable(),lastActiveDate:o.date().optional()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0},{key:{userId:1}}]});async function me(n){if(n){let e=g(n),t=await w.findOne({authToken:e}),r=/^[0-9a-f]{64}$/i.test(n);if(!t&&!r&&(t=await w.findOne({authToken:n}),t&&await w.updateOne({_id:t._id},{$set:{authToken:e}})),t)return {authToken:n,expiresAt:new Date(t.expiresAt),userId:t.userId??null}}return await We()}async function pn(n,e){await w.updateOne({authToken:g(n)},{$set:{userId:e}});}async function hn(n){await w.updateOne({authToken:g(n)},{$set:{userId:null}});}async function mn(n){await w.deleteMany({userId:n});}async function We(n=null){let e=randomBytes(32).toString("base64url"),t=Date.now(),r=new Date(t+a$1.days(7));return await w.insertOne({authToken:g(e),createdAt:new Date(t),expiresAt:r,userId:n}),{authToken:e,expiresAt:r,userId:n}}async function Qe(n){let e=Date.now(),t=new Date(e+a$1.days(7));await w.updateOne({authToken:g(n.authToken)},{$set:{lastActiveDate:new Date(e),expiresAt:t}});}function Ke(n,e){n.cookie("authToken",e,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/",maxAge:a$1.days(7)});}function yn(n){n.clearCookie("authToken",{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/"});}var fn=new Z("_system.session",{stores:[w,ee,te],mutations:{init:async function(n,{session:e,user:t,res:r}){return r&&e?.userId&&Ke(r,e.authToken),{session:e,user:t,configs:b(),...se()?{setupRequired:true}:{}}},heartbeat:async function(n,{session:e}){e&&await Qe(e);}}});var ye=new f("_modelenceUsers",{schema:{handle:o.string(),emails:o.array(o.object({address:o.string(),verified:o.boolean()})).optional(),status:o.enum(["active","disabled","deleted"]).optional(),firstName:o.string().optional(),lastName:o.string().optional(),avatarUrl:o.string().optional(),createdAt:o.date(),disabledAt:o.date().optional(),deletedAt:o.date().optional(),roles:o.array(o.string()).optional(),authMethods:o.object({password:o.object({hash:o.string()}).optional(),google:o.object({id:o.string()}).optional(),github:o.object({id:o.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"emails.address":1},unique:true,collation:{locale:"en",strength:2},partialFilterExpression:{"emails.address":{$exists:true}}},{key:{"authMethods.google.id":1},sparse:true,unique:true},{key:{"authMethods.github.id":1},sparse:true,unique:true}]}),Sn=new f("_modelenceDisposableEmailDomains",{schema:{domain:o.string(),addedAt:o.date()},indexes:[{key:{domain:1},unique:true}]}),bn=new f("_modelenceEmailVerificationTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),wn=new f("_modelenceResetPasswordTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),Dn=new f("_modelenceMagicLinkTokens",{schema:{email:o.string(),token:o.string(),code:o.string(),attempts:o.number(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{email:1}},{key:{expiresAt:1},expireAfterSeconds:0}]});var fe=new Map,_={authenticated:null,unauthenticated:null};function On(n,e){_.authenticated=e.authenticated,_.unauthenticated=e.unauthenticated;for(let[t,r]of Object.entries(n))fe.set(t,r);}function ge(){return _.unauthenticated?[_.unauthenticated]:[]}function Te(){return _.authenticated?[_.authenticated]:[]}function ne(n,e){let t=e.find(r=>!Ve(n,r));if(t)throw new Error(`Access denied - missing permission: '${t}'`)}function Ve(n,e){for(let t of n)if(fe.get(t)?.permissions?.includes(e))return true;return false}async function xe(n){let e=await me(n),t=e.userId?await ye.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,r=t?{id:t._id.toString(),handle:t.handle,roles:t.roles||[],hasRole:a=>(t.roles||[]).includes(a),requireRole:a=>{if(!(t.roles||[]).includes(a))throw new Error(`Access denied - role '${a}' required`)},firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0}:null,i=r?Te():ge();return {user:r,session:e,roles:i}}var k=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function Je(){return typeof window!="object"}function O(){if(!Je())throw new Error("This function can only be called on the server")}function Rn(n){return n.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var v=new Map;function He(n){let e=v.get(n.id);return e||(e=new Map,v.set(n.id,e)),e}async function Xe(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({}),authToken:z$1.string().nullish(),clientInfo:z$1.object({screenWidth:z$1.number(),screenHeight:z$1.number(),windowWidth:z$1.number(),windowHeight:z$1.number(),pixelRatio:z$1.number(),orientation:z$1.string().nullable()}).optional()}).safeParse(e);if(!t.success){n.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${t.error.message}`});return}let{subscriptionId:r,method:i,args:a,authToken:c,clientInfo:d}=t.data,h=He(n),T=h.get(r);if(T)if(T.cleanup)try{T.cleanup();}catch(y){console.error("[LiveQuery] Error cleaning up existing subscription:",y);}else T.aborted=true;let D={cleanup:null};h.set(r,D);try{let{session:y,user:s,roles:l}=await xe(c??null),u={session:y,user:s,roles:l,clientInfo:d??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:n.handshake.address,userAgent:n.handshake.headers["user-agent"]},req:null,res:null},x=await Se(i,a,u),E=async()=>{let b=a$2(await x.fetch());D.aborted||n.emit("liveQueryData",{subscriptionId:r,data:b,typeMap:b$1(b)});},M=!0,S=!1,C=()=>{D.aborted||!M||S||(M=!1,S=!0,E().catch(b=>{D.aborted||(console.error(`[LiveQuery] Error fetching data for ${i}:`,b),n.emit("liveQueryError",{subscriptionId:r,error:b instanceof Error?b.message:String(b)}));}).finally(()=>{S=!1,C();}));},U=x.watch({publish:()=>{M=!0,C();}});if(D.aborted){if(U)try{U();}catch(b){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",b);}return}D.cleanup=U||null,C();}catch(y){h.delete(r),console.error(`[LiveQuery] Error in ${i}:`,y),n.emit("liveQueryError",{subscriptionId:r,error:y instanceof Error?y.message:String(y)});}}function Ge(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1)}).safeParse(e);if(!t.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${t.error.message}`);return}let{subscriptionId:r}=t.data,i=v.get(n.id);if(!i)return;let a=i.get(r);if(a){if(a.cleanup)try{a.cleanup();}catch(c){console.error("[LiveQuery] Error in cleanup:",c);}else a.aborted=true;i.delete(r);}}function Ye(n){let e=v.get(n.id);if(e){for(let t of e.values())if(t.cleanup)try{t.cleanup();}catch(r){console.error("[LiveQuery] Error in cleanup on disconnect:",r);}else t.aborted=true;v.delete(n.id);}}var q={};function Vn(n,e){return O(),be(n),z("query",n,e)}function Bn(n,e){return O(),be(n),z("mutation",n,e)}function Jn(n,e){return O(),we(n),z("query",n,e)}function Hn(n,e){return O(),we(n),z("mutation",n,e)}function be(n){if(n.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${n})`)}function we(n){if(!n.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${n})`)}function z(n,e,t){if(O(),q[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof t=="function"?t:t.handler,i=typeof t=="function"?[]:t.permissions??[];q[e]={type:n,name:e,handler:r,permissions:i};}async function Xn(n$1,e,t){O();let r=q[n$1];if(!r)throw new Error(`Method with name '${n$1}' is not defined.`);let{type:i,handler:a}=r,c=n("method",`method:${n$1}`,{type:i,args:j$1(e)}),d;try{ne(t.roles,r.permissions),d=await a(e,t);}catch(h){throw o$1(h instanceof Error?h:new Error(String(h))),c.end("error"),h}return c.end(),d}async function Se(n$1,e,t){O();let r=q[n$1];if(!r)throw new Error(`Method with name '${n$1}' is not defined.`);let{type:i,handler:a}=r;if(i!=="query")throw new Error("Live methods are only supported for queries");let c=n("method",`method:${n$1}:live`,{type:i,args:j$1(e)}),d;try{if(ne(t.roles,r.permissions),d=await a(e,t),!(d instanceof k))throw new Error(`Live query handler for '${n$1}' must return a LiveData object with fetch and watch functions. See https://docs.modelence.com/live-queries`)}catch(h){throw o$1(h instanceof Error?h:new Error(String(h))),c.end("error"),h}return c.end(),d}
|
|
3
|
+
export{k as A,Rn as B,Vn as C,Bn as D,Jn as E,Hn as F,Xn as G,Xe as H,Ge as I,Ye as J,Z as a,se as b,f as c,o as d,g as e,cn as f,dn as g,ln as h,un as i,w as j,me as k,pn as l,hn as m,mn as n,We as o,Ke as p,yn as q,fn as r,ye as s,Sn as t,bn as u,wn as v,Dn as w,On as x,ge as y,xe as z};//# sourceMappingURL=chunk-6CIFSSQP.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-6CIFSSQP.js.map
|