modelence 0.22.2 → 0.23.0-mobile-oauth.dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/bin/modelence.js +8 -3
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/bson.d-M1rp21TC.d.ts +137 -0
  4. package/dist/chunk-DRLEIBGM.js +2 -0
  5. package/dist/chunk-DRLEIBGM.js.map +1 -0
  6. package/dist/chunk-FMEVYO43.js +41 -0
  7. package/dist/chunk-FMEVYO43.js.map +1 -0
  8. package/dist/{chunk-PJRYLKYW.js → chunk-HT5Q3IPP.js} +2 -2
  9. package/dist/{chunk-PJRYLKYW.js.map → chunk-HT5Q3IPP.js.map} +1 -1
  10. package/dist/chunk-MA24NXV7.js +4 -0
  11. package/dist/chunk-MA24NXV7.js.map +1 -0
  12. package/dist/chunk-UW37F3GV.js +2 -0
  13. package/dist/chunk-UW37F3GV.js.map +1 -0
  14. package/dist/chunk-VCIQ5DQM.js +3 -0
  15. package/dist/chunk-VCIQ5DQM.js.map +1 -0
  16. package/dist/chunk-WXSRHKW3.js +2 -0
  17. package/dist/chunk-WXSRHKW3.js.map +1 -0
  18. package/dist/chunk-XMEOB6SD.js +3 -0
  19. package/dist/chunk-XMEOB6SD.js.map +1 -0
  20. package/dist/client.d.ts +181 -7
  21. package/dist/client.js +1 -1
  22. package/dist/package-34JWTHQR.js +2 -0
  23. package/dist/{package-77VM3ZYJ.js.map → package-34JWTHQR.js.map} +1 -1
  24. package/dist/render-VZSAFZWU.js +2 -0
  25. package/dist/{render-CBIFY4DG.js.map → render-VZSAFZWU.js.map} +1 -1
  26. package/dist/renderApp-TK35MPRS.js +2 -0
  27. package/dist/{renderApp-J347DR2B.js.map → renderApp-TK35MPRS.js.map} +1 -1
  28. package/dist/server-HJBOIP54.js +2 -0
  29. package/dist/{server-2Z7VTMEZ.js.map → server-HJBOIP54.js.map} +1 -1
  30. package/dist/server.d.ts +35 -137
  31. package/dist/server.js +1 -1
  32. package/dist/telemetry.js +1 -1
  33. package/dist/transport-KVA6QNGX.js +2 -0
  34. package/dist/{transport-C7DEK6NV.js.map → transport-KVA6QNGX.js.map} +1 -1
  35. package/package.json +4 -3
  36. package/dist/chunk-2VYAJGWJ.js +0 -37
  37. package/dist/chunk-2VYAJGWJ.js.map +0 -1
  38. package/dist/chunk-7I6ULNRU.js +0 -3
  39. package/dist/chunk-7I6ULNRU.js.map +0 -1
  40. package/dist/chunk-AMJHJA2V.js +0 -2
  41. package/dist/chunk-AMJHJA2V.js.map +0 -1
  42. package/dist/chunk-BCUSVRAY.js +0 -2
  43. package/dist/chunk-BCUSVRAY.js.map +0 -1
  44. package/dist/chunk-OJ3LMWVQ.js +0 -2
  45. package/dist/chunk-OJ3LMWVQ.js.map +0 -1
  46. package/dist/chunk-VF4RU7MF.js +0 -3
  47. package/dist/chunk-VF4RU7MF.js.map +0 -1
  48. package/dist/chunk-YOJ4ZP5D.js +0 -4
  49. package/dist/chunk-YOJ4ZP5D.js.map +0 -1
  50. package/dist/package-77VM3ZYJ.js +0 -2
  51. package/dist/render-CBIFY4DG.js +0 -2
  52. package/dist/renderApp-J347DR2B.js +0 -2
  53. package/dist/server-2Z7VTMEZ.js +0 -2
  54. package/dist/transport-C7DEK6NV.js +0 -2
@@ -1,5 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import N,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import M from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import pe from'archiver';import ie from'open';var C=".modelence.env";async function J(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function A(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${C} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function q(e){return String(e).replace(/"/g,'\\"')}async function W(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),C),t={};try{let c=await promises.readFile(o,"utf8");t=parse(c),await W(o),await A()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await J(e.token,e.host),s={...t,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},i=Object.entries(s).map(([c,n])=>`${c}="${q(n)}"`).join(`
3
- `);await promises.writeFile(o,i.trim()+`
4
- `),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var X=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function D(){let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");return X.parse(t)}var h=null,b=null;function Q(){if(!h)throw new Error("Environment variables not loaded");return h}function O(){if(!b)throw new Error("Configuration not loaded");return b}function P(e){return `${Q().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function l(){let{serverDir:e,serverEntry:o}=O();return join(e,o).replace(/\\/g,"/")}function T(){return O().postBuildCommand}function E(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){try{b=await D();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await M.readFile(join(process.cwd(),".modelence.env"),"utf-8");h=parse(e);}catch(e){if(e.code==="ENOENT")h={};else throw e}}async function oe(){let e=T();if(e){console.log("Running post-build command..."),execSync(e);return}await te(),await ne();}async function te(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:N.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function ne(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:N.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:N.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},t,true));}async function re(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[l()],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 v(){console.log("Building Modelence project...");try{let e=E();await M.rm(e,{recursive:!0,force:!0}),await re(),await oe(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await M.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function F(e){let o=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!o.ok)throw new Error("Failed to create CLI authentication code");let{code:t,verificationUrl:r}=await o.json();console.log(`Please visit ${r} to authenticate`),console.log(`Code: ${t}`),await ie(r);let s=await ae(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function ae(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await le(e,o);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function le(e,o){let t=await fetch(`${e}/api/cli/token?code=${o}`,{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:r}=await t.json();return r}async function _(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||P("");await v(),await ue(r);let{token:i}=await F(s),{bundleName:c}=await me(e.app,e.env,r,i,s);await promises.unlink(r),await fe(e.app,e.env,c,join(".modelence","build","app.mjs"),i,s);}async function ue(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=pe("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,g)=>{o.on("close",n),o.on("error",g),t.on("error",g);});t.pipe(o);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server",join(".modelence","build"),".next"];for(let n of s)await promises.access(d(n)).then(()=>true).catch(()=>false)&&t.file(d(n),{name:n});for(let n of i)await promises.access(d(n)).then(()=>true).catch(()=>false)&&t.directory(d(n),n);await t.finalize(),await r;let c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function me(e,o,t,r,s){let i=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:c,bundleName:n}=await i.json(),g=await promises.readFile(t),S=await fetch(c,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!S.ok)throw new Error(`Failed to upload bundle: ${S.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function fe(e,o,t,r,s,i){let c=await fetch(`${i}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!c.ok)throw new Error(`Failed to trigger deployment: ${c.statusText}`);let{deploymentUrl:n}=await c.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${n}`);}function I(){console.log("Starting Modelence dev server...");let e=l(),o=N.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function R(){console.log("Starting Modelence production server...");let e=l(),o=N.basename(e,N.extname(e)),t=E(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var xe=fileURLToPath(import.meta.url),Ne=dirname(xe),Se=JSON.parse(readFileSync(join(Ne,"../../package.json"),"utf-8")),p=new Command().name("modelence").description("Modelence CLI tool").version(Se.version);p.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await k(e);});p.command("build").description("Build the application").action(async()=>{await m(),await v();});p.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 m(),await _(e);});p.command("dev").description("Start development server").action(async()=>{await m(),I();});p.command("start").description("Start production server").action(async()=>{await m(),R();});p.parse(process.argv);//# sourceMappingURL=modelence.js.map
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(`
5
+ `);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(`
7
+ Next step \u2014 run the app on this machine:
8
+ `),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","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
5
10
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","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","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","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":";ueAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,EAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,MAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,EAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CACD,CAAA,SAAA,EAAYP,CAAkB,CAAA,oDAAA,CAAA,CAC7BU,CAAAA,EAAW,CACVH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,EAAO,WAAA,EAAY,GAAM,GAAG,EACtC,CACF,EACF,CAAC,CACH,CAEA,SAASC,CAAAA,CAAeC,CAAAA,CAAgC,CAEtD,OAAO,MAAA,CAAOA,CAAK,CAAA,CAAE,QAAQ,IAAA,CAAM,KAAK,CAC1C,CAEA,eAAeC,CAAAA,CAAcC,CAAAA,CAAgC,CAC3D,GAAI,CACF,IAAMC,CAAAA,CAAaD,CAAAA,CAAQ,OAAA,CAAQ,MAA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,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } 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 open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\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\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\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 { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
1
+ {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","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,CAA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A,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 = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(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"]}
@@ -0,0 +1,137 @@
1
+ /** @public */
2
+ declare abstract class BSONValue {
3
+ /** @public */
4
+ abstract get _bsontype(): string;
5
+ /* Excluded from this release type: [BSON_VERSION_SYMBOL] */
6
+ /**
7
+ * @public
8
+ * Prints a human-readable string of BSON value information
9
+ * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
10
+ */
11
+ abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
12
+ /* Excluded from this release type: toExtendedJSON */
13
+ }
14
+
15
+ declare type InspectFn = (x: unknown, options?: unknown) => string;
16
+
17
+ /**
18
+ * A class representation of the BSON ObjectId type.
19
+ * @public
20
+ * @category BSONType
21
+ */
22
+ declare class ObjectId extends BSONValue {
23
+ get _bsontype(): 'ObjectId';
24
+ /* Excluded from this release type: index */
25
+ static cacheHexString: boolean;
26
+ /* Excluded from this release type: buffer */
27
+ /**
28
+ * Create ObjectId from a number.
29
+ *
30
+ * @param inputId - A number.
31
+ * @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId.
32
+ */
33
+ constructor(inputId: number);
34
+ /**
35
+ * Create ObjectId from a 24 character hex string.
36
+ *
37
+ * @param inputId - A 24 character hex string.
38
+ */
39
+ constructor(inputId: string);
40
+ /**
41
+ * Create ObjectId from the BSON ObjectId type.
42
+ *
43
+ * @param inputId - The BSON ObjectId type.
44
+ */
45
+ constructor(inputId: ObjectId);
46
+ /**
47
+ * Create ObjectId from the object type that has the toHexString method.
48
+ *
49
+ * @param inputId - The ObjectIdLike type.
50
+ */
51
+ constructor(inputId: ObjectIdLike);
52
+ /**
53
+ * Create ObjectId from a 12 byte binary Buffer.
54
+ *
55
+ * @param inputId - A 12 byte binary Buffer.
56
+ */
57
+ constructor(inputId: Uint8Array);
58
+ /** To generate a new ObjectId, use ObjectId() with no argument. */
59
+ constructor();
60
+ /**
61
+ * Implementation overload.
62
+ *
63
+ * @param inputId - All input types that are used in the constructor implementation.
64
+ */
65
+ constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array);
66
+ /**
67
+ * The ObjectId bytes
68
+ * @readonly
69
+ */
70
+ get id(): Uint8Array;
71
+ set id(value: Uint8Array);
72
+ /* Excluded from this release type: validateHexString */
73
+ /** Returns the ObjectId id as a 24 lowercase character hex string representation */
74
+ toHexString(): string;
75
+ /* Excluded from this release type: getInc */
76
+ /**
77
+ * Generate a 12 byte id buffer used in ObjectId's
78
+ *
79
+ * @param time - pass in a second based timestamp.
80
+ */
81
+ static generate(time?: number): Uint8Array;
82
+ /**
83
+ * Converts the id into a 24 character hex string for printing, unless encoding is provided.
84
+ * @param encoding - hex or base64
85
+ */
86
+ toString(encoding?: 'hex' | 'base64'): string;
87
+ /** Converts to its JSON the 24 character hex string representation. */
88
+ toJSON(): string;
89
+ /* Excluded from this release type: is */
90
+ /**
91
+ * Compares the equality of this ObjectId with `otherID`.
92
+ *
93
+ * @param otherId - ObjectId instance to compare against.
94
+ */
95
+ equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
96
+ /** Returns the generation date (accurate up to the second) that this ID was generated. */
97
+ getTimestamp(): Date;
98
+ /* Excluded from this release type: createPk */
99
+ /* Excluded from this release type: serializeInto */
100
+ /**
101
+ * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
102
+ *
103
+ * @param time - an integer number representing a number of seconds.
104
+ */
105
+ static createFromTime(time: number): ObjectId;
106
+ /**
107
+ * Creates an ObjectId from a hex string representation of an ObjectId.
108
+ *
109
+ * @param hexString - create a ObjectId from a passed in 24 character hexstring.
110
+ */
111
+ static createFromHexString(hexString: string): ObjectId;
112
+ /** Creates an ObjectId instance from a base64 string */
113
+ static createFromBase64(base64: string): ObjectId;
114
+ /**
115
+ * Checks if a value can be used to create a valid bson ObjectId
116
+ * @param id - any JS value
117
+ */
118
+ static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean;
119
+ /* Excluded from this release type: toExtendedJSON */
120
+ /* Excluded from this release type: fromExtendedJSON */
121
+ /* Excluded from this release type: isCached */
122
+ /**
123
+ * Converts to a string representation of this Id.
124
+ *
125
+ * @returns return the 24 character hex string representation.
126
+ */
127
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
128
+ }
129
+
130
+ /** @public */
131
+ declare interface ObjectIdLike {
132
+ id: string | Uint8Array;
133
+ __id?: string;
134
+ toHexString(): string;
135
+ }
136
+
137
+ export { ObjectId as O };
@@ -0,0 +1,2 @@
1
+ import {c as c$1}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {create}from'zustand';import {z as z$1}from'zod';var E={},x=null;function F(e){x=e;}function G(e){return typeof window>"u"&&x?x(e):E[e]?.value}function g(e){E=e;}var O="modelence.session";function P(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function p(){if(!P())return null;let e=globalThis.localStorage.getItem(O);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function h(e){P()&&globalThis.localStorage.setItem(O,JSON.stringify(e));}var N=null;function Q(e){N=e;}function a(){return N}var m=null;function j(e){let n=new Uint8Array(e),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(n);else for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);let r="";for(let o of n)r+=o.toString(16).padStart(2,"0");return r}function I(){return m=j(32),m}function M(){let e=m;return m=null,e}function T(e){let n=a();return n&&n.setAuthToken(e.session.authToken),y(e.user)}async function se(e){let{email:n,password:t,handle:r,firstName:o,lastName:s,avatarUrl:l}=e;await i("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...s!==void 0?{lastName:s}:{},...l!==void 0?{avatarUrl:l}:{}});}async function ae(e){let{email:n,password:t}=e,r=await i("_system.user.loginWithPassword",{email:n,password:t});return T(r)}async function le(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:s}=await i("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return y(s)}async function ue(e){let{token:n}=e;await i("_system.user.verifyEmail",{token:n});}async function ce(e){let{email:n}=e;await i("_system.user.resendEmailVerification",{email:n});}async function de(){await i("_system.user.logout");let e=a();e&&e.setAuthToken(null),y(null);}async function fe(e){let{email:n}=e;await i("_system.user.sendResetPasswordToken",{email:n});}async function ge(e){let{email:n}=e;await i("_system.user.sendMagicLink",{email:n});}async function pe(){let e=await i("_system.user.loginWithMagicLink");return T(e)}async function he(e){let{email:n,code:t}=e,r=await i("_system.user.loginWithOneTimeCode",{email:n,code:t});return T(r)}async function me(e){let{token:n,password:t}=e;await i("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function we(e){let{provider:n,redirectUri:t}=e,r=a(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("signInWithOAuth was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let l=I(),C=`${o}/api/_internal/auth/${n}?mode=login&platform=mobile&redirectUri=${encodeURIComponent(t)}&codeChallenge=${encodeURIComponent(l)}`;r.openUrl(C);return}let s=`${o}/api/_internal/auth/${n}?mode=login`;if(r?.openUrl){r.openUrl(s);return}window.location.href=s;}async function ye(e){let{code:n}=e,t=M();if(!t)throw new Error("No sign-in is in progress. Call signInWithOAuth before redeeming an OAuth code.");let r=await i("_system.user.loginWithOAuth",{code:n,codeVerifier:t});return T(r)}async function Te(e){let{provider:n,redirectUri:t}=e,r=a(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("linkOAuthProvider was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let s=w();if(!s)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let l=await fetch(`${o}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:s})});if(!l.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:C}=await l.json(),V=`${o}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(C)}&platform=mobile&redirectUri=${encodeURIComponent(t)}`;r.openUrl(V);}else {let s=w();if(s&&!(await fetch(`${o}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:s}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${o}/api/_internal/auth/${n}?mode=link`;}}async function Se(e){let{provider:n}=e;await i("_system.user.unlinkOAuthProvider",{provider:n});}function w(){let e=a();return e?e.getAuthToken():p()?.authToken}function W(){let e=a();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var H=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function Ce(e){H=e;}function L(e,n){return H(e,n)}var k=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},q=async(e,n)=>{let t=a()?.baseUrl??"";return z(`${t}/api/_internal/method/${e}`,n)},S="__modelence_call_method_transport__";function D(){return globalThis[S]??q}function Ae(e){let n=globalThis[S];return globalThis[S]=e,()=>{globalThis[S]=n;}}async function i(e,n,t){n=n??{},t=t??{};try{return await D()(e,n)}catch(r){throw (t.errorHandler??L)(r,e),r}}async function z(e,n){let t=await fetch(e,{method:"POST",credentials:a()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:w(),clientInfo:W()})});if(!t.ok){let s=await t.text(),l=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new k(s,t.status,l)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c$1(o.data,o.typeMap)}var c=create(e=>({user:null,setUser:n=>e({user:n})})),f=false,U=false,K=a$1.seconds(30),$=null,B=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function d(e){if(!e)return null;let n=B.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}var R=false;function He(){return R}function Le(e){if(f)return;f=true,R=!!e.setupRequired,g(e.configs);let t=p()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){U=true,c.getState().setUser(d(e.user));return}h(e.session),c.getState().setUser(d(e.user));}async function $e(){if(U){U=false;try{let{configs:e,session:n,user:t}=await i("_system.session.init");g(e),h(n),c.getState().setUser(d(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function Ve(){return U}async function je(){if(f)return;f=true;let e=await i("_system.session.init"),{configs:n,session:t,user:r}=e;R=!!e.setupRequired,g(n);let o=a();o?o.setAuthToken(t.authToken):h(t),c.getState().setUser(d(r)),await b();}async function qe(){typeof window>"u"||$!==null||await b();}async function b(){if(!(typeof window>"u")){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}$=setTimeout(b,K);}}function y(e){let n=d(e);return c.getState().setUser(n),n}function De(){return f}var v=null;function ze(e){v=e;}function Je(e){return d(e)}function Ke(){return typeof window>"u"&&v?{user:v()}:{user:c(n=>n.user)}}export{we as A,ye as B,Te as C,Se as D,w as E,W as F,Ce as G,k as H,q as I,Ae as J,i as K,F as a,G as b,p as c,Q as d,a as e,He as f,Le as g,$e as h,Ve as i,je as j,qe as k,De as l,ze as m,Je as n,Ke as o,se as p,ae as q,le as r,ue as s,ce as t,de as u,fe as v,ge as w,pe as x,he as y,me as z};//# sourceMappingURL=chunk-DRLEIBGM.js.map
2
+ //# sourceMappingURL=chunk-DRLEIBGM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/client.ts","../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/oauthVerifier.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/client/session.ts"],"names":["config","ssrConfigResolver","_setSsrConfigResolver","resolver","getConfig","key","_setConfig","configs","SESSION_KEY","hasLocalStorage","getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","configureClient","userConfig","getClientConfig","pendingVerifier","randomHex","byteLength","bytes","cryptoObj","i","out","byte","startOAuthVerifier","consumeOAuthVerifier","verifier","completeLogin","result","setCurrentUser","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","updateProfile","user","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","code","resetPassword","signInWithOAuth","provider","redirectUri","baseUrl","codeChallenge","url","webUrl","loginWithOAuth","codeVerifier","linkOAuthProvider","getAuthToken","nonceResponse","nonce","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","defaultCallMethodTransport","args","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","endpoint","response","text","reviveResponseTypes","useSessionStore","create","set","isInitialized","pendingReconciliation","SESSION_HEARTBEAT_INTERVAL","time","heartbeatTimer","userSchema","z","parseUser","parsedData","role","setupRequired","_isSetupRequired","hydrateSession","payload","existingToken","ssrSession","reconcileSession","_isReconciliationPending","initSession","loopSessionHeartbeat","startSessionHeartbeat","enrichedUser","isSessionInitialized","ssrSessionResolver","_setSsrSessionResolver","_parseSessionUser","useSession","state"],"mappings":"8IAEA,IAAIA,CAAAA,CAAuC,EAAC,CAGxCC,CAAAA,CAA8C,KAG3C,SAASC,CAAAA,CAAsBC,EAAoC,CACxEF,CAAAA,CAAoBE,EACtB,CAQO,SAASC,EAAUC,CAAAA,CAAuD,CAC/E,OAAI,OAAO,MAAA,CAAW,KAAeJ,CAAAA,CAC5BA,CAAAA,CAAkBI,CAAG,CAAA,CAEvBL,CAAAA,CAAOK,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,CAAWC,EAAkB,CAC3CP,CAAAA,CAASO,EACX,CC3BA,IAAMC,EAAc,mBAAA,CAEpB,SAASC,GAA2B,CAClC,OAAO,OAAO,UAAA,CAAe,GAAA,EAAe,OAAO,WAAW,YAAA,CAAiB,GACjF,CAEO,SAASC,CAAAA,EAAyB,CACvC,GAAI,CAACD,GAAgB,CACnB,OAAO,KAGT,IAAME,CAAAA,CAAc,WAAW,YAAA,CAAa,OAAA,CAAQH,CAAW,CAAA,CAC/D,GAAI,CACF,OAAOG,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,0CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACjDL,CAAAA,EAAgB,EAIrB,UAAA,CAAW,YAAA,CAAa,OAAA,CAAQD,CAAAA,CAAa,KAAK,SAAA,CAAUM,CAAO,CAAC,EACtE,CCDA,IAAId,CAAAA,CAA8B,IAAA,CAgC3B,SAASe,CAAAA,CAAgBC,CAAAA,CAA0B,CACxDhB,CAAAA,CAASgB,EACX,CAEO,SAASC,CAAAA,EAAuC,CACrD,OAAOjB,CACT,CC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B","file":"chunk-DRLEIBGM.js","sourcesContent":["import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\ntype SsrConfigResolver = (key: ConfigKey) => string | number | boolean | undefined;\nlet ssrConfigResolver: SsrConfigResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrConfigResolver(resolver: SsrConfigResolver | null) {\n ssrConfigResolver = resolver;\n}\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n if (typeof window === 'undefined' && ssrConfigResolver) {\n return ssrConfigResolver(key);\n }\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n /**\n * Credentials mode for method-call requests. Defaults to `'include'`, which\n * browser apps need for the cookie-based flows (password reset, magic link).\n *\n * Clients configured with token-in-body auth (React Native / Expo) never use\n * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin\n * request is otherwise blocked by any server answering\n * `Access-Control-Allow-Origin: *`, surfacing as \"TypeError: Failed to fetch\".\n */\n credentials?: RequestCredentials;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","/**\n * Device-side binding for the native OAuth flow (PKCE-style).\n *\n * The deep link that carries the exchange code back into the app is the weakest\n * hop in the chain: a custom scheme can be claimed by any installed app, and a\n * crafted `myapp://auth?code=...` can be handed to the device from outside the\n * flow entirely. Without a device-held secret, redeeming such a code silently\n * rebinds the session to whoever minted it.\n *\n * So `signInWithOAuth` mints a verifier, keeps it in memory, and sends only a\n * derived challenge to the server. `loginWithOAuth` replays the verifier at\n * redemption, and the server checks it against the challenge bound to the code\n * when it was minted. A code minted for an attacker's flow carries the\n * attacker's challenge and cannot be redeemed by this device.\n *\n * Why not the RFC 7636 `S256` transform: bare React Native ships neither\n * `crypto.subtle` nor `crypto.getRandomValues`, so a SHA-256 challenge would\n * force a native crypto dependency on every consumer. The challenge is instead\n * sent as the verifier itself over TLS and stored only as a hash server-side,\n * which is the `plain` method of the same RFC. The property that matters here —\n * a code is redeemable only by the device that started the flow — is identical;\n * what `S256` additionally protects against is a challenge leaking from the\n * *authorization request*, which for us never leaves the TLS channel between\n * the app and its own server.\n */\n\n/** Verifier length in characters. 32 bytes of entropy, hex-encoded. */\nconst VERIFIER_BYTES = 32;\n\n/**\n * The verifier for the in-flight sign-in.\n *\n * Deliberately module-scoped memory rather than persistent storage: the flow is\n * a foreground round trip measured in seconds, and a verifier that outlives the\n * app process is a credential sitting on disk for no benefit. An app killed\n * mid-flow simply restarts the sign-in.\n */\nlet pendingVerifier: string | null = null;\n\n/**\n * Random hex string, using the best source the runtime offers.\n *\n * `crypto.getRandomValues` exists in browsers, Expo (via `expo-crypto`'s global\n * install) and Hermes with a polyfill; bare React Native has none of them, so\n * `Math.random` is the documented fallback. That fallback is weaker than a CSPRNG,\n * but the verifier only needs to be unguessable by an attacker who cannot read\n * the device's memory — and an attacker who can read process memory has already\n * won regardless of the entropy source.\n */\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoObj?.getRandomValues) {\n cryptoObj.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n\n let out = '';\n for (const byte of bytes) {\n out += byte.toString(16).padStart(2, '0');\n }\n return out;\n}\n\n/**\n * Mints a fresh verifier for a new sign-in and returns the challenge to send.\n *\n * Any previously pending verifier is discarded: only the most recently started\n * flow is redeemable, so an abandoned flow cannot be completed later.\n */\nexport function startOAuthVerifier(): string {\n pendingVerifier = randomHex(VERIFIER_BYTES);\n return pendingVerifier;\n}\n\n/**\n * Returns the pending verifier and clears it, so a given verifier is replayed\n * at most once even if the deep link fires twice.\n */\nexport function consumeOAuthVerifier(): string | null {\n const verifier = pendingVerifier;\n pendingVerifier = null;\n return verifier;\n}\n\n/** Clears any pending verifier. Exposed for tests and for abandoning a flow. */\nexport function resetOAuthVerifier(): void {\n pendingVerifier = null;\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\nimport { consumeOAuthVerifier, startOAuthVerifier } from './oauthVerifier';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\n/**\n * Stores the session from a completed sign-in and returns the enriched user.\n *\n * Every login method ends the same way — persist the auth token through the\n * client config, then publish the user to the reactive session store. Kept in\n * one place so a new sign-in method cannot half-implement it.\n */\nfunction completeLogin(result: { user: RawUserData; session: { authToken: string } }) {\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(result.session.authToken);\n }\n return setCurrentUser(result.user);\n}\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n return completeLogin(result);\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Send a magic sign-in link to the given email address.\n *\n * Clicking the emailed link signs the user in. When the server enables\n * `auth.magicLink.allowSignup`, this also works for new users — the account is\n * created when the link is used; otherwise unknown emails receive no email.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await sendMagicLink({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to send the magic link to.\n */\nexport async function sendMagicLink(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendMagicLink', {\n email,\n });\n}\n\n/**\n * Complete a magic link sign-in.\n *\n * Call this from the page the magic link landing route redirects to. The\n * token is exchanged server-side via an httpOnly cookie, so no arguments are\n * needed. Signs the user in — creating the account first when the email is\n * not registered yet and the server enables `auth.magicLink.allowSignup` —\n * and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithMagicLink();\n * ```\n */\nexport async function loginWithMagicLink() {\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\n );\n return completeLogin(result);\n}\n\n/**\n * Complete a magic link sign-in by typing the one-time code from the email.\n *\n * Alternative to `loginWithMagicLink()` for contexts where clicking the link\n * can't reach the app — native apps without deep links, or when the email is\n * read on a different device. Signs the user in — creating the account first\n * when the email is not registered yet and the server enables\n * `auth.magicLink.allowSignup` — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });\n * ```\n * @param options.email - The email the magic link was sent to.\n * @param options.code - The one-time code from the email.\n */\nexport async function loginWithOneTimeCode(options: { email: string; code: string }) {\n const { email, code } = options;\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\n );\n return completeLogin(result);\n}\n\n/**\n * Reset password.\n *\n * The token is normally exchanged server-side via an httpOnly cookie, so the\n * client only submits the new password. Pass `token` only for legacy flows\n * that still carry it client-side (deprecated).\n *\n * @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token?: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n ...(token ? { token } : {}),\n password,\n });\n}\n\n/**\n * Start an OAuth sign-in.\n *\n * On the web this navigates to the provider and the flow finishes on its own —\n * the session cookie is set and the browser lands back on your site.\n *\n * Pass `redirectUri` to run the native flow: the device browser opens the\n * provider, and when the flow completes Modelence redirects back to that deep\n * link with a single-use `code` query parameter. Hand that code to\n * {@link loginWithOAuth} to finish signing in. The redirect target must be\n * listed in the server's `auth.mobile.redirectUrls`, otherwise the request is\n * rejected before the provider is ever reached.\n *\n * The native flow additionally binds the sign-in to this device: a verifier is\n * held in memory here and replayed by `loginWithOAuth`, so a `code` delivered\n * to the app from outside this flow cannot be redeemed.\n *\n * @example Web\n * ```ts\n * await signInWithOAuth({ provider: 'google' });\n * ```\n *\n * @example React Native\n * ```ts\n * import { parseDeepLinkParams } from 'modelence/client';\n *\n * await signInWithOAuth({ provider: 'google', redirectUri: 'myapp://auth' });\n *\n * Linking.addEventListener('url', async ({ url }) => {\n * const { code } = parseDeepLinkParams(url);\n * if (code) await loginWithOAuth({ code });\n * });\n * ```\n * @param options.provider - The OAuth provider to sign in with ('google' or 'github').\n * @param options.redirectUri - Deep link to return to. Required on React Native.\n */\nexport async function signInWithOAuth(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n // `redirectUri` — not the presence of `openUrl` — decides the flow. An\n // Electron or Capacitor client may set `openUrl` purely to control how links\n // open while still completing the ordinary cookie-based web flow.\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'signInWithOAuth was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\n\n const codeChallenge = startOAuthVerifier();\n const url =\n `${baseUrl}/api/_internal/auth/${provider}?mode=login&platform=mobile` +\n `&redirectUri=${encodeURIComponent(redirectUri)}` +\n `&codeChallenge=${encodeURIComponent(codeChallenge)}`;\n config.openUrl(url);\n return;\n }\n\n const webUrl = `${baseUrl}/api/_internal/auth/${provider}?mode=login`;\n if (config?.openUrl) {\n config.openUrl(webUrl);\n return;\n }\n\n window.location.href = webUrl;\n}\n\n/**\n * Complete a native OAuth sign-in with the code from the deep link.\n *\n * Exchanges the single-use code that {@link signInWithOAuth} delivered to your\n * app's deep link for a session, stores the auth token, and returns the\n * signed-in user. Codes are valid for one minute and can only be redeemed once.\n *\n * The verifier minted by `signInWithOAuth` is replayed here, which is what\n * makes a code usable only by the device that started the flow. Calling this\n * without a preceding `signInWithOAuth` — as a crafted deep link would — fails\n * before the code is ever sent.\n *\n * @example\n * ```ts\n * const user = await loginWithOAuth({ code });\n * ```\n * @param options.code - The `code` query parameter from the deep link.\n */\nexport async function loginWithOAuth(options: { code: string }) {\n const { code } = options;\n\n const codeVerifier = consumeOAuthVerifier();\n if (!codeVerifier) {\n throw new Error(\n 'No sign-in is in progress. Call signInWithOAuth before redeeming an OAuth code.'\n );\n }\n\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOAuth',\n { code, codeVerifier }\n );\n return completeLogin(result);\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n * @param options.redirectUri - Deep link to return to once linking completes.\n * React Native only; must be listed in the server's `auth.mobile.redirectUrls`.\n * Without it the flow ends in the device browser instead of back in the app.\n */\nexport async function linkOAuthProvider(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'linkOAuthProvider was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url =\n `${baseUrl}/api/_internal/auth/${provider}?mode=link` +\n `&linkNonce=${encodeURIComponent(nonce)}` +\n `&platform=mobile&redirectUri=${encodeURIComponent(redirectUri)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n\n if (typeof window === 'undefined') {\n return {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n };\n }\n\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // Send cookies even when the SPA and API are on different origins. The\n // password-reset and magic-link flows rely on httpOnly cookies set by the\n // server landing routes; with the default `same-origin` policy the cookie\n // would be dropped on cross-origin POSTs and those flows would fail.\n // (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n // Token-in-body clients (React Native / Expo) don't use cookies and can\n // override this via `configureClient({ credentials: 'omit' })`.\n credentials: getClientConfig()?.credentials ?? 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { getLocalStorageSession, setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\n// Set when SSR rendered anonymously but localStorage holds a token (no\n// cookie yet). `reconcileSession()` then re-auths via the body and refreshes\n// the cookie for subsequent SSR requests.\nlet pendingReconciliation = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport type SessionInitPayload = {\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n /*\n Present (true) only when a development server has no backend at all —\n neither a Modelence Cloud connection nor a local database. AppProvider\n then shows setup instructions instead of the app. The server decides this;\n the client never consults its own build mode.\n */\n setupRequired?: boolean;\n};\n\nlet setupRequired = false;\n\n/** @internal */\nexport function _isSetupRequired(): boolean {\n return setupRequired;\n}\n\n/** Hydrate session state from the SSR payload, skipping the network round-trip. */\nexport function hydrateSession(payload: SessionInitPayload) {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(payload.configs);\n\n // localStorage token + anonymous SSR payload = server couldn't read the\n // token (no cookie yet). Preserve the localStorage token and defer to\n // `reconcileSession()`; overwriting here would log the user out permanently.\n const existingLocalSession = getLocalStorageSession() as { authToken?: string } | null;\n const existingToken = existingLocalSession?.authToken;\n const ssrSession = payload.session as { authToken?: string };\n\n if (existingToken && !payload.user && existingToken !== ssrSession.authToken) {\n pendingReconciliation = true;\n // First render must match the server (anonymous); reconcile swaps later.\n useSessionStore.getState().setUser(parseUser(payload.user));\n return;\n }\n\n setLocalStorageSession(payload.session);\n useSessionStore.getState().setUser(parseUser(payload.user));\n}\n\n/** Re-auth via the body token when SSR couldn't read it from a cookie. */\nexport async function reconcileSession() {\n if (!pendingReconciliation) {\n return;\n }\n pendingReconciliation = false;\n\n try {\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n useSessionStore.getState().setUser(parseUser(user));\n } catch (error) {\n console.error('Modelence: session reconciliation failed', error);\n }\n}\n\n/** @internal */\nexport function _isReconciliationPending(): boolean {\n return pendingReconciliation;\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const payload = await callMethod<SessionInitPayload>('_system.session.init');\n const { configs, session, user } = payload;\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\n/** Idempotent, client-only. Auto-started by `initSession`; call explicitly after `hydrateSession`. */\nexport async function startSessionHeartbeat() {\n if (typeof window === 'undefined' || heartbeatTimer !== null) {\n return;\n }\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function isSessionInitialized() {\n return isInitialized;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\ntype SsrSessionResolver = () => User | null;\nlet ssrSessionResolver: SsrSessionResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrSessionResolver(resolver: SsrSessionResolver | null) {\n ssrSessionResolver = resolver;\n}\n\n/** @internal */\nexport function _parseSessionUser(user: unknown): User | null {\n return parseUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n if (typeof window === 'undefined' && ssrSessionResolver) {\n return { user: ssrSessionResolver() };\n }\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n"]}