modelence 0.24.1 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import O,{join,dirname}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import G from'open';import R from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import Ee 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 G(a.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return {token:await W(e,s)}}async function W(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let r=await X(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 X(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",b="project.json";async function Q(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 Z(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${x} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function ee(e){return String(e).replace(/"/g,'\\"')}async function te(){try{let e=await promises.readFile(join(process.cwd(),C,b),"utf8"),{appId:t}=JSON.parse(e);return typeof t=="string"&&t?t:void 0}catch{return}}async function oe(e){let t=join(process.cwd(),C),o=join(t,b),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
- `);}var $=".claude",w=join($,"settings.json"),D="modelence@modelence",I={modelence:{source:{source:"github",repo:"modelence/modelence"}}};async function ne(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch{try{await promises.mkdir(join(process.cwd(),$),{recursive:!0}),await promises.writeFile(e,JSON.stringify({extraKnownMarketplaces:I,enabledPlugins:{[D]:!0}},null,2)+`
4
- `),console.log(`Enabled the Modelence Claude Code plugin in ${w}`);}catch(o){console.warn(`Failed to create ${w}:`,o);}return}try{let n=JSON.parse(t)?.enabledPlugins?.[D];n!==!0&&console.warn(`Note: the Modelence plugin is ${n===!1?"disabled":"not enabled"} in ${w}. To get Modelence tools and docs in Claude Code, add "${D}": true under "enabledPlugins", and declare the marketplace under "extraKnownMarketplaces": ${JSON.stringify(I)}.`);}catch{console.warn(`Could not parse ${w} to check the Modelence plugin status.`);}}async function re(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 j(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 re(t),await Z()||(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 te()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await Q(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}="${ee(g)}"`).join(`
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
+ `);}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
+ claude plugin marketplace add ${I}
5
+ claude plugin install ${N}
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
+ `),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(`
5
8
  `);if(await promises.writeFile(t,i.trim()+`
6
- `),console.log(`Successfully configured ${x} file`),r.appId)try{await oe(r.appId),console.log(`Recorded the app ID in ${C}/${b}`);}catch(c){console.warn(`Failed to record the app ID in ${C}/${b}:`,c);}await ne(),n&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session."),!n&&a.MODELENCE_RUNTIME==="local"&&(console.log(`
9
+ `),console.log(`Successfully configured ${x} file`),r.appId)try{await se(r.appId),console.log(`Recorded the app ID in ${C}/${k}`);}catch(c){console.warn(`Failed to record the app ID in ${C}/${k}:`,c);}await le(),!e.token&&process.stdin.isTTY&&await de(),n&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, start a new session."),!n&&a.MODELENCE_RUNTIME==="local"&&(console.log(`
7
10
  Next step \u2014 run the app on this machine:
8
11
  `),console.log(" npm install (if you haven't already)"),console.log(` npm run dev (starts the app)
9
- `));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var ae=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()});async function _(){let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");return ae.parse(o)}var N=null,T=null;function de(){if(!N)throw new Error("Environment variables not loaded");return N}function L(){if(!T)throw new Error("Configuration not loaded");return T}function F(e){return `${de().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function u(){let{serverDir:e,serverEntry:t}=L();return join(e,t).replace(/\\/g,"/")}function B(){return L().postBuildCommand}function S(e){let t=M("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function M(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{T=await _();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await R.readFile(join(process.cwd(),".modelence.env"),"utf-8");N=parse(e);}catch(e){if(e.code==="ENOENT")N={};else throw e}}async function me(){let e=B();if(e){console.log("Running post-build command..."),execSync(e);return}await fe(),await ge();}async function fe(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:O.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function ge(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:O.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:O.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},o,true));}async function we(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[u()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function P(){console.log("Building Modelence project...");try{let e=S();await R.rm(e,{recursive:!0,force:!0}),await we(),await me(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await R.access(M());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function J(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||F("");await P(),await ve(n);let{token:r}=await y(s),{bundleName:a}=await ye(e.app,e.env,n,r,s);await promises.unlink(n),await Ce(e.app,e.env,a,join(".modelence","build","app.mjs"),r,s);}async function ve(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Ee("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,c)=>{t.on("close",i),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","package-lock.json","next.config.js","next.config.ts","modelence.config.ts"],r=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.file(m(i),{name:i});for(let i of r)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.directory(m(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ye(e,t,o,n,s){let r=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:a,bundleName:i}=await r.json(),c=await promises.readFile(o),g=await fetch(a,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!g.ok)throw new Error(`Failed to upload bundle: ${g.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function Ce(e,t,o,n,s,r){let a=await fetch(`${r}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:n})});if(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:i}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function z(e={}){console.log("Starting Modelence dev server...");let t=u(),o=O.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function K(){console.log("Starting Modelence production server...");let e=u(),t=O.basename(e,O.extname(e)),o=S(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Me=fileURLToPath(import.meta.url),Oe=dirname(Me),Ie=JSON.parse(readFileSync(join(Oe,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Ie.version);f.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await j(e);});f.command("build").description("Build the application").action(async()=>{await E(),await P();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await E(),await J(e);});f.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await E(),z(e);});f.command("start").description("Start production server").action(async()=>{await E(),K();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
12
+ `));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var fe=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function F(){let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");return fe.parse(o)}var S=null,M=null;function he(){if(!S)throw new Error("Environment variables not loaded");return S}function B(){if(!M)throw new Error("Configuration not loaded");return M}function U(e){return `${he().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:t}=B();return join(e,t).replace(/\\/g,"/")}function A(){return B().postBuildCommand}function P(e){let t=O("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function O(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{M=await F();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await V.readFile(join(process.cwd(),".modelence.env"),"utf-8");S=parse(e);}catch(e){if(e.code==="ENOENT")S={};else throw e}}async function ye(){let e=A();if(e){console.log("Running post-build command..."),execSync(e);return}await Ce(),await ke();}async function Ce(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:L.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function ke(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:L.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:L.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},o,true));}async function Ne(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[p()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function D(){console.log("Building Modelence project...");try{let e=P();await V.rm(e,{recursive:!0,force:!0}),await Ne(),await ye(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await V.access(O());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function K(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||U("");await D(),await Pe(n);let{token:r}=await y(s),{bundleName:a}=await De(e.app,e.env,n,r,s);await promises.unlink(n),await Te(e.app,e.env,a,join(".modelence","build","app.mjs"),r,s);}async function Pe(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Se("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,c)=>{t.on("close",i),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","package-lock.json","next.config.js","next.config.ts","modelence.config.ts"],r=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.file(m(i),{name:i});for(let i of r)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.directory(m(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function De(e,t,o,n,s){let r=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:a,bundleName:i}=await r.json(),c=await promises.readFile(o),g=await fetch(a,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!g.ok)throw new Error(`Failed to upload bundle: ${g.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function Te(e,t,o,n,s,r){let a=await fetch(`${r}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:n})});if(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:i}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function q(e={}){console.log("Starting Modelence dev server...");let t=p(),o=L.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function Y(){console.log("Starting Modelence production server...");let e=p(),t=L.basename(e,L.extname(e)),o=P(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Re=fileURLToPath(import.meta.url),Fe=dirname(Re),Be=JSON.parse(readFileSync(join(Fe,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Be.version);f.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await R(e);});f.command("build").description("Build the application").action(async()=>{await E(),await D();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await E(),await K(e);});f.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await E(),q(e);});f.command("start").description("Start production server").action(async()=>{await E(),Y();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
10
13
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACES","ensureClaudePluginEnabled","settingsPath","enabled","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":";+dAkBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAI,gBAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,EAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAM,IAAI,IAAID,CAAe,CAAA,CAC/BJ,CAAAA,EACFK,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,OAAQ,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,MAAME,CAAAA,CAAYR,CAAAA,CAAMI,CAAI,CAE3B,CACjB,CAEA,eAAeI,CAAAA,CAAYR,CAAAA,CAAcI,EAA+B,CAGtE,IAAMK,CAAAA,C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C,CAAA,CACnD,OAAO,qBAAA,CAAuB,0DAA0D,EACxF,MAAA,CAAO,mBAAA,CAAqB,gBAAA,CAAkB,6BAA6B,EAC3E,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAMD,EAAMC,CAAO,EACrB,CAAC,CAAA,CAEHmF,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMrD,GAAQ,CACd,MAAMc,CAAAA,GACR,CAAC,CAAA,CAEHuC,CAAAA,CACG,OAAA,CAAQ,QAAQ,EAChB,WAAA,CAAY,2BAA2B,EACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,EACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,CAAA,CAC5C,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACN,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,EAEHmF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,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 { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n 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_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: 'modelence/modelence' } },\n};\n\n/*\n Makes the Modelence Claude Code plugin available in connected projects that\n didn't start from the template (which ships this file). Only ever creates\n the file: an existing settings.json is the user's own — a missing or\n explicitly disabled plugin entry there gets a hint, not an edit, so a\n deliberate opt-out is never flipped back on. The file is inert for people\n who don't use Claude Code, and like the project file, failing to write it\n doesn't fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch {\n // Missing — create it with just the plugin enabled.\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(\n settingsPath,\n JSON.stringify(\n {\n extraKnownMarketplaces: CLAUDE_MARKETPLACES,\n enabledPlugins: { [CLAUDE_PLUGIN_ID]: true },\n },\n null,\n 2\n ) + '\\n'\n );\n console.log(`Enabled the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to create ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n return;\n }\n\n try {\n const settings = JSON.parse(content);\n const enabled = settings?.enabledPlugins?.[CLAUDE_PLUGIN_ID];\n if (enabled !== true) {\n console.warn(\n `Note: the Modelence plugin is ${enabled === false ? 'disabled' : 'not enabled'} in ` +\n `${CLAUDE_SETTINGS_FILE}. To get Modelence tools and docs in Claude Code, add ` +\n `\"${CLAUDE_PLUGIN_ID}\": true under \"enabledPlugins\", and declare the marketplace under ` +\n `\"extraKnownMarketplaces\": ${JSON.stringify(CLAUDE_MARKETPLACES)}.`\n );\n }\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE} to check the Modelence plugin status.`);\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\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n\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', 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,CAA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B,6BAA6B,EAC3E,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAMD,EAAMC,CAAO,EACrB,CAAC,CAAA,CAEHmF,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMrD,GAAQ,CACd,MAAMc,CAAAA,GACR,CAAC,CAAA,CAEHuC,CAAAA,CACG,OAAA,CAAQ,QAAQ,EAChB,WAAA,CAAY,2BAA2B,EACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,EACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,CAAA,CAC5C,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACN,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,EAEHmF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,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}\\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', 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,2 +1,2 @@
1
- import {a,b as b$2}from'./chunk-NMG65UCR.js';import {W as W$1,b as b$1,g,S,v as v$1,r,w,j}from'./chunk-VKGZ35WJ.js';import v from'react';import k from'react-dom/client';import {jsx}from'react/jsx-runtime';function h(t){return {getConfig(e){return b$1(`${t}.${e}`)},query(e,...r){let n=r[0]??{};return {queryKey:[t,e,n],queryFn:()=>W$1(`${t}.${e}`,n)}},mutation(e){return {mutationFn:r=>W$1(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:n})=>W$1(`${t}.${e}`,r(n))}}}}var Q=h("_system");function W(t){let e={};if(typeof t!="string")return e;let r=t.indexOf("?");if(r===-1)return e;let n=t.indexOf("#",r),c=t.slice(r+1,n===-1?void 0:n);for(let o of c.split("&")){if(!o)continue;let i=o.indexOf("="),p=i===-1?o:o.slice(0,i),l=i===-1?"":o.slice(i+1),s=K(p);s&&(s in e||(e[s]=K(l)));}return e}function K(t){let e=t.replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}var M=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){g()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){g()?.joinChannel({category:this.category,id:e});}leaveChannel(e){g()?.leaveChannel({category:this.category,id:e});}};var O="useClient"in v?v.useClient(a):a;var b="__MODELENCE_STATE__";function H(){return typeof document>"u"?false:document.getElementById(b)!==null}function D(){if(typeof document>"u")return null;let t=document.getElementById(b);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var q="__modelence_ssr_snapshot__";function $(t){globalThis[q]=t;}function Xe(){return globalThis[q]??null}function I(t){if(typeof window>"u"){$(t);return}let{loadingElement:e,routesElement:r$1,favicon:n,errorHandler:c,router:o,setupElement:i}=t;c&&S(c),window.addEventListener("pageshow",u=>{u.persisted&&v$1();});let p=H(),l=D();l?.session&&(r(l.session),w());let s=document.getElementById("root"),w$1=window.location.pathname+window.location.search,x=o?o({children:r$1,location:w$1}):r$1,_=j()?x:jsx(b$2,{children:x}),T=jsx(v.StrictMode,{children:jsx(O,{loadingElement:e,setupElement:i,children:_})});if(p?k.hydrateRoot(s,T):k.createRoot(s).render(T),n){let u=document.querySelector("link[rel~='icon']");if(u)u.href=n;else {let f=document.createElement("link");f.rel="icon",f.href=n,document.head.appendChild(f);}}}export{h as a,Q as b,Xe as c,I as d,W as e,M as f,O as g};//# sourceMappingURL=chunk-BQ4WG67Z.js.map
2
- //# sourceMappingURL=chunk-BQ4WG67Z.js.map
1
+ import {a,b as b$2}from'./chunk-FXPFIA66.js';import {W as W$1,b as b$1,g,S,v as v$1,r,w,j}from'./chunk-VKGZ35WJ.js';import v from'react';import k from'react-dom/client';import {jsx}from'react/jsx-runtime';function h(t){return {getConfig(e){return b$1(`${t}.${e}`)},query(e,...r){let n=r[0]??{};return {queryKey:[t,e,n],queryFn:()=>W$1(`${t}.${e}`,n)}},mutation(e){return {mutationFn:r=>W$1(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:n})=>W$1(`${t}.${e}`,r(n))}}}}var Q=h("_system");function W(t){let e={};if(typeof t!="string")return e;let r=t.indexOf("?");if(r===-1)return e;let n=t.indexOf("#",r),c=t.slice(r+1,n===-1?void 0:n);for(let o of c.split("&")){if(!o)continue;let i=o.indexOf("="),p=i===-1?o:o.slice(0,i),l=i===-1?"":o.slice(i+1),s=K(p);s&&(s in e||(e[s]=K(l)));}return e}function K(t){let e=t.replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}var M=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){g()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){g()?.joinChannel({category:this.category,id:e});}leaveChannel(e){g()?.leaveChannel({category:this.category,id:e});}};var O="useClient"in v?v.useClient(a):a;var b="__MODELENCE_STATE__";function H(){return typeof document>"u"?false:document.getElementById(b)!==null}function D(){if(typeof document>"u")return null;let t=document.getElementById(b);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var q="__modelence_ssr_snapshot__";function $(t){globalThis[q]=t;}function Xe(){return globalThis[q]??null}function I(t){if(typeof window>"u"){$(t);return}let{loadingElement:e,routesElement:r$1,favicon:n,errorHandler:c,router:o,setupElement:i}=t;c&&S(c),window.addEventListener("pageshow",u=>{u.persisted&&v$1();});let p=H(),l=D();l?.session&&(r(l.session),w());let s=document.getElementById("root"),w$1=window.location.pathname+window.location.search,x=o?o({children:r$1,location:w$1}):r$1,_=j()?x:jsx(b$2,{children:x}),T=jsx(v.StrictMode,{children:jsx(O,{loadingElement:e,setupElement:i,children:_})});if(p?k.hydrateRoot(s,T):k.createRoot(s).render(T),n){let u=document.querySelector("link[rel~='icon']");if(u)u.href=n;else {let f=document.createElement("link");f.rel="icon",f.href=n,document.head.appendChild(f);}}}export{h as a,Q as b,Xe as c,I as d,W as e,M as f,O as g};//# sourceMappingURL=chunk-7JUFVY6Q.js.map
2
+ //# sourceMappingURL=chunk-7JUFVY6Q.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/auth/client/deepLink.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","parseDeepLinkParams","url","params","queryStart","fragmentStart","query","pair","eq","rawKey","rawValue","safeDecode","value","plus","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setupElement","setErrorHandler","event","revalidateSessionOnPageShow","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"6MAuFO,SAASA,CAAAA,CAA8CC,CAAAA,CAAoB,CAChF,OAAO,CACL,SAAA,CACEC,CAAAA,CACqD,CAErD,OAAOC,GAAAA,CAAiB,CAAA,EAAGF,CAAU,CAAA,CAAA,EAAIC,CAAG,CAAA,CAAE,CAChD,CAAA,CAEA,KAAA,CACEE,CAAAA,CAAAA,GACGC,CAAAA,CAGH,CACA,IAAMC,CAAAA,C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AA,CAMHA,CAAAA,CAAK,IAAA,CAAOpB,CAAAA,CAAAA,KANH,CACT,IAAMqB,CAAAA,CAAU,QAAA,CAAS,aAAA,CAAc,MAAM,CAAA,CAC7CA,CAAAA,CAAQ,GAAA,CAAM,OACdA,CAAAA,CAAQ,IAAA,CAAOrB,CAAAA,CACf,QAAA,CAAS,IAAA,CAAK,WAAA,CAAYqB,CAAO,EACnC,CAGF,CACF","file":"chunk-BQ4WG67Z.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","/**\n * Deep-link query parsing that works on bare React Native.\n *\n * `new URL(url).searchParams` is not usable here: React Native's `URL` is a\n * partial implementation that throws on `searchParams` access, and Expo only\n * appears to work because it installs a polyfill. Parsing the query string\n * directly keeps the documented callback snippet working on both.\n */\n\n/**\n * Reads query parameters out of a deep link such as `myapp://auth?code=abc`.\n *\n * Only the query component is considered — everything from the first `?` up to\n * an optional `#` fragment. Values are percent-decoded, with `+` treated as a\n * space to match `application/x-www-form-urlencoded`, which is how the server's\n * `URL.searchParams.set` encodes them.\n */\nexport function parseDeepLinkParams(url: string): Record<string, string> {\n const params: Record<string, string> = {};\n\n if (typeof url !== 'string') return params;\n\n const queryStart = url.indexOf('?');\n if (queryStart === -1) return params;\n\n const fragmentStart = url.indexOf('#', queryStart);\n const query = url.slice(queryStart + 1, fragmentStart === -1 ? undefined : fragmentStart);\n\n for (const pair of query.split('&')) {\n if (!pair) continue;\n\n const eq = pair.indexOf('=');\n const rawKey = eq === -1 ? pair : pair.slice(0, eq);\n const rawValue = eq === -1 ? '' : pair.slice(eq + 1);\n\n const key = safeDecode(rawKey);\n if (!key) continue;\n\n // First occurrence wins, so a crafted link cannot override an earlier\n // parameter by appending a duplicate.\n if (!(key in params)) {\n params[key] = safeDecode(rawValue);\n }\n }\n\n return params;\n}\n\n/**\n * Percent-decodes a component, falling back to the raw text.\n *\n * `decodeURIComponent` throws on malformed escapes like `%zz`; a deep link is\n * attacker-reachable input, so a bad escape must not take down the app's link\n * handler.\n */\nfunction safeDecode(value: string): string {\n const plus = value.replace(/\\+/g, ' ');\n try {\n return decodeURIComponent(plus);\n } catch {\n return plus;\n }\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n signInWithOAuth,\n loginWithOAuth,\n resumeOAuthPopup,\n cancelOAuthPopup,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport { parseDeepLinkParams } from './auth/client/deepLink';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport {\n hydrateSession,\n revalidateSessionOnPageShow,\n startSessionHeartbeat,\n type SessionInitPayload,\n} from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (no Modelence Cloud connection, no local database). Pass\n `null` to disable the screen entirely.\n */\n setupElement?: React.ReactNode;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router, setupElement } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Revalidate session when page is restored from BFCache (e.g. back navigation after logout)\n window.addEventListener('pageshow', (event) => {\n if (event.persisted) {\n void revalidateSessionOnPageShow();\n }\n });\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement} setupElement={setupElement}>\n {appTree}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/auth/client/deepLink.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","parseDeepLinkParams","url","params","queryStart","fragmentStart","query","pair","eq","rawKey","rawValue","safeDecode","value","plus","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setupElement","setErrorHandler","event","revalidateSessionOnPageShow","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appT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AA,CAAcK,CAAAA,CACxD,QAAA,CAAAW,CAAAA,CACH,CAAA,CACF,CAAA,CASF,GANIP,CAAAA,CACFY,CAAAA,CAAS,WAAA,CAAYR,CAAAA,CAAWO,CAAI,CAAA,CAEpCC,CAAAA,CAAS,UAAA,CAAWR,CAAS,EAAE,MAAA,CAAOO,CAAI,CAAA,CAGxClB,CAAAA,CAAS,CACX,IAAMoB,CAAAA,CAAO,QAAA,CAAS,aAAA,CAAc,mBAAmB,CAAA,CACvD,GAAKA,CAAAA,CAMHA,CAAAA,CAAK,IAAA,CAAOpB,CAAAA,CAAAA,KANH,CACT,IAAMqB,CAAAA,CAAU,QAAA,CAAS,aAAA,CAAc,MAAM,CAAA,CAC7CA,CAAAA,CAAQ,GAAA,CAAM,OACdA,CAAAA,CAAQ,IAAA,CAAOrB,CAAAA,CACf,QAAA,CAAS,IAAA,CAAK,WAAA,CAAYqB,CAAO,EACnC,CAGF,CACF","file":"chunk-7JUFVY6Q.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","/**\n * Deep-link query parsing that works on bare React Native.\n *\n * `new URL(url).searchParams` is not usable here: React Native's `URL` is a\n * partial implementation that throws on `searchParams` access, and Expo only\n * appears to work because it installs a polyfill. Parsing the query string\n * directly keeps the documented callback snippet working on both.\n */\n\n/**\n * Reads query parameters out of a deep link such as `myapp://auth?code=abc`.\n *\n * Only the query component is considered — everything from the first `?` up to\n * an optional `#` fragment. Values are percent-decoded, with `+` treated as a\n * space to match `application/x-www-form-urlencoded`, which is how the server's\n * `URL.searchParams.set` encodes them.\n */\nexport function parseDeepLinkParams(url: string): Record<string, string> {\n const params: Record<string, string> = {};\n\n if (typeof url !== 'string') return params;\n\n const queryStart = url.indexOf('?');\n if (queryStart === -1) return params;\n\n const fragmentStart = url.indexOf('#', queryStart);\n const query = url.slice(queryStart + 1, fragmentStart === -1 ? undefined : fragmentStart);\n\n for (const pair of query.split('&')) {\n if (!pair) continue;\n\n const eq = pair.indexOf('=');\n const rawKey = eq === -1 ? pair : pair.slice(0, eq);\n const rawValue = eq === -1 ? '' : pair.slice(eq + 1);\n\n const key = safeDecode(rawKey);\n if (!key) continue;\n\n // First occurrence wins, so a crafted link cannot override an earlier\n // parameter by appending a duplicate.\n if (!(key in params)) {\n params[key] = safeDecode(rawValue);\n }\n }\n\n return params;\n}\n\n/**\n * Percent-decodes a component, falling back to the raw text.\n *\n * `decodeURIComponent` throws on malformed escapes like `%zz`; a deep link is\n * attacker-reachable input, so a bad escape must not take down the app's link\n * handler.\n */\nfunction safeDecode(value: string): string {\n const plus = value.replace(/\\+/g, ' ');\n try {\n return decodeURIComponent(plus);\n } catch {\n return plus;\n }\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n signInWithOAuth,\n loginWithOAuth,\n resumeOAuthPopup,\n cancelOAuthPopup,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport { parseDeepLinkParams } from './auth/client/deepLink';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport {\n hydrateSession,\n revalidateSessionOnPageShow,\n startSessionHeartbeat,\n type SessionInitPayload,\n} from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (no Modelence Cloud connection, no local database). Pass\n `null` to disable the screen entirely.\n */\n setupElement?: React.ReactNode;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router, setupElement } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Revalidate session when page is restored from BFCache (e.g. back navigation after logout)\n window.addEventListener('pageshow', (event) => {\n if (event.persisted) {\n void revalidateSessionOnPageShow();\n }\n });\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement} setupElement={setupElement}>\n {appTree}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
- import {x,q as q$1,i,t as t$1,s,u,W}from'./chunk-VKGZ35WJ.js';import {useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';import {QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var t={page:{minHeight:"100vh",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",color:"#111827"},container:{maxWidth:"576px",width:"100%"},logoWrap:{display:"flex",justifyContent:"center",marginBottom:"32px"},title:{fontSize:"30px",lineHeight:"36px",fontWeight:700,textAlign:"center",margin:0},subtitle:{marginTop:"16px",color:"#4b5563",textAlign:"center"},steps:{marginTop:"32px",listStyle:"none",padding:0,display:"flex",flexDirection:"column",gap:"16px"},step:{display:"flex",gap:"16px",alignItems:"flex-start",backgroundColor:"#ffffff",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"16px"},stepNumber:{flex:"none",width:"28px",height:"28px",borderRadius:"9999px",backgroundColor:"#111827",color:"#ffffff",fontSize:"14px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},stepText:{color:"#374151",lineHeight:"28px"},code:{fontSize:"14px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",backgroundColor:"#e5e7eb",borderRadius:"4px",padding:"2px 4px"},footer:{marginTop:"32px",fontSize:"14px",color:"#6b7280",textAlign:"center"}};function m(){return jsx("div",{style:t.page,children:jsxs("div",{style:t.container,children:[jsx("div",{style:t.logoWrap,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"80",height:"80",viewBox:"0 0 48 48",fill:"none","aria-label":"Modelence Logo",children:jsx("path",{fill:"#5509D9",d:"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z"})})}),jsx("h1",{style:t.title,children:"Connect this project to Modelence Cloud"}),jsx("p",{style:t.subtitle,children:"One quick step before you can use this app locally."}),jsxs("ol",{style:t.steps,children:[jsxs(y,{number:1,children:["Run ",jsx("code",{style:t.code,children:"npx modelence setup"})," in the project folder."]}),jsx(y,{number:2,children:"Your browser opens \u2014 log in and choose your environment."}),jsxs(y,{number:3,children:["Restart the dev server (",jsx("code",{style:t.code,children:"npm run dev"}),")."]})]}),jsx("p",{style:t.footer,children:"This page refreshes automatically once the project is connected."})]})})}function y({number:n,children:o}){return jsxs("li",{style:t.step,children:[jsx("span",{style:t.stepNumber,children:n}),jsx("span",{style:t.stepText,children:o})]})}var N="__MODELENCE_STATE__",_=3e3,w=false;function L(){return typeof document<"u"&&document.getElementById(N)!==null}function U({children:n,loadingElement:o,setupElement:i}){let d=typeof window>"u",[c,l]=useState(()=>!d&&!x()&&!L()),[u$1,g]=useState(()=>!d&&x()&&q$1());return useEffect(()=>{async function s$1(){if(!w){if(w=true,x()){t$1()&&await s(),g(q$1());return}await u(),g(q$1()),l(false);}}s$1();},[]),useEffect(()=>{if(!u$1)return;let s=false,f;async function S(){try{let{setupRequired:P}=await W("_system.setupStatus",{},{errorHandler:()=>{}});if(!P){window.location.reload();return}}catch{}s||(f=setTimeout(S,_));}return f=setTimeout(S,_),()=>{s=true,clearTimeout(f);}},[u$1]),c?o??jsx("div",{children:"Loading..."}):u$1&&i!==null?i??jsx(m,{}):n}var k="__MODELENCE_QUERY_STATE__";function q(){if(typeof document>"u")return;let n=document.getElementById(k);if(!(!n||!n.textContent))try{return JSON.parse(n.textContent)}catch(o){console.error("Modelence: failed to parse SSR query state",o);return}}function K({children:n,client:o,dehydratedState:i$1}){let[d]=useState(()=>{let l=o??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&i(l),l}),c=i$1??q();return jsx(QueryClientProvider,{client:d,children:jsx(HydrationBoundary,{state:c,children:n})})}
2
- export{U as a,K as b};//# sourceMappingURL=chunk-NMG65UCR.js.map
3
- //# sourceMappingURL=chunk-NMG65UCR.js.map
1
+ import {x,q as q$1,i,t as t$1,s,u,W}from'./chunk-VKGZ35WJ.js';import {useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';import {QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var t={page:{minHeight:"100vh",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",color:"#111827"},container:{maxWidth:"576px",width:"100%"},logoWrap:{display:"flex",justifyContent:"center",marginBottom:"32px"},title:{fontSize:"30px",lineHeight:"36px",fontWeight:700,textAlign:"center",margin:0},subtitle:{marginTop:"16px",color:"#4b5563",textAlign:"center"},steps:{marginTop:"32px",listStyle:"none",padding:0,display:"flex",flexDirection:"column",gap:"16px"},step:{display:"flex",gap:"16px",alignItems:"flex-start",backgroundColor:"#ffffff",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"16px"},stepNumber:{flex:"none",width:"28px",height:"28px",borderRadius:"9999px",backgroundColor:"#111827",color:"#ffffff",fontSize:"14px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},stepText:{color:"#374151",lineHeight:"28px"},code:{fontSize:"14px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",backgroundColor:"#e5e7eb",borderRadius:"4px",padding:"2px 4px"},footer:{marginTop:"32px",fontSize:"14px",color:"#6b7280",textAlign:"center"}};function m(){return jsx("div",{style:t.page,children:jsxs("div",{style:t.container,children:[jsx("div",{style:t.logoWrap,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"80",height:"80",viewBox:"0 0 48 48",fill:"none","aria-label":"Modelence Logo",children:jsx("path",{fill:"#5509D9",d:"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z"})})}),jsx("h1",{style:t.title,children:"Connect this project to Modelence Cloud"}),jsx("p",{style:t.subtitle,children:"One quick step before you can use this app locally."}),jsxs("ol",{style:t.steps,children:[jsxs(y,{number:1,children:["Run ",jsx("code",{style:t.code,children:"npx modelence@latest setup"})," in the project folder."]}),jsx(y,{number:2,children:"Your browser opens \u2014 log in and choose your environment."}),jsxs(y,{number:3,children:["Restart the dev server (",jsx("code",{style:t.code,children:"npm run dev"}),")."]})]}),jsx("p",{style:t.footer,children:"This page refreshes automatically once the project is connected."})]})})}function y({number:n,children:o}){return jsxs("li",{style:t.step,children:[jsx("span",{style:t.stepNumber,children:n}),jsx("span",{style:t.stepText,children:o})]})}var N="__MODELENCE_STATE__",_=3e3,w=false;function L(){return typeof document<"u"&&document.getElementById(N)!==null}function U({children:n,loadingElement:o,setupElement:i}){let d=typeof window>"u",[c,l]=useState(()=>!d&&!x()&&!L()),[u$1,g]=useState(()=>!d&&x()&&q$1());return useEffect(()=>{async function s$1(){if(!w){if(w=true,x()){t$1()&&await s(),g(q$1());return}await u(),g(q$1()),l(false);}}s$1();},[]),useEffect(()=>{if(!u$1)return;let s=false,f;async function S(){try{let{setupRequired:P}=await W("_system.setupStatus",{},{errorHandler:()=>{}});if(!P){window.location.reload();return}}catch{}s||(f=setTimeout(S,_));}return f=setTimeout(S,_),()=>{s=true,clearTimeout(f);}},[u$1]),c?o??jsx("div",{children:"Loading..."}):u$1&&i!==null?i??jsx(m,{}):n}var k="__MODELENCE_QUERY_STATE__";function q(){if(typeof document>"u")return;let n=document.getElementById(k);if(!(!n||!n.textContent))try{return JSON.parse(n.textContent)}catch(o){console.error("Modelence: failed to parse SSR query state",o);return}}function K({children:n,client:o,dehydratedState:i$1}){let[d]=useState(()=>{let l=o??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&i(l),l}),c=i$1??q();return jsx(QueryClientProvider,{client:d,children:jsx(HydrationBoundary,{state:c,children:n})})}
2
+ export{U as a,K as b};//# sourceMappingURL=chunk-FXPFIA66.js.map
3
+ //# sourceMappingURL=chunk-FXPFIA66.js.map