modelence 0.10.12 → 0.11.0-dev.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,6 +58,9 @@ See what you can build in just a few hours with Modelence's batteries-included a
58
58
  ## Getting Started
59
59
  Modelence is an all-in-one TypeScript framework for startups shipping production apps, with the mission to eliminate all boilerplate for standard features that modern web applications need, like authentication, database setup, cron jobs, AI observability, email and more.
60
60
 
61
+ > **Prerequisites:** Modelence requires [Node.js 20.20](https://nodejs.org/en/download) or higher.
62
+
63
+
61
64
  ### Quick Start
62
65
 
63
66
  #### 1. Create a new project
@@ -81,6 +84,78 @@ Your app will be available at [http://localhost:3000](http://localhost:3000)
81
84
 
82
85
  For a more detailed guide, check out the [Todo App tutorial](https://docs.modelence.com/tutorial).
83
86
 
87
+ ---
88
+
89
+ ### Local Development (Modelence Framework)
90
+
91
+ If you want to contribute to Modelence itself (not just use it in an application), follow the steps below.
92
+
93
+ #### 1. Clone the repository
94
+ ```bash
95
+ git clone https://github.com/modelence/modelence.git
96
+ cd modelence
97
+ ```
98
+
99
+ #### 2. Install dependencies for the core package
100
+ ```bash
101
+ cd packages/modelence
102
+ npm install
103
+ ```
104
+
105
+ #### 3. Build the package
106
+ ```bash
107
+ npm run build
108
+ ```
109
+
110
+ This generates the `dist/` directory required for local usage.
111
+
112
+ #### 4. (Optional) Watch for changes during development
113
+ ```bash
114
+ npm run dev
115
+ ```
116
+
117
+ This runs the build in watch mode and rebuilds on file changes.
118
+
119
+ > **Note**
120
+ >
121
+ > If you encounter dependency or build errors while developing Modelence locally, a clean install may help:
122
+ >
123
+ > ```bash
124
+ > rm -rf node_modules package-lock.json
125
+ > npm install
126
+ > npm run build
127
+ > ```
128
+ >
129
+ > This resets the local dependency state and mirrors the workflow often recommended when resolving local development issues.
130
+ > The regenerated `package-lock.json` is only for local development and should not be committed as part of a PR unless explicitly requested.
131
+
132
+ ### Using the local build in a test app
133
+
134
+ To test your local Modelence changes inside a real application:
135
+ ```bash
136
+ npx create-modelence-app@latest my-app
137
+ cd my-app
138
+ ```
139
+
140
+ Update `package.json` to point to your local Modelence package:
141
+ ```json
142
+ {
143
+ "dependencies": {
144
+ "modelence": "../modelence/packages/modelence"
145
+ }
146
+ }
147
+ ```
148
+
149
+ Then reinstall dependencies and start the app:
150
+ ```bash
151
+ npm install
152
+ npm run dev
153
+ ```
154
+
155
+ Your application will now use your local Modelence build.
156
+
157
+ ---
158
+
84
159
  ### Examples
85
160
 
86
161
  For more examples on how to use Modelence, check out https://github.com/modelence/examples
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {s}from'../chunk-UGJXO42W.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import M,{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 R(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 U(){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 V(e){return String(e).replace(/"/g,'\\"')}async function z(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await z(o),await U()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await R(e.token,e.host),s={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},i=Object.entries(s).map(([a,n])=>`${a}="${V(n)}"`).join(`
2
+ import {t}from'../chunk-JBVRKV7T.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import M,{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 R(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 U(){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 V(e){return String(e).replace(/"/g,'\\"')}async function z(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await z(o),await U()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await R(e.token,e.host),s={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},i=Object.entries(s).map(([a,n])=>`${a}="${V(n)}"`).join(`
3
3
  `);await promises.writeFile(o,i.trim()+`
4
- `),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var h=null,N=null;function W(){if(!h)throw new Error("Environment variables not loaded");return h}function D(){if(!N)throw new Error("Configuration not loaded");return N}function O(e){return `${W().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=D();return join(e,o).replace(/\\/g,"/")}function P(){return D().postBuildCommand}function E(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){try{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()}).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 Z(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}await ee();}async function ee(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:M.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function oe(){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,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],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 oe(),await Z(),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 j(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 $(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await v(),await le(r);let{token:i}=await j(s),{bundleName:a}=await pe(e.app,e.env,r,i,s);await promises.unlink(r),await de(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,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 pe(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),S=await fetch(a,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!S.ok)throw new Error(`Failed to upload bundle: ${S.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function de(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 B(){console.log("Starting Modelence dev server...");let e=p(),o=M.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function _(){console.log("Starting Modelence production server...");let e=p(),o=M.basename(e,M.extname(e)),t=E(`${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 k(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(),B();});u.command("start").description("Start production server").action(async()=>{await 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 W(){if(!h)throw new Error("Environment variables not loaded");return h}function D(){if(!N)throw new Error("Configuration not loaded");return N}function O(e){return `${W().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=D();return join(e,o).replace(/\\/g,"/")}function P(){return D().postBuildCommand}function E(e){let o=x("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=d(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function m(){try{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()}).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 Z(){let e=P();if(e){console.log("Running post-build command..."),execSync(e);return}await ee();}async function ee(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:M.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function oe(){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,treeshake:true,platform:"node",external:[...Object.keys(t.dependencies??{}),...Object.keys(t.peerDependencies??{})],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 oe(),await Z(),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 j(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 $(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||O("");await v(),await le(r);let{token:i}=await j(s),{bundleName:a}=await pe(e.app,e.env,r,i,s);await promises.unlink(r),await de(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,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 pe(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),S=await fetch(a,{method:"PUT",body:new Uint8Array(g),headers:{"Content-Type":"application/zip"}});if(!S.ok)throw new Error(`Failed to upload bundle: ${S.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function de(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 B(){console.log("Starting Modelence dev server...");let e=p(),o=M.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function _(){console.log("Starting Modelence production server...");let e=p(),o=M.basename(e,M.extname(e)),t=E(`${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 k(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(),B();});u.command("start").description("Start production server").action(async()=>{await m(),_();});u.parse(process.argv);//# sourceMappingURL=modelence.js.map
5
5
  //# sourceMappingURL=modelence.js.map
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",r="0.11.0-dev.7",o="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",c="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"],l={modelence:"./dist/bin/modelence.js"},a={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",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"},u="Modelence",y="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},j="https://modelence.com",h={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@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:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","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={react:">=18.0.0","react-dom":">=18.0.0"},b={access:"public",provenance:true},k={type:s,name:i,version:r,description:o,main:n,types:c,exports:p,files:d,bin:l,scripts:a,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:u,license:y,bugs:g,homepage:j,devDependencies:h,dependencies:x,peerDependencies:v,publishConfig:b};
2
+ export{s as a,i as b,r as c,o as d,n as e,c as f,p as g,d as h,l as i,a as j,m as k,u as l,y as m,g as n,j as o,h as p,x as q,v as r,b as s,k as t};//# sourceMappingURL=chunk-JBVRKV7T.js.map
3
+ //# sourceMappingURL=chunk-JBVRKV7T.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","publishConfig","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,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,YAAA,CAAc,2BAAA,CACd,cAAA,CAAkB,eAAA,CAClB,IAAA,CAAQ,8CACR,YAAA,CAAc,qDAAA,CACd,eAAA,CAAiB,wDAAA,CACjB,WAAA,CAAe,6BAAA,CACf,OAAA,CAAW,8CACb,CAAA,CAIAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,CAAAA,CAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA,CAAO,+CACT,CAAA,CACAC,CAAAA,CAAY,uBAAA,CACZC,CAAAA,CAAmB,CACjB,kBAAmB,QAAA,CACnB,eAAA,CAAiB,QAAA,CACjB,sBAAA,CAAwB,QAAA,CACxB,gBAAA,CAAkB,QAAA,CAClB,iBAAA,CAAmB,SAAA,CACnB,aAAA,CAA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,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,EAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAcA,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,CAuBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAAAA,CAIA,aAAA,CAAAC,CAIF","file":"chunk-JBVRKV7T.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.11.0-dev.7\",\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 \"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 \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\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\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"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 \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true\n }\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -107,6 +107,20 @@ declare function loginWithPassword(options: {
107
107
  declare function verifyEmail(options: {
108
108
  token: string;
109
109
  }): Promise<void>;
110
+ /**
111
+ * Resend the verification email for a given email address.
112
+ * The email is only sent if the address is registered and not yet verified.
113
+ * A generic response is always returned to avoid leaking account information.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * await resendEmailVerification({ email: 'user@example.com' });
118
+ * ```
119
+ * @param options.email - The email address to resend verification to.
120
+ */
121
+ declare function resendEmailVerification(options: {
122
+ email: string;
123
+ }): Promise<void>;
110
124
  /**
111
125
  * Logout the current user.
112
126
  *
@@ -142,4 +156,4 @@ declare function getLocalStorageSession(): any;
142
156
 
143
157
  declare const AppProvider: any;
144
158
 
145
- export { AppProvider, ClientChannel, type MethodArgs, MethodError, type UserInfo, callMethod, getConfig, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, useSession, verifyEmail };
159
+ export { AppProvider, ClientChannel, type MethodArgs, MethodError, type UserInfo, callMethod, getConfig, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, useSession, verifyEmail };
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-3S2FFBNS.js';import {a}from'./chunk-DO5TZLF5.js';import q,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import le from'react-dom/client';import de from'socket.io-client';function v(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function R(e){localStorage.setItem("modelence.session",JSON.stringify(e));}async function K(e){let{email:r,password:t}=e;await i("_system.user.signupWithPassword",{email:r,password:t});}async function B(e){let{email:r,password:t}=e,{user:n}=await i("_system.user.loginWithPassword",{email:r,password:t});return b(n)}async function V(e){let{token:r}=e;await i("_system.user.verifyEmail",{token:r});}async function F(){await i("_system.user.logout"),b(null);}async function G(e){let{email:r}=e;await i("_system.user.sendResetPasswordToken",{email:r});}async function X(e){let{token:r,password:t}=e;await i("_system.user.resetPassword",{token:r,password:t});}function c(){return v()?.authToken}function l(){return {screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var I=(e,r)=>{console.error(`Error calling method '${r}':`,e);};function A(e){I=e;}function W(e,r){return I(e,r)}var w=class extends Error{constructor(r,t){super(r),this.name="MethodError",this.status=t;}};async function i(e,r={},t={}){try{return await Y(`/api/_internal/method/${e}`,r)}catch(n){throw (t.errorHandler??W)(n,e),n}}async function Y(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:c(),clientInfo:l()})});if(!t.ok){let s=await t.text();throw new w(s,t.status)}let n=await t.text(),o=n?JSON.parse(n):void 0;if(!o)throw new Error("Invalid response from server");return b$1(o.data,o.typeMap)}var L={};function Z(e){return L[e]?.value}function M(e){L=e;}var k=create(e=>({user:null,setUser:r=>e({user:r})})),H=false,re=a.seconds(30),oe=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string())});function U(e){if(!e)return null;let r=oe.parse(e);return Object.freeze({...r,hasRole:t=>r.roles.includes(t),requireRole:t=>{if(!r.roles.includes(t))throw new Error(`Access denied - role '${t}' required`)}})}async function N(){if(H)return;H=true;let{configs:e,session:r,user:t}=await i("_system.session.init");M(e),R(r),k.getState().setUser(U(t)),await _();}async function _(){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(_,re);}function b(e){let r=U(e);return k.getState().setUser(r),r}function ne(){return {user:k(r=>r.user)}}var O=false;function C({children:e,loadingElement:r}){let[t,n]=useState(true);return useEffect(()=>{async function o(){O||(O=true,await N(),n(false));}o();},[]),t?r??jsx("div",{children:"Loading..."}):e}function ue({loadingElement:e,routesElement:r,favicon:t,errorHandler:n}){if(n&&A(n),window.addEventListener("unload",()=>{}),le.createRoot(document.getElementById("root")).render(jsx(q.StrictMode,{children:jsx(z,{loadingElement:e,children:r})})),t){let o=document.querySelector("link[rel~='icon']");if(o)o.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}var d=null,p=new Map;function f(){if(!d)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return d}function pe(){let e=c(),r=l();for(let t of p.values())d?.emit("subscribeLiveQuery",{subscriptionId:t.subscriptionId,method:t.method,args:t.args,authToken:e,clientInfo:r});}function fe(e){d=de("/",{auth:{token:c()}}),d.on("connect",()=>{p.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${p.size} live queries`),pe());}),e.channels?.forEach(r=>r.init());}function ge({category:e,listener:r}){f().on(e,r);}function me({category:e,listener:r}){f().once(e,r);}function he({category:e,listener:r}){f().off(e,r);}function S({eventName:e,category:r,id:t}){f().emit(e,`${r}:${t}`);}function we({category:e,id:r}){S({eventName:"joinChannel",category:e,id:r});}function ye({category:e,id:r}){S({eventName:"leaveChannel",category:e,id:r});}var ve=0;function D(e,r,t,n){let o=`sub-${++ve}-${Date.now()}`,s=({subscriptionId:y,data:m,typeMap:J})=>{y===o&&t(b$1(m,J));},E=({subscriptionId:y,error:m})=>{y===o&&(console.error(`[Modelence] Live query error for ${e}:`,m),n?.(m));},a=f();return a.on("liveQueryData",s),a.on("liveQueryError",E),p.set(o,{subscriptionId:o,method:e,args:r}),a.connected&&a.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:r,authToken:c(),clientInfo:l()}),()=>{p.delete(o),a.emit("unsubscribeLiveQuery",{subscriptionId:o}),a.off("liveQueryData",s),a.off("liveQueryError",E);}}var be={init:fe,on:ge,once:me,off:he,emit:S,joinChannel:we,leaveChannel:ye},$=be;var x=null;function j(e){x=e;}function g(){return x}function ke(e){if(x){console.warn("WebSocket already initialized. Skipping initialization.");return}let r=e?.provider||$;r.init({channels:e?.channels}),j(r);}var T=class{constructor(r,t){this.category=r,this.onMessage=t;}init(){g()?.on({category:this.category,listener:this.onMessage});}joinChannel(r){g()?.joinChannel({category:this.category,id:r});}leaveChannel(r){g()?.leaveChannel({category:this.category,id:r});}};var z="useClient"in q?q.useClient(C):C;export{z as AppProvider,T as ClientChannel,w as MethodError,i as callMethod,Z as getConfig,v as getLocalStorageSession,g as getWebsocketClientProvider,B as loginWithPassword,F as logout,ue as renderApp,X as resetPassword,G as sendResetPasswordToken,j as setWebsocketClientProvider,K as signupWithPassword,ke as startWebsockets,D as subscribeLiveQuery,ne as useSession,V as verifyEmail};//# sourceMappingURL=client.js.map
1
+ import {b as b$1}from'./chunk-3S2FFBNS.js';import {a}from'./chunk-DO5TZLF5.js';import q,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import de from'react-dom/client';import pe from'socket.io-client';function v(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function R(e){localStorage.setItem("modelence.session",JSON.stringify(e));}async function V(e){let{email:r,password:t}=e;await i("_system.user.signupWithPassword",{email:r,password:t});}async function K(e){let{email:r,password:t}=e,{user:n}=await i("_system.user.loginWithPassword",{email:r,password:t});return b(n)}async function B(e){let{token:r}=e;await i("_system.user.verifyEmail",{token:r});}async function F(e){let{email:r}=e;await i("_system.user.resendEmailVerification",{email:r});}async function G(){await i("_system.user.logout"),b(null);}async function X(e){let{email:r}=e;await i("_system.user.sendResetPasswordToken",{email:r});}async function Y(e){let{token:r,password:t}=e;await i("_system.user.resetPassword",{token:r,password:t});}function c(){return v()?.authToken}function l(){return {screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var I=(e,r)=>{console.error(`Error calling method '${r}':`,e);};function A(e){I=e;}function W(e,r){return I(e,r)}var w=class extends Error{constructor(r,t){super(r),this.name="MethodError",this.status=t;}};async function i(e,r={},t={}){try{return await Z(`/api/_internal/method/${e}`,r)}catch(n){throw (t.errorHandler??W)(n,e),n}}async function Z(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:c(),clientInfo:l()})});if(!t.ok){let s=await t.text();throw new w(s,t.status)}let n=await t.text(),o=n?JSON.parse(n):void 0;if(!o)throw new Error("Invalid response from server");return b$1(o.data,o.typeMap)}var L={};function ee(e){return L[e]?.value}function M(e){L=e;}var k=create(e=>({user:null,setUser:r=>e({user:r})})),H=false,te=a.seconds(30),ne=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string())});function U(e){if(!e)return null;let r=ne.parse(e);return Object.freeze({...r,hasRole:t=>r.roles.includes(t),requireRole:t=>{if(!r.roles.includes(t))throw new Error(`Access denied - role '${t}' required`)}})}async function N(){if(H)return;H=true;let{configs:e,session:r,user:t}=await i("_system.session.init");M(e),R(r),k.getState().setUser(U(t)),await _();}async function _(){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(_,te);}function b(e){let r=U(e);return k.getState().setUser(r),r}function ie(){return {user:k(r=>r.user)}}var O=false;function C({children:e,loadingElement:r}){let[t,n]=useState(true);return useEffect(()=>{async function o(){O||(O=true,await N(),n(false));}o();},[]),t?r??jsx("div",{children:"Loading..."}):e}function ue({loadingElement:e,routesElement:r,favicon:t,errorHandler:n}){if(n&&A(n),window.addEventListener("unload",()=>{}),de.createRoot(document.getElementById("root")).render(jsx(q.StrictMode,{children:jsx(z,{loadingElement:e,children:r})})),t){let o=document.querySelector("link[rel~='icon']");if(o)o.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}var u=null,p=new Map;function f(){if(!u)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return u}function fe(){let e=c(),r=l();for(let t of p.values())u?.emit("subscribeLiveQuery",{subscriptionId:t.subscriptionId,method:t.method,args:t.args,authToken:e,clientInfo:r});}function ge(e){u=pe("/",{auth:{token:c()}}),u.on("connect",()=>{p.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${p.size} live queries`),fe());}),e.channels?.forEach(r=>r.init());}function me({category:e,listener:r}){f().on(e,r);}function he({category:e,listener:r}){f().once(e,r);}function we({category:e,listener:r}){f().off(e,r);}function S({eventName:e,category:r,id:t}){f().emit(e,`${r}:${t}`);}function ye({category:e,id:r}){S({eventName:"joinChannel",category:e,id:r});}function ve({category:e,id:r}){S({eventName:"leaveChannel",category:e,id:r});}var be=0;function D(e,r,t,n){let o=`sub-${++be}-${Date.now()}`,s=({subscriptionId:y,data:m,typeMap:J})=>{y===o&&t(b$1(m,J));},T=({subscriptionId:y,error:m})=>{y===o&&(console.error(`[Modelence] Live query error for ${e}:`,m),n?.(m));},a=f();return a.on("liveQueryData",s),a.on("liveQueryError",T),p.set(o,{subscriptionId:o,method:e,args:r}),a.connected&&a.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:r,authToken:c(),clientInfo:l()}),()=>{p.delete(o),a.emit("unsubscribeLiveQuery",{subscriptionId:o}),a.off("liveQueryData",s),a.off("liveQueryError",T);}}var ke={init:ge,on:me,once:he,off:we,emit:S,joinChannel:ye,leaveChannel:ve},$=ke;var x=null;function j(e){x=e;}function g(){return x}function Ce(e){if(x){console.warn("WebSocket already initialized. Skipping initialization.");return}let r=e?.provider||$;r.init({channels:e?.channels}),j(r);}var E=class{constructor(r,t){this.category=r,this.onMessage=t;}init(){g()?.on({category:this.category,listener:this.onMessage});}joinChannel(r){g()?.joinChannel({category:this.category,id:r});}leaveChannel(r){g()?.leaveChannel({category:this.category,id:r});}};var z="useClient"in q?q.useClient(C):C;export{z as AppProvider,E as ClientChannel,w as MethodError,i as callMethod,ee as getConfig,v as getLocalStorageSession,g as getWebsocketClientProvider,K as loginWithPassword,G as logout,ue as renderApp,F as resendEmailVerification,Y as resetPassword,X as sendResetPasswordToken,j as setWebsocketClientProvider,V as signupWithPassword,Ce as startWebsockets,D as subscribeLiveQuery,ie as useSession,B as verifyEmail};//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/localStorage.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","signupWithPassword","options","email","password","callMethod","loginWithPassword","user","setCurrentUser","verifyEmail","token","logout","sendResetPasswordToken","resetPassword","getAuthToken","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,EAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,EAAiB,CACtD,YAAA,CAAa,OAAA,CAAQ,mBAAA,CAAqB,KAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCiBA,eAAsBC,CAAAA,CAAmBC,CAAAA,CAA8C,CACrF,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAIF,CAAAA,CAC5B,MAAMG,EAAW,iCAAA,CAAmC,CAAE,KAAA,CAAAF,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,EACzE,CAYA,eAAsBE,CAAAA,CAAkBJ,CAAAA,CAA8C,CACpF,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAA,CAAIF,CAAAA,CACtB,CAAE,IAAA,CAAAK,CAAK,CAAA,CAAI,MAAMF,CAAAA,CAAkC,iCAAkC,CACzF,KAAA,CAAAF,CAAAA,CACA,QAAA,CAAAC,CACF,CAAC,CAAA,CAED,OADqBI,CAA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AAA,EAAYyB,CAAAA,CACpCG,CAAAA,CAAS,IAAA,CAAK,CACZ,QAAA,CAAU5B,CAAAA,EAAO,QACnB,CAAC,CAAA,CACD2B,CAAAA,CAA2BC,CAAQ,EACrC,CC5BO,IAAMG,CAAAA,CAAN,KAAiC,CAItC,YAAY3B,CAAAA,CAAkB4B,CAAAA,CAA8B,CAC1D,IAAA,CAAK,SAAW5B,CAAAA,CAChB,IAAA,CAAK,SAAA,CAAY4B,EACnB,CAEA,IAAA,EAAO,CACLH,CAAAA,IAA8B,EAAA,CAAG,CAC/B,QAAA,CAAU,IAAA,CAAK,SACf,QAAA,CAAU,IAAA,CAAK,SACjB,CAAC,EACH,CAEA,WAAA,CAAYnB,CAAAA,CAAY,CACtBmB,CAAAA,EAA2B,EAAG,WAAA,CAAY,CACxC,SAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CAEA,YAAA,CAAaA,CAAAA,CAAY,CACvBmB,CAAAA,EAA2B,EAAG,YAAA,CAAa,CACzC,SAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CACF,ECzBO,IAAMlC,EACX,WAAA,GAAea,CAAAA,CAEXA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { ClientInfo } from '@/methods/types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n await callMethod('_system.user.signupWithPassword', { email, password });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n\n constructor(message: string, status: number) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\nexport async function callMethod<T = unknown>(\n methodName: string,\n args: MethodArgs = {},\n options: CallMethodOptions = {}\n): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new MethodError(error, response.status);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const parsedData = userSchema.parse(user);\n\n return Object.freeze({\n ...parsedData,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object;\n user: object;\n }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import 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 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) {\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 provider.init({\n channels: props?.channels,\n });\n setWebsocketClientProvider(provider);\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n logout,\n sendResetPasswordToken,\n resetPassword,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n"]}
1
+ {"version":3,"sources":["../src/client/localStorage.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","signupWithPassword","options","email","password","callMethod","loginWithPassword","user","setCurrentUser","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","getAuthToken","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,KAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,OAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuB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,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CAEA,YAAA,CAAaA,CAAAA,CAAY,CACvBmB,CAAAA,EAA2B,EAAG,YAAA,CAAa,CACzC,SAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CACF,ECzBO,IAAMlC,EACX,WAAA,GAAea,CAAAA,CAEXA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { ClientInfo } from '@/methods/types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n await callMethod('_system.user.signupWithPassword', { email, password });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n\n constructor(message: string, status: number) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\nexport async function callMethod<T = unknown>(\n methodName: string,\n args: MethodArgs = {},\n options: CallMethodOptions = {}\n): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new MethodError(error, response.status);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const parsedData = userSchema.parse(user);\n\n return Object.freeze({\n ...parsedData,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object;\n user: object;\n }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import 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 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) {\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 provider.init({\n channels: props?.channels,\n });\n setWebsocketClientProvider(provider);\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n"]}
@@ -0,0 +1,2 @@
1
+ export{l as author,i as bin,n as bugs,t as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,s as publishConfig,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-JBVRKV7T.js';//# sourceMappingURL=package-AQK4I5AP.js.map
2
+ //# sourceMappingURL=package-AQK4I5AP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-HU7WQD3O.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-AQK4I5AP.js"}
package/dist/server.d.ts CHANGED
@@ -530,11 +530,13 @@ declare function deleteUser(userId: ObjectId$1): Promise<void>;
530
530
  * @param options.bucket - The bucket for the rate limit.
531
531
  * @param options.type - The type of the rate limit.
532
532
  * @param options.value - The value for the rate limit.
533
+ * @param options.message - Optional custom error message when the rate limit is exceeded.
533
534
  */
534
535
  declare function consumeRateLimit(options: {
535
536
  bucket: string;
536
537
  type: RateLimitType;
537
538
  value: string;
539
+ message?: string;
538
540
  }): Promise<void>;
539
541
 
540
542
  /**