modelence 0.17.0-dev.0 → 0.18.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bin/modelence.js +2 -2
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/chunk-IJ5BS7PM.js +2 -0
  4. package/dist/chunk-IJ5BS7PM.js.map +1 -0
  5. package/dist/chunk-JBTEZOY2.js +2 -0
  6. package/dist/chunk-JBTEZOY2.js.map +1 -0
  7. package/dist/chunk-KU4GANYW.js +3 -0
  8. package/dist/chunk-KU4GANYW.js.map +1 -0
  9. package/dist/chunk-LDVLXJLS.js +3 -0
  10. package/dist/chunk-LDVLXJLS.js.map +1 -0
  11. package/dist/chunk-S2E4OO6G.js +19 -0
  12. package/dist/chunk-S2E4OO6G.js.map +1 -0
  13. package/dist/chunk-S77LRZU6.js +2 -0
  14. package/dist/chunk-S77LRZU6.js.map +1 -0
  15. package/dist/chunk-VFOGVWJK.js +2 -0
  16. package/dist/chunk-VFOGVWJK.js.map +1 -0
  17. package/dist/client.d.ts +64 -5
  18. package/dist/client.js +1 -1
  19. package/dist/client.js.map +1 -1
  20. package/dist/collectCss-4V7I3QV3.js +2 -0
  21. package/dist/collectCss-4V7I3QV3.js.map +1 -0
  22. package/dist/{index-CLpVWWuj.d.ts → index-BBMsjrFN.d.ts} +3 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +1 -1
  25. package/dist/{package-WKD57CCF.js → package-XQQF6NGT.js} +2 -2
  26. package/dist/{package-WKD57CCF.js.map → package-XQQF6NGT.js.map} +1 -1
  27. package/dist/render-57TPXKHI.js +2 -0
  28. package/dist/render-57TPXKHI.js.map +1 -0
  29. package/dist/renderApp-3FQ6KUQ2.js +2 -0
  30. package/dist/renderApp-3FQ6KUQ2.js.map +1 -0
  31. package/dist/server-JB4DTGBT.js +2 -0
  32. package/dist/server-JB4DTGBT.js.map +1 -0
  33. package/dist/server.d.ts +8 -6
  34. package/dist/server.js +1 -18
  35. package/dist/server.js.map +1 -1
  36. package/dist/transport-BOPYDAVH.js +2 -0
  37. package/dist/transport-BOPYDAVH.js.map +1 -0
  38. package/dist/{types-CTjq1HaP.d.ts → types-DV0J5rPI.d.ts} +8 -0
  39. package/dist/{types-DNZiaNSs.d.ts → types-mkbhnQN2.d.ts} +2 -2
  40. package/dist/types.d.ts +3 -3
  41. package/package.json +3 -1
  42. package/dist/chunk-52CM66XJ.js +0 -3
  43. package/dist/chunk-52CM66XJ.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import B,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T 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 ae from'archiver';import oe from'open';var b=".modelence.env";async function L(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 R(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function U(e){return String(e).replace(/"/g,'\\"')}async function V(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 S(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await V(o),await R()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await L(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(([a,n])=>`${a}="${U(n)}"`).join(`
2
+ import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import S,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T 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 ce from'archiver';import te from'open';var C=".modelence.env";async function z(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 J(){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 A(e){return String(e).replace(/"/g,'\\"')}async function q(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 D(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await q(o),await J()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await z(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(([a,n])=>`${a}="${A(n)}"`).join(`
3
3
  `);await promises.writeFile(o,i.trim()+`
4
- `),console.log(`Successfully configured ${b} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var h=null,C=null;function q(){if(!h)throw new Error("Environment variables not loaded");return h}function k(){if(!C)throw new Error("Configuration not loaded");return C}function D(e){return `${q().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=k();return join(e,o).replace(/\\/g,"/")}function P(){return k().postBuildCommand}function E(e){let o=N("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function N(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");C=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");h=parse(e);}catch(e){if(e.code==="ENOENT")h={};else throw e}}async function Q(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}await Z();}async function Z(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:B.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function ee(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[p()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=E();await T.rm(e,{recursive:!0,force:!0}),await ee(),await Q(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function O(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 oe(r);let s=await re(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function re(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await ie(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 ie(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||D("");await v(),await ce(r);let{token:i}=await O(s),{bundleName:a}=await le(e.app,e.env,r,i,s);await promises.unlink(r),await pe(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function ce(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=ae("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 a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function le(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:a,bundleName:n}=await i.json(),g=await promises.readFile(t),x=await fetch(a,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!x.ok)throw new Error(`Failed to upload bundle: ${x.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function pe(e,o,t,r,s,i){let a=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(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:n}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${n}`);}function j(){console.log("Starting Modelence dev server...");let e=p(),o=B.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 M(){console.log("Starting Modelence production server...");let e=p(),o=B.basename(e,B.extname(e)),t=E(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var ve=fileURLToPath(import.meta.url),ye=dirname(ve),be=JSON.parse(readFileSync(join(ye,"../../package.json"),"utf-8")),u=new Command().name("modelence").description("Modelence CLI tool").version(be.version);u.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 S(e);});u.command("build").description("Build the application").action(async()=>{await m(),await v();});u.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);});u.command("dev").description("Start development server").action(async()=>{await m(),j();});u.command("start").description("Start production server").action(async()=>{await m(),M();});u.parse(process.argv);//# sourceMappingURL=modelence.js.map
4
+ `),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var h=null,N=null;function X(){if(!h)throw new Error("Environment variables not loaded");return h}function E(){if(!N)throw new Error("Configuration not loaded");return N}function O(e){return `${X().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function d(){let{serverDir:e,serverEntry:o}=E();return join(e,o).replace(/\\/g,"/")}function P(){return E().postBuildCommand}function v(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function f(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");N=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional(),ssr:z$1.boolean().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");h=parse(e);}catch(e){if(e.code==="ENOENT")h={};else throw e}}async function Q(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}await Z(),E().ssr&&await ee();}async function Z(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:S.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function ee(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:S.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:S.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 oe(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[d()],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 y(){console.log("Building Modelence project...");try{let e=v();await T.rm(e,{recursive:!0,force:!0}),await oe(),await Q(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function M(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 te(r);let s=await ie(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function ie(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await se(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 se(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 F(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await y(),await le(r);let{token:i}=await M(s),{bundleName:a}=await de(e.app,e.env,r,i,s);await promises.unlink(r),await pe(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function le(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=ce("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,w)=>{o.on("close",n),o.on("error",w),t.on("error",w);});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(p(n)).then(()=>true).catch(()=>false)&&t.file(p(n),{name:n});for(let n of i)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.directory(p(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function de(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:a,bundleName:n}=await i.json(),w=await promises.readFile(t),k=await fetch(a,{method:"PUT",body:new Uint8Array(w),headers:{"Content-Type":"application/zip"}});if(!k.ok)throw new Error(`Failed to upload bundle: ${k.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function pe(e,o,t,r,s,i){let a=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(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:n}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${n}`);}function _(){console.log("Starting Modelence dev server...");let e=d(),o=S.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 L(){console.log("Starting Modelence production server...");let e=d(),o=S.basename(e,S.extname(e)),t=v(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var ye=fileURLToPath(import.meta.url),be=dirname(ye),Ce=JSON.parse(readFileSync(join(be,"../../package.json"),"utf-8")),u=new Command().name("modelence").description("Modelence CLI tool").version(Ce.version);u.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 D(e);});u.command("build").description("Build the application").action(async()=>{await f(),await y();});u.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 f(),await F(e);});u.command("dev").description("Start development server").action(async()=>{await f(),_();});u.command("start").description("Start production server").action(async()=>{await f(),L();});u.parse(process.argv);//# sourceMappingURL=modelence.js.map
5
5
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/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","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","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,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,OAAO,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMjE,GAAQ,CACd,MAAMiB,IACR,CAAC,EAEHgD,CAAAA,CACG,OAAA,CAAQ,QAAQ,CAAA,CAChB,YAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAA,CAAmB,mBAAmB,EACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,oBAAqB,gBAAgB,CAAA,CAC5C,OAAO,MAAOxF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,EAAQ,CACd,MAAM2B,EAAOlD,CAAO,EACtB,CAAC,CAAA,CAEHwF,CAAAA,CACG,QAAQ,KAAK,CAAA,CACb,YAAY,0BAA0B,CAAA,CACtC,OAAO,SAAY,CAClB,MAAMjE,CAAAA,EAAQ,CACdqD,IACF,CAAC,CAAA,CAEHY,CAAAA,CACG,QAAQ,OAAO,CAAA,CACf,YAAY,yBAAyB,CAAA,CACrC,OAAO,SAAY,CAClB,MAAMjE,CAAAA,EAAQ,CACdwD,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\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 { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n 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/setup.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","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","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":";8eAKA,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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AAA,CACrD,MAAA,CAAO,oBAAqB,gBAAgB,CAAA,CAC5C,OAAO,MAAOzF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,GACN,MAAM4B,CAAAA,CAAOnD,CAAO,EACtB,CAAC,EAEHyF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAMlE,GAAQ,CACdsD,CAAAA,GACF,CAAC,CAAA,CAEHY,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,yBAAyB,EACrC,MAAA,CAAO,SAAY,CAClB,MAAMlE,CAAAA,GACNyD,CAAAA,GACF,CAAC,CAAA,CAEHS,CAAAA,CAAQ,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 { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z\n .object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n ssr: z.boolean().optional(),\n })\n .parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport {\n getBuildPath,\n getConfig,\n getModelencePath,\n getPostBuildCommand,\n getServerPath,\n} from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n\n if (getConfig().ssr) {\n await buildViteSsr();\n }\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n },\n };\n\n await viteBuild(mergeConfig(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 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"]}
@@ -0,0 +1,2 @@
1
+ import {w as w$1,m,l,q,u as u$1}from'./chunk-VFOGVWJK.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx}from'react/jsx-runtime';import z from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var E=false;function oe({children:e,loadingElement:n}){let r=typeof window>"u",[t,o]=useState(()=>!r&&!w$1());return useEffect(()=>{async function s(){E||(E=true,!w$1()&&(await u$1(),o(false)));}s();},[]),t?n??jsx("div",{children:"Loading..."}):e}var y=null,v=new Map;function p(){if(!y)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return y}function _(){let e=l(),n=m();for(let r of v.values())y?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:n});}function K(e){y=z("/",{transports:["websocket"],auth:{token:l()}}),y.on("connect",()=>{v.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${v.size} live queries`),_());}),e.channels?.forEach(n=>n.init());}function U({category:e,listener:n}){p().on(e,n);}function N({category:e,listener:n}){p().once(e,n);}function O({category:e,listener:n}){p().off(e,n);}function C({eventName:e,category:n,id:r}){p().emit(e,`${n}:${r}`);}function $({category:e,id:n}){C({eventName:"joinChannel",category:e,id:n});}function F({category:e,id:n}){C({eventName:"leaveChannel",category:e,id:n});}var B=0;function w(e,n,r,t){let o=`sub-${++B}-${Date.now()}`,s=({subscriptionId:l,data:i,typeMap:f})=>{l===o&&r(c(i,f));},a=({subscriptionId:l,error:i})=>{l===o&&(console.error(`[Modelence] Live query error for ${e}:`,i),t?.(i));},c$1=p();return c$1.on("liveQueryData",s),c$1.on("liveQueryError",a),v.set(o,{subscriptionId:o,method:e,args:n}),c$1.connected&&c$1.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:l(),clientInfo:m()}),()=>{v.delete(o),c$1.emit("unsubscribeLiveQuery",{subscriptionId:o}),c$1.off("liveQueryData",s),c$1.off("liveQueryError",a);}}var j={init:K,on:U,once:N,off:O,emit:C,joinChannel:$,leaveChannel:F},M=j;var Q=null;function x(e){Q=e;}function ye(){return Q}function R(e){if(Q){console.warn("WebSocket already initialized. Skipping initialization.");return}let n=e?.provider||M;x(n);try{n.init({channels:e?.channels});}catch(r){throw x(null),r}}var d=null,g=null,u=new Map;function S(e){d!==e&&(d&&H(),R(),d=e,g=e.getQueryCache().subscribe(n=>{if(n.type==="removed"){let r=hashKey(n.query.queryKey),t=u.get(r);if(t){if(t.resolvers.size>0){let o=new Error("Query was removed from cache");t.resolvers.forEach(s=>s.reject(o)),t.resolvers.clear();}t.unsubscribe(),u.delete(r);}}}));}function H(){g&&(g(),g=null),u.forEach(e=>e.unsubscribe()),u.clear(),d=null;}var A=class{connect(n){S(n);}};function he(e,n={}){return {queryKey:[e,n],queryFn:()=>q(e,n)}}function ke(e,n={}){let r=["live",e,n],t=hashKey(r);return {queryKey:r,queryFn:()=>new Promise((o,s)=>{if(!d){let c=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",c.message),s(c);return}let a=u.get(t);a||(a={unsubscribe:w(e,n,l=>{let i=u.get(t);i?.resolvers.size&&(i.resolvers.forEach(f=>f.resolve(l)),i.resolvers.clear()),d&&d.setQueryData(r,l);},l=>{let i=u.get(t);i&&(i.resolvers.size&&(i.resolvers.forEach(f=>f.reject(new Error(l))),i.resolvers.clear()),i.unsubscribe(),u.delete(t));}),resolvers:new Set},u.set(t,a)),a.resolvers.add({resolve:o,reject:s});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function Ce(e,n={}){return {mutationFn:(r={})=>q(e,{...n,...r})}}function we(e,n={}){return [e,n]}var X="__MODELENCE_QUERY_STATE__";function Z(){if(typeof document>"u")return;let e=document.getElementById(X);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(n){console.error("Modelence: failed to parse SSR query state",n);return}}function Me({children:e,client:n,dehydratedState:r}){let[t]=useState(()=>{let s=n??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&S(s),s}),o=r??Z();return jsx(QueryClientProvider,{client:t,children:jsx(HydrationBoundary,{state:o,children:e})})}export{oe as a,w as b,x as c,ye as d,R as e,S as f,H as g,A as h,he as i,ke as j,Ce as k,we as l,Me as m};//# sourceMappingURL=chunk-IJ5BS7PM.js.map
2
+ //# sourceMappingURL=chunk-IJ5BS7PM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["isInitialized","AppProvider","children","loadingElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","useEffect","initConfig","initSession","jsx","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","ModelenceQueryClient","modelenceQuery","methodName","callMethod","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"uSAiBA,IAAIA,CAAAA,CAAgB,KAAA,CAEb,SAASC,EAAAA,CAAY,CAAE,QAAA,CAAAC,CAAAA,CAAU,cAAA,CAAAC,CAAe,CAAA,CAAqB,CAM1E,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C,CAAAA,CAAO,QAAA,CAAS,cAAA,CAAeF,CAAyB,CAAA,CAC9D,GAAI,EAAA,CAACE,CAAAA,EAAQ,CAACA,CAAAA,CAAK,WAAA,CAAA,CAInB,GAAI,CACF,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAAA,CAAK,WAAW,CACpC,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,CAAQ,KAAA,CAAM,4CAAA,CAA8CA,CAAC,CAAA,CAC7D,MACF,CACF,CAQO,SAASC,EAAAA,CAAuB,CACrC,QAAA,CAAApF,EACA,MAAA,CAAAqF,CAAAA,CACA,eAAA,CAAAC,CACF,CAAA,CAAgC,CAC9B,GAAM,CAACC,CAAc,CAAA,CAAIlF,QAAAA,CAAS,IAAM,CACtC,IAAMmF,EACJH,CAAAA,EACA,IAAII,WAAAA,CAAY,CACd,cAAA,CAAgB,CACd,OAAA,CAAS,CACP,SAAA,CAAW,GACb,CACF,CACF,CAAC,CAAA,CACH,OAAI,OAAO,MAAA,CAAW,GAAA,EACpB9B,CAAAA,CAA4B6B,CAAE,CAAA,CAEzBA,CACT,CAAC,CAAA,CAEKE,CAAAA,CAAQJ,CAAAA,EAAmBL,CAAAA,EAAoB,CAErD,OACEvE,GAAAA,CAACiF,mBAAAA,CAAA,CAAoB,MAAA,CAAQJ,CAAAA,CAC3B,QAAA,CAAA7E,GAAAA,CAACkF,iBAAAA,CAAA,CAAkB,KAAA,CAAOF,CAAAA,CAAQ,QAAA,CAAA1F,CAAAA,CAAS,CAAA,CAC7C,CAEJ","file":"chunk-IJ5BS7PM.js","sourcesContent":["/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n\n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession, isSessionInitialized } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n // Skip loading on the server (would defeat SSR) and when session is already\n // hydrated client-side (would cause a hydration mismatch).\n // INVARIANT: when SSR is enabled, `hydrateSession()` MUST run before\n // `hydrateRoot()` so `isSessionInitialized()` is true on the first render\n // and matches the server's `isLoading=false`. See renderApp.tsx.\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(() => !isServer && !isSessionInitialized());\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n return;\n }\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n socketClient = io('/', {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n startWebsockets();\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Cast required: the shared `subscriptions` map stores resolvers from\n // calls with different `T` instantiations, so the union must be erased.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport React, { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {x}from'./chunk-LDVLXJLS.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function f(t,e,u){let o=a(await x(t,e,u)),a$1=b(o);return c(o,a$1??void 0)}var p=new AsyncLocalStorage;function S(t,e){return p.run(t,e)}function g(){return p.getStore()}export{f as a,S as b,g as c};//# sourceMappingURL=chunk-JBTEZOY2.js.map
2
+ //# sourceMappingURL=chunk-JBTEZOY2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHASA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CAC5C,OAAOK,CAAAA,CAAoBL,CAAAA,CAAWG,GAAAA,EAAW,MAAS,CAC5D,CCDA,IAAMG,CAAAA,CAAU,IAAIC,kBAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,EAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,GAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-JBTEZOY2.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n/**\n * Invokes a Modelence method in-process and round-trips the result through the\n * same sanitize → typeMap → revive pipeline used by the HTTP transport, so\n * SSR consumers receive identical types to client callers.\n */\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n return reviveResponseTypes(sanitized, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",r="0.18.0-dev.1",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",h={url:"https://github.com/modelence/modelence/issues"},j="https://modelence.com",g={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",husky:"^9.1.7",jest:"^30.2.0","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},v={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,scripts:l,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:h,homepage:j,devDependencies:g,dependencies:x,peerDependencies:v};
2
+ export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,y as l,u as m,h as n,j as o,g as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-KU4GANYW.js.map
3
+ //# sourceMappingURL=chunk-KU4GANYW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,cAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,mBAAA,CACT,QAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAA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W,SAAA,CACX,UAAA,CAAY,SAAA,CACZ,IAAA,CAAQ,QAAA,CACR,OAAA,CAAW,QAAA,CACX,IAAA,CAAQ,SAAA,CACR,YAAa,QAAA,CACb,kBAAA,CAAoB,QAAA,CACpB,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,IAAA,CAAQ,QAAA,CACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,UACX,uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,SAAA,CACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,uBAAA,CAAyB,SAAA,CACzB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CA3GFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAeA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAwBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAKF","file":"chunk-KU4GANYW.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.18.0-dev.1\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^30.2.0\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import {a,b as b$1,l}from'./chunk-3SPXJEOR.js';import {a as a$2,b as b$2}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {isDeepStrictEqual}from'util';import {MongoError,ObjectId}from'mongodb';import {z}from'zod';import {randomBytes}from'crypto';var k=class{constructor(e,{stores:t=[],queries:i={},mutations:r={},routes:a=[],cronJobs:c={},configSchema:d={},rateLimits:m=[],channels:f=[]}={}){this.name=e,this.stores=t,this.queries=i,this.mutations=r,this.routes=a,this.cronJobs=c,this.configSchema=d,this.rateLimits=m,this.channels=f;}getConfig(e){return a(`${this.name}.${e}`)}};function b(n){let e=n._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:b(e.type)};if(e.typeName==="ZodObject"){let i=e.shape(),r={};for(let[a,c]of Object.entries(i))r[a]=b(c);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...b(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...b(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(b)};if(e.typeName==="ZodEffects"){let t=e;return t.description?{type:"custom",typeName:t.description}:b(t.schema)}return {type:"custom",typeName:e.typeName}}function R(n){let e={};for(let[t,i]of Object.entries(n))Array.isArray(i)?e[t]=i.map(r=>typeof r=="object"&&"_def"in r?b(r):R(r)):typeof i=="object"&&"_def"in i?e[t]=b(i):e[t]=R(i);return e}var se=["background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","sparse","storageEngine","textIndexVersion","unique","weights","wildcardProjection","2dsphereIndexVersion"],q=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),ae=n=>n.startsWith("_modelence_"),L=n=>{let e={};for(let t of se){let i=n[t];i!==void 0&&(e[t]=i);}return e},ce=(n,e)=>{if(!q(n)||!q(e))return false;let t=Object.entries(n),i=Object.entries(e);return t.length!==i.length?false:t.every(([r,a],c)=>{let[d,m]=i[c]||[];return r===d&&isDeepStrictEqual(a,m)})},J=(n,e)=>ce(n.key,e.key)?isDeepStrictEqual(L(n),L(e)):false,$=n=>q(n)?Object.entries(n).map(([e,t])=>`${e}:${JSON.stringify(t)}`).join("|"):null,de=async n=>{try{return await n.listIndexes().toArray()}catch(e){if(e instanceof MongoError&&e.code===26)return [];throw e}},le=n=>Object.entries(n).map(([e,t])=>`${e}_${t}`).join("_"),ue=n=>{if(n.name){let t=n.name.startsWith("_modelence_")?n.name:`_modelence_${n.name}`;return {...n,name:t}}let e=le(n.key);return {...n,name:`_modelence_${e}`}},S=class n{constructor(e,t){this._chainParent=null;this._chainChild=null;this.name=e,this.schema=t.schema,this.methods=t.methods,this.indexes=t.indexes.map(ue),this.searchIndexes=t.searchIndexes||[],this.indexCreationMode=t.indexCreationMode??"background";}getName(){return this.name}getIndexCreationMode(){return this.indexCreationMode}getSchema(){return this.schema}getSerializedSchema(){return R(this.schema)}getIndexes(){return this.indexes}getSearchIndexes(){return this.searchIndexes}getChainTail(){let e=this;for(;e._chainChild;)e=e._chainChild;return e}getChainRoot(){let e=this;for(;e._chainParent;)e=e._chainParent;return e}extend(e){let t=this.getChainTail();if(this.client||t.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);let i={...t.schema,...e.schema||{}},r=[...t.indexes,...e.indexes||[]],a=[...t.searchIndexes,...e.searchIndexes||[]],c={...t.methods||{},...e.methods||{}},d=new n(this.name,{schema:i,methods:c,indexes:r,searchIndexes:a,indexCreationMode:e.indexCreationMode??t.indexCreationMode});return t._chainChild=d,d._chainParent=t,d}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(e="full"){let t=this.requireCollection(),i=e!=="create-only",r=e!=="drop-only",a=await de(t),c=new Map,d=new Map,m=new Set,f=o=>{c.set(o.name,o);let l=$(o.key);if(!l)return;let u=d.get(l);u?u.add(o.name):d.set(l,new Set([o.name]));},x=o=>{let l=c.get(o);if(!l)return;c.delete(o);let u=$(l.key);if(!u)return;let g=d.get(u);g&&(g.delete(o),g.size===0&&d.delete(u));};for(let o of a)typeof o.name=="string"&&f({...o,name:o.name});let y=async o=>{if(!(o==="_id_"||m.has(o))){try{await t.dropIndex(o);}catch(l){if(!(l instanceof MongoError&&l.code===27))throw l}m.add(o),x(o);}};if(i){let o=new Set(this.indexes.map(u=>u.name).filter(u=>typeof u=="string")),l=[...c.values()].filter(u=>ae(u.name)&&!o.has(u.name));for(let u of l)await y(u.name);}if(this.indexes.length>0)for(let o of this.indexes){if(!o.name)continue;let l=false,u=c.get(o.name);u&&!J(u,o)&&(i?await y(u.name):l=true);let g=$(o.key);if(g){let O=[...d.get(g)||[]];for(let I of O)I!==o.name&&(i?await y(I):l=true);}let _=c.get(o.name);!(!!_&&J(_,o))&&r&&!l&&(await t.createIndexes([o]),f({name:o.name,key:o.key,...L(o)}));}if(r&&this.searchIndexes.length>0)for(let o of this.searchIndexes)try{await t.createSearchIndexes([o]);}catch(l){if(l instanceof MongoError&&l.code===68&&o.name)await t.dropSearchIndex(o.name),await t.createSearchIndexes([o]);else throw l}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,t){let i=await this.requireCollection().findOne(e,t);return i?this.wrapDocument(i):null}async requireOne(e,t,i){let r=await this.findOne(e,t);if(!r)throw i?i():new Error(`Record not found in ${this.name}`);return r}find(e,t){let i=this.requireCollection().find(e,t?.projection?{projection:t.projection}:void 0);return t?.sort&&i.sort(t.sort),t?.limit&&i.limit(t.limit),t?.skip&&i.skip(t.skip),i}async findById(e){let t=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(t)}async requireById(e,t){let i=await this.findById(e);if(!i)throw t?t():new Error(`Record with id ${e} not found in ${this.name}`);return i}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,t){return (await this.find(e,t).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e,t){return await this.requireCollection().insertOne(e,t)}async insertMany(e,t){return await this.requireCollection().insertMany(e,t)}async updateOne(e,t,i){return await this.requireCollection().updateOne(this.getSelector(e),t,i)}async upsertOne(e,t,i){return await this.requireCollection().updateOne(this.getSelector(e),t,{upsert:true,...i})}async updateMany(e,t,i){return await this.requireCollection().updateMany(e,t,i)}async upsertMany(e,t,i){return await this.requireCollection().updateMany(e,t,{upsert:true,...i})}async deleteOne(e,t){return await this.requireCollection().deleteOne(e,t)}async deleteMany(e,t){return await this.requireCollection().deleteMany(e,t)}async findOneAndUpdate(e,t,i){let r=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,i??{});return r?this.wrapDocument(r):null}async findOneAndDelete(e,t){let i=await this.requireCollection().findOneAndDelete(this.getSelector(e),t??{});return i?this.wrapDocument(i):null}async findOneAndReplace(e,t,i){let r=await this.requireCollection().findOneAndReplace(this.getSelector(e),t,i??{});return r?this.wrapDocument(r):null}async replaceOne(e,t,i){return await this.requireCollection().replaceOne(this.getSelector(e),t,i)}async distinct(e,t,i){let r=t??{};return i!==void 0?await this.requireCollection().distinct(e,r,i):await this.requireCollection().distinct(e,r)}watch(e,t){return this.requireCollection().watch(e,t)}aggregate(e,t){return this.requireCollection().aggregate(e,t)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,t){let i=this.getDatabase();if(!this.collection||!i)throw new Error(`Store ${this.name} is not provisioned`);if((await i.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await i.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await i.collection(e).rename(this.name,t);}async vectorSearch({field:e,embedding:t,numCandidates:i,limit:r,projection:a,indexName:c}){return this.aggregate([{$vectorSearch:{index:c||e+"VectorSearch",path:e,queryVector:t,numCandidates:i||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...a}}])}static vectorIndex({field:e,dimensions:t,similarity:i="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:t,similarity:i}]}}}};var pe=z.string.bind(z),he=z.number.bind(z),me=z.date.bind(z),ye=z.boolean.bind(z),fe=z.array.bind(z),ge=z.object.bind(z),Te=z.enum.bind(z),s={string:pe,number:he,date:me,boolean:ye,array:fe,object:ge,enum:Te,embedding(){return z.array(z.number())},objectId(){return z.instanceof(ObjectId).describe("ObjectId")},userId(){return z.instanceof(ObjectId).describe("UserId")},ref(n){return z.instanceof(ObjectId).describe("Ref")},union:z.union.bind(z),infer(n){return {}}};var X=new S("_modelenceUsers",{schema:{handle:s.string(),emails:s.array(s.object({address:s.string(),verified:s.boolean()})).optional(),status:s.enum(["active","disabled","deleted"]).optional(),firstName:s.string().optional(),lastName:s.string().optional(),avatarUrl:s.string().optional(),createdAt:s.date(),disabledAt:s.date().optional(),deletedAt:s.date().optional(),roles:s.array(s.string()).optional(),authMethods:s.object({password:s.object({hash:s.string()}).optional(),google:s.object({id:s.string()}).optional(),github:s.object({id:s.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"authMethods.google.id":1},sparse:true,unique:true},{key:{"authMethods.github.id":1},sparse:true,unique:true}]}),St=new S("_modelenceDisposableEmailDomains",{schema:{domain:s.string(),addedAt:s.date()},indexes:[{key:{domain:1},unique:true}]}),xt=new S("_modelenceEmailVerificationTokens",{schema:{userId:s.objectId(),email:s.string().optional(),token:s.string(),createdAt:s.date(),expiresAt:s.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),bt=new S("_modelenceResetPasswordTokens",{schema:{userId:s.objectId(),email:s.string().optional(),token:s.string(),createdAt:s.date(),expiresAt:s.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var G=new Map,C={authenticated:null,unauthenticated:null};function Dt(n,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[t,i]of Object.entries(n))G.set(t,i);}function Y(){return C.unauthenticated?[C.unauthenticated]:[]}function ee(){return C.authenticated?[C.authenticated]:[]}function W(n,e){let t=e.find(i=>!Se(n,i));if(t)throw new Error(`Access denied - missing permission: '${t}'`)}function Se(n,e){for(let t of n)if(G.get(t)?.permissions?.includes(e))return true;return false}var D=new S("_modelenceSessions",{schema:{authToken:s.string(),createdAt:s.date(),expiresAt:s.date(),userId:s.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0},{key:{userId:1}}]});async function te(n){let e=n?await D.findOne({authToken:n}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await be()}async function kt(n,e){await D.updateOne({authToken:n},{$set:{userId:e}});}async function Rt(n){await D.updateOne({authToken:n},{$set:{userId:null}});}async function Et(n){await D.deleteMany({userId:n});}async function be(n=null){let e=randomBytes(32).toString("base64url"),t=Date.now(),i=new Date(t+a$1.days(7));return await D.insertOne({authToken:e,createdAt:new Date(t),expiresAt:i,userId:n}),{authToken:e,expiresAt:i,userId:n}}async function we(n){let e=Date.now(),t=new Date(e+a$1.days(7));await D.updateOne({authToken:n.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:t}});}function De(n,e){n.cookie("authToken",e,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict",path:"/"});}function Ft(n){n.clearCookie("authToken",{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict",path:"/"});}var jt=new k("_system.session",{stores:[D],mutations:{init:async function(n,{session:e,user:t,res:i}){return i&&e&&De(i,e.authToken),{session:e,user:t,configs:b$1()}},heartbeat:async function(n,{session:e}){e&&await we(e);}}});async function ne(n){let e=await te(n),t=e.userId?await X.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,i=t?{id:t._id.toString(),handle:t.handle,roles:t.roles||[],hasRole:a=>(t.roles||[]).includes(a),requireRole:a=>{if(!(t.roles||[]).includes(a))throw new Error(`Access denied - role '${a}' required`)},firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0}:null,r=i?ee():Y();return {user:i,session:e,roles:r}}var v=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function Ce(){return typeof window!="object"}function w(){if(!Ce())throw new Error("This function can only be called on the server")}function Ut(n){return n.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var M=new Map;function Oe(n){let e=M.get(n.id);return e||(e=new Map,M.set(n.id,e)),e}async function ve(n,e){let t=z.object({subscriptionId:z.string().min(1),method:z.string().min(1),args:z.record(z.unknown()).default({}),authToken:z.string().nullish(),clientInfo:z.object({screenWidth:z.number(),screenHeight:z.number(),windowWidth:z.number(),windowHeight:z.number(),pixelRatio:z.number(),orientation:z.string().nullable()}).optional()}).safeParse(e);if(!t.success){n.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${t.error.message}`});return}let{subscriptionId:i,method:r,args:a,authToken:c,clientInfo:d}=t.data,m=Oe(n),f=m.get(i);if(f)if(f.cleanup)try{f.cleanup();}catch(y){console.error("[LiveQuery] Error cleaning up existing subscription:",y);}else f.aborted=true;let x={cleanup:null};m.set(i,x);try{let{session:y,user:o,roles:l}=await ne(c??null),u={session:y,user:o,roles:l,clientInfo:d??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:n.handshake.address,userAgent:n.handshake.headers["user-agent"]},res:null},g=await ie(r,a,u),_=async()=>{let T=a$2(await g.fetch());x.aborted||n.emit("liveQueryData",{subscriptionId:i,data:T,typeMap:b$2(T)});},A=!0,O=!1,I=()=>{x.aborted||!A||O||(A=!1,O=!0,_().catch(T=>{x.aborted||(console.error(`[LiveQuery] Error fetching data for ${r}:`,T),n.emit("liveQueryError",{subscriptionId:i,error:T instanceof Error?T.message:String(T)}));}).finally(()=>{O=!1,I();}));},j=g.watch({publish:()=>{A=!0,I();}});if(x.aborted){if(j)try{j();}catch(T){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",T);}return}x.cleanup=j||null,I();}catch(y){m.delete(i),console.error(`[LiveQuery] Error in ${r}:`,y),n.emit("liveQueryError",{subscriptionId:i,error:y instanceof Error?y.message:String(y)});}}function Me(n,e){let t=z.object({subscriptionId:z.string().min(1)}).safeParse(e);if(!t.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${t.error.message}`);return}let{subscriptionId:i}=t.data,r=M.get(n.id);if(!r)return;let a=r.get(i);if(a){if(a.cleanup)try{a.cleanup();}catch(c){console.error("[LiveQuery] Error in cleanup:",c);}else a.aborted=true;r.delete(i);}}function _e(n){let e=M.get(n.id);if(e){for(let t of e.values())if(t.cleanup)try{t.cleanup();}catch(i){console.error("[LiveQuery] Error in cleanup on disconnect:",i);}else t.aborted=true;M.delete(n.id);}}var E={};function rn(n,e){return w(),re(n),F("query",n,e)}function on(n,e){return w(),re(n),F("mutation",n,e)}function sn(n,e){return w(),oe(n),F("query",n,e)}function an(n,e){return w(),oe(n),F("mutation",n,e)}function re(n){if(n.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${n})`)}function oe(n){if(!n.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${n})`)}function F(n,e,t){if(w(),E[e])throw new Error(`Method with name '${e}' is already defined.`);let i=typeof t=="function"?t:t.handler,r=typeof t=="function"?[]:t.permissions??[];E[e]={type:n,name:e,handler:i,permissions:r};}async function cn(n,e,t){w();let i=E[n];if(!i)throw new Error(`Method with name '${n}' is not defined.`);let{type:r,handler:a}=i,c=l("method",`method:${n}`,{type:r,args:e}),d;try{W(t.roles,i.permissions),d=await a(e,t);}catch(m){throw c.end("error"),m}return c.end(),d}async function ie(n,e,t){w();let i=E[n];if(!i)throw new Error(`Method with name '${n}' is not defined.`);let{type:r,handler:a}=i;if(r!=="query")throw new Error("Live methods are only supported for queries");let c=l("method",`method:${n}:live`,{type:r,args:e}),d;try{if(W(t.roles,i.permissions),d=await a(e,t),!(d instanceof v))throw new Error(`Live query handler for '${n}' must return a LiveData object with fetch and watch functions. See https://docs.modelence.com/live-queries`)}catch(m){throw c.end("error"),m}return c.end(),d}
2
+ export{_e as A,k as a,S as b,s as c,kt as d,Rt as e,Et as f,be as g,De as h,Ft as i,jt as j,X as k,St as l,xt as m,bt as n,Dt as o,Y as p,ne as q,v as r,Ut as s,rn as t,on as u,sn as v,an as w,cn as x,ve as y,Me as z};//# sourceMappingURL=chunk-LDVLXJLS.js.map
3
+ //# sourceMappingURL=chunk-LDVLXJLS.js.map