modelence 0.10.5 → 0.10.6
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/dist/bin/modelence.js +1 -1
- package/dist/{chunk-A4DIEYUV.js → chunk-7GV4EONF.js} +3 -3
- package/dist/{chunk-A4DIEYUV.js.map → chunk-7GV4EONF.js.map} +1 -1
- package/dist/client.d.ts +5 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/{package-ZQMMK5LQ.js → package-QH2M7AMM.js} +2 -2
- package/dist/{package-ZQMMK5LQ.js.map → package-QH2M7AMM.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {s}from'../chunk-
|
|
2
|
+
import {s}from'../chunk-7GV4EONF.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
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
|
|
5
5
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",r="0.10.
|
|
2
|
-
export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var s="module",i="modelence",r="0.10.6",o="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./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"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="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={type:s,name:i,version:r,description:o,main:n,types:p,exports:c,files:d,bin:l,scripts:a,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:j,homepage:g,devDependencies:h,dependencies:x,peerDependencies:v};
|
|
2
|
+
export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-7GV4EONF.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-7GV4EONF.js.map
|
|
@@ -1 +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,SACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,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,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,EAAW,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,gBAClB,IAAA,CAAQ,6CAAA,CACR,YAAA,CAAc,qDAAA,CACd,eAAA,CAAiB,wDAAA,CACjB,YAAe,6BAAA,CACf,OAAA,CAAW,8CACb,CAAA,CAIAC,CAAAA,CAAc,CACZ,KAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC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AAAA,CAAoB,CAClB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,EAxGFC,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,CAAAA,CACA,QAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAcA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-
|
|
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,SACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,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,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP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,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,EACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,EAxGFC,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,CAAAA,CACA,QAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAcA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-7GV4EONF.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.10.6\",\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}\n"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -20,6 +20,10 @@ declare function renderApp({ loadingElement, routesElement, favicon, errorHandle
|
|
|
20
20
|
errorHandler?: ErrorHandler;
|
|
21
21
|
}): void;
|
|
22
22
|
|
|
23
|
+
declare class MethodError extends Error {
|
|
24
|
+
status: number;
|
|
25
|
+
constructor(message: string, status: number);
|
|
26
|
+
}
|
|
23
27
|
type MethodArgs = Record<string, unknown>;
|
|
24
28
|
type CallMethodOptions = {
|
|
25
29
|
errorHandler?: (error: Error, methodName: string) => void;
|
|
@@ -132,4 +136,4 @@ declare function getLocalStorageSession(): any;
|
|
|
132
136
|
|
|
133
137
|
declare const AppProvider: any;
|
|
134
138
|
|
|
135
|
-
export { AppProvider, ClientChannel, type MethodArgs, type UserInfo, callMethod, getConfig, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, useSession, verifyEmail };
|
|
139
|
+
export { AppProvider, ClientChannel, type MethodArgs, MethodError, type UserInfo, callMethod, getConfig, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, 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 $,{useState,useEffect}from'react';import {create}from'zustand';import {z}from'zod';import {jsx}from'react/jsx-runtime';import
|
|
1
|
+
import {b as b$1}from'./chunk-3S2FFBNS.js';import {a}from'./chunk-DO5TZLF5.js';import $,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import Z from'react-dom/client';import ae from'socket.io-client';function c(){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 P(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var T=(e,r)=>{console.error(`Error calling method '${r}':`,e);};function R(e){T=e;}function W(e,r){return T(e,r)}var h=class extends Error{constructor(r,t){super(r),this.name="MethodError",this.status=t;}};async function s(e,r={},t={}){try{return await q(`/api/_internal/method/${e}`,r)}catch(n){throw (t.errorHandler??W)(n,e),n}}async function q(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:c()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!t.ok){let i=await t.text();throw new h(i,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 D(e){return L[e]?.value}function A(e){L=e;}var w=create(e=>({user:null,setUser:r=>e({user:r})})),M=false,K=a.seconds(30);async function I(){if(M)return;M=true;let{configs:e,session:r,user:t}=await s("_system.session.init");A(e),P(r);let n=t?(()=>{let o=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string())}).parse(t);return Object.freeze({...o,hasRole:i=>o.roles.includes(i),requireRole:i=>{if(!o.roles.includes(i))throw new Error(`Access denied - role '${i}' required`)}})})():null;w.getState().setUser(n),await H();}async function H(){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(H,K);}function y(e){w.getState().setUser(e);}function V(){return {user:w(r=>r.user)}}var N=false;function b({children:e,loadingElement:r}){let[t,n]=useState(true);return useEffect(()=>{async function o(){N||(N=true,await I(),n(false));}o();},[]),t?r??jsx("div",{children:"Loading..."}):e}function ee({loadingElement:e,routesElement:r,favicon:t,errorHandler:n}){if(n&&R(n),window.addEventListener("unload",()=>{}),Z.createRoot(document.getElementById("root")).render(jsx($.StrictMode,{children:jsx(_,{loadingElement:e,children:r})})),t){let o=document.querySelector("link[rel~='icon']");if(o)o.href=t;else {let i=document.createElement("link");i.rel="icon",i.href=t,document.head.appendChild(i);}}}async function re(e){let{email:r,password:t}=e;await s("_system.user.signupWithPassword",{email:r,password:t});}async function te(e){let{email:r,password:t}=e,{user:n}=await s("_system.user.loginWithPassword",{email:r,password:t});return y(n),n}async function oe(e){let{token:r}=e;await s("_system.user.verifyEmail",{token:r});}async function ne(){await s("_system.user.logout"),y(null);}async function ie(e){let{email:r}=e;await s("_system.user.sendResetPasswordToken",{email:r});}async function se(e){let{token:r,password:t}=e;await s("_system.user.resetPassword",{token:r,password:t});}var d=null,u=new Map;function p(){if(!d)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return d}function ce(){for(let e of u.values())d?.emit("subscribeLiveQuery",{subscriptionId:e.subscriptionId,method:e.method,args:e.args});}function le(e){d=ae("/",{auth:{token:c()?.authToken}}),d.on("connect",()=>{u.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${u.size} live queries`),ce());}),e.channels?.forEach(r=>r.init());}function de({category:e,listener:r}){p().on(e,r);}function ue({category:e,listener:r}){p().once(e,r);}function pe({category:e,listener:r}){p().off(e,r);}function k({eventName:e,category:r,id:t}){p().emit(e,`${r}:${t}`);}function ge({category:e,id:r}){k({eventName:"joinChannel",category:e,id:r});}function fe({category:e,id:r}){k({eventName:"leaveChannel",category:e,id:r});}var me=0;function O(e,r,t,n){let o=`sub-${++me}-${Date.now()}`,i=({subscriptionId:v,data:f,typeMap:j})=>{v===o&&t(b$1(f,j));},x=({subscriptionId:v,error:f})=>{v===o&&(console.error(`[Modelence] Live query error for ${e}:`,f),n?.(f));},a=p();return a.on("liveQueryData",i),a.on("liveQueryError",x),u.set(o,{subscriptionId:o,method:e,args:r}),a.connected&&a.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:r}),()=>{u.delete(o),a.emit("unsubscribeLiveQuery",{subscriptionId:o}),a.off("liveQueryData",i),a.off("liveQueryError",x);}}var he={init:le,on:de,once:ue,off:pe,emit:k,joinChannel:ge,leaveChannel:fe},Q=he;var C=null;function z(e){C=e;}function g(){return C}function ve(e){if(C){console.warn("WebSocket already initialized. Skipping initialization.");return}let r=e?.provider||Q;r.init({channels:e?.channels}),z(r);}var S=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 _="useClient"in $?$.useClient(b):b;export{_ as AppProvider,S as ClientChannel,h as MethodError,s as callMethod,D as getConfig,c as getLocalStorageSession,g as getWebsocketClientProvider,te as loginWithPassword,ne as logout,ee as renderApp,se as resetPassword,ie as sendResetPasswordToken,z as setWebsocketClientProvider,re as signupWithPassword,ve as startWebsockets,O as subscribeLiveQuery,V as useSession,oe as verifyEmail};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.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/auth/client/index.ts","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","options","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","parsedData","z","role","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","verifyEmail","token","logout","sendResetPasswordToken","resetPassword","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","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":"8QAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CA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"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","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\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 { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\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: getLocalStorageSession()?.authToken,\n clientInfo: {\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,\n },\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\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\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 const parsedUser = user\n ? (() => {\n const parsedData = z\n .object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n })\n .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 : null;\n\n useSessionStore.getState().setUser(parsedUser);\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: User | null) {\n useSessionStore.getState().setUser(user);\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 { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\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\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: UserInfo }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n setCurrentUser(user);\n return user;\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: UserInfo }>('_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","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getLocalStorageSession } from '@/client/localStorage';\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 for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n socketClient = io('/', {\n auth: {\n token: getLocalStorageSession()?.authToken,\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', { subscriptionId, method, args });\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, 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/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","callMethod","args","options","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","parsedData","z","role","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","verifyEmail","token","logout","sendResetPasswordToken","resetPassword","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","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":"qRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,EAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACtD,YAAA,CAAa,QAAQ,mBAAA,CAAqB,IAAA,CAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCVA,IAAIC,EAA6B,CAACC,CAAAA,CAAOC,C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A,CAAQD,EAAAA,CCnKf,IAAIE,EAA0D,IAAA,CAEvD,SAASC,CAAAA,CAA2BC,CAAAA,CAAmC,CAC5EF,CAAAA,CAA0BE,EAC5B,CAEO,SAASC,CAAAA,EAA6B,CAC3C,OAAOH,CACT,CAEO,SAASI,EAAAA,CAAgB9B,CAAAA,CAG7B,CACD,GAAI0B,CAAAA,CAAyB,CAC3B,OAAA,CAAQ,IAAA,CAAK,yDAAyD,CAAA,CACtE,MACF,CAEA,IAAME,CAAAA,CAAW5B,CAAAA,EAAO,QAAA,EAAYyB,EACpCG,CAAAA,CAAS,IAAA,CAAK,CACZ,QAAA,CAAU5B,GAAO,QACnB,CAAC,CAAA,CACD2B,CAAAA,CAA2BC,CAAQ,EACrC,CC5BO,IAAMG,EAAN,KAAiC,CAItC,WAAA,CAAY3B,CAAAA,CAAkB4B,CAAAA,CAA8B,CAC1D,IAAA,CAAK,QAAA,CAAW5B,EAChB,IAAA,CAAK,SAAA,CAAY4B,EACnB,CAEA,IAAA,EAAO,CACLH,CAAAA,EAA2B,EAAG,GAAG,CAC/B,QAAA,CAAU,IAAA,CAAK,QAAA,CACf,SAAU,IAAA,CAAK,SACjB,CAAC,EACH,CAEA,WAAA,CAAYnB,CAAAA,CAAY,CACtBmB,CAAAA,EAA2B,EAAG,WAAA,CAAY,CACxC,QAAA,CAAU,KAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CAEA,YAAA,CAAaA,CAAAA,CAAY,CACvBmB,GAA2B,EAAG,YAAA,CAAa,CACzC,QAAA,CAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CACF,ECzBO,IAAMzC,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","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 { getLocalStorageSession } from './localStorage';\nimport { handleError } from './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: getLocalStorageSession()?.authToken,\n clientInfo: {\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,\n },\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\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 const parsedUser = user\n ? (() => {\n const parsedData = z\n .object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n })\n .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 : null;\n\n useSessionStore.getState().setUser(parsedUser);\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: User | null) {\n useSessionStore.getState().setUser(user);\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 { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\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\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: UserInfo }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n setCurrentUser(user);\n return user;\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: UserInfo }>('_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","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getLocalStorageSession } from '@/client/localStorage';\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 for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n socketClient = io('/', {\n auth: {\n token: getLocalStorageSession()?.authToken,\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', { subscriptionId, method, args });\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,2 +1,2 @@
|
|
|
1
|
-
export{l as author,i as bin,n as bugs,s 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,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=package-
|
|
1
|
+
export{l as author,i as bin,n as bugs,s 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,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-7GV4EONF.js';//# sourceMappingURL=package-QH2M7AMM.js.map
|
|
2
|
+
//# sourceMappingURL=package-QH2M7AMM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-QH2M7AMM.js"}
|
package/dist/server.js
CHANGED
|
@@ -14,6 +14,6 @@ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d as d$1,a as a$3}from'./chun
|
|
|
14
14
|
`}var Te={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function St(t,{connectionInfo:e}){let o=q(t.email),r=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r||!r.authMethods?.password)return Te;let n=b().provider;if(!n)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=Date.now(),a$1=new Date(s),c=new Date(s+a.hours(1));await v.insertOne({userId:r._id,token:i,createdAt:a$1,expiresAt:c});let l=process.env.MODELENCE_SITE_URL||e?.baseUrl,m=`${Mo(l,b().passwordReset?.redirectUrl)}?token=${i}`,x=(b()?.passwordReset?.template||Io)({email:o,resetUrl:m,name:""}),M=ne(x);return await n.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:M,html:x}),Te}async function Ct(t,{}){let e=z$1.string().parse(t.token),o=ce(t.password),r=await v.findOne({token:e});if(!r)throw new Error("Invalid or expired reset token");if(r.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let n=await p.findOne({_id:r.userId});if(!n)throw new Error("User not found");let i=await vo.hash(o,10);return await p.updateOne({_id:n._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var xt=new E("_system.user",{stores:[p,J,k,v],queries:{getOwnProfile:wt},mutations:{signupWithPassword:Et,loginWithPassword:gt,logout:yt,sendResetPasswordToken:St,resetPassword:Ct},cronJobs:{updateDisposableEmailList:lt},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:mt}}]});async function vt({configSchema:t,cronJobsMetadata:e,stores:o}){let r=process.env.MODELENCE_CONTAINER_ID;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await De("/api/connect","POST",{hostname:Lo.hostname(),containerId:r,dataModels:n,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function Tt(){return await De("/api/configs","GET")}async function Dt(){return await De("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function De(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var ke=false,Po=a.seconds(10);function kt(){setInterval(async()=>{if(!ke){ke=true;try{await Dt();}catch(t){console.error("Error syncing status",t);}try{await Uo();}catch(t){console.error("Error syncing config",t);}ke=false;}},Po);}async function Uo(){let{configs:t}=await Tt();c(t);}var K=new w("_modelenceLocks",{schema:{resource:d.string(),instanceId:d.string(),acquiredAt:d.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var W={},_t=a.seconds(10),At=randomBytes(32).toString("base64url"),$o=a.seconds(30);async function le(t,{lockDuration:e=$o,successfulLockCacheDuration:o=_t,failedLockCacheDuration:r=_t,instanceId:n=At}={}){let i=Date.now();if(W[t]&&i<W[t].expiresAt)return W[t].value;let s=new Date(i-e);h$1(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:n});try{let a=await K.upsertOne({$or:[{resource:t,instanceId:n},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:n,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return W[t]={value:c,expiresAt:i+(c?o:r)},c?h$1(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:n}):h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),c}catch{return W[t]={value:false,expiresAt:i+r},h$1(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:n}),false}}async function Ot(t,{instanceId:e=At}={}){let o=await K.deleteOne({resource:t,instanceId:e});return delete W[t],o.deletedCount>0}var No=a.minutes(1),$={},_e=null,Ae=new w("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Mt(t,{description:e="",interval:o,timeout:r=No,handler:n}){if($[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(_e)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(r>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);$[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function It(){if(_e)throw new Error("Cron jobs already started");let t=Object.keys($);if(t.length>0){let e={alias:{$in:t}},o=await Ae.fetch(e),r=Date.now();o.forEach(n=>{let i=$[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values($).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),_e=setInterval(zo,a.seconds(1));}}async function zo(){let t=Date.now();await le("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values($).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Fo(o);});}async function Fo(t){let{alias:e,params:o,handler:r,state:n}=t;n.isRunning=true,n.startTs=Date.now(),await Ae.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});let i=k$1("cron",`cron:${e}`);try{await r(),Rt(n,o),i.end("success");}catch(s){Rt(n,o);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function Rt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Lt(){return Object.values($).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Pt=new E("_system.cron",{stores:[Ae]});var Oe=new E("_system.lock",{stores:[K]});var Y=new w("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function qo(t){if(t.length===0)return;if(!await le("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),r=await Y.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!n.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let f=(await c()||"").toString().trim(),m=15*1024*1024,S=f.length>m?f.slice(0,m)+`
|
|
15
15
|
[Output truncated - exceeded size limit]`:f;await Y.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:S,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await Y.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}await Ot("migrations");}}function Ut(t){setTimeout(()=>{qo(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var jt=new E("_system.migration",{stores:[Y]});var $t=new E("_system.rateLimit",{stores:[H]});var Nt=new E("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var Me=class{async init(){this.config=await Ko(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[R.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(R.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(r){console.error("Error serving index.html:",r),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Qo(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function Ho(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Ko(){let t=process.cwd(),e=await Qo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Go.existsSync(Re.join(t,i))),r=[Jo(),Yo()];if(o){let i=(await import('vite-plugin-eslint')).default;r.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Re.resolve(t,o)}));}let n=defineConfig({plugins:r,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Re.resolve(t,"src").replace(/\\/g,"/")}}});return Ho(n,e)}function Yo(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t}}}var Ft=new Me;async function qt(t,e){let{authToken:o}=await ge(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function Z(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function de(t,e,o){let r=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await Ie(t);try{if(r){await qt(e,r._id),h().onAfterLogin?.({provider:o.providerName,user:r,session:n,connectionInfo:i}),h().login?.onSuccess?.(r);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({provider:o.providerName,error:s,session:n,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await qt(e,a.insertedId);let c=await p.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(h().onAfterSignup?.({provider:o.providerName,user:c,session:n,connectionInfo:i}),h().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(h().onSignupError?.({provider:o.providerName,error:s,session:n,connectionInfo:i}),h().signup?.onError?.(s)),s}}function ue(t){return !t||typeof t!="string"?null:t}async function tr(t,e,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function or(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function rr(t,e){let o=ue(t.query.code),r=t.query.state,n=t.cookies.authStateGoogle;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!r||!n||r!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGoogle");let i=String(a$1("_system.user.auth.google.clientId")),s=String(a$1("_system.user.auth.google.clientSecret")),a=Z("google");try{let c=await tr(o,i,s,a),l=await or(c.access_token),f={id:l.id,email:l.email,emailVerified:l.verified_email,providerName:"google"};await de(t,e,f);}catch(c){console.error("Google OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function nr(){let t=Router(),e=(o,r,n)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){r.status(503).json({error:"Google authentication is not configured"});return}n();};return t.get("/api/_internal/auth/google",e,(o,r)=>{let n=String(a$1("_system.user.auth.google.clientId")),i=Z("google"),s=randomBytes(32).toString("hex");r.cookie("authStateGoogle",s,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let a$2=new URL("https://accounts.google.com/o/oauth2/v2/auth");a$2.searchParams.append("client_id",n),a$2.searchParams.append("redirect_uri",i),a$2.searchParams.append("response_type","code"),a$2.searchParams.append("scope","profile email"),a$2.searchParams.append("access_type","online"),a$2.searchParams.append("state",s),r.redirect(a$2.toString());}),t.get("/api/_internal/auth/google/callback",e,rr),t}var Wt=nr;async function ar(t,e,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function cr(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function lr(t,e){let o=ue(t.query.code),r=t.query.state,n=t.cookies.authStateGithub;if(!o){e.status(400).json({error:"Missing authorization code"});return}if(!r||!n||r!==n){e.status(400).json({error:"Invalid OAuth state - possible CSRF attack"});return}e.clearCookie("authStateGithub");let i=String(a$1("_system.user.auth.github.clientId")),s=String(a$1("_system.user.auth.github.clientSecret")),a=Z("github");try{let c=await ar(o,i,s,a),l=await cr(c.access_token),f=l.email||"";if(!f){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let m={id:String(l.id),email:f,emailVerified:!0,providerName:"github"};await de(t,e,m);}catch(c){console.error("GitHub OAuth error:",c),e.status(500).json({error:"Authentication failed"});}}function dr(){let t=Router(),e=(o,r,n)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){r.status(503).json({error:"GitHub authentication is not configured"});return}n();};return t.get("/api/_internal/auth/github",e,(o,r)=>{let n=String(a$1("_system.user.auth.github.clientId")),i=Z("github"),s=a$1("_system.user.auth.github.scopes"),a$2=s?String(s).split(",").map(f=>f.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex");r.cookie("authStateGithub",c,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a.minutes(10)});let l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",n),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a$2),l.searchParams.append("state",c),r.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,lr),t}var Zt=dr;function Bt(t,e,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&P())try{let{session:l,user:f}=await L(s);a={session:l,user:f};}catch{}let c=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:r.query,body:r.body,params:r.params});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.redirect&&n.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([f,m])=>{n.setHeader(f,m);}),n.send(l.data));}catch(l){c.end("error"),l instanceof a$3?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}var Le=Object.freeze({});function Vt(t){Le=Object.freeze(Object.assign({},Le,t));}function pe(){return Le}function mr(t){let e=[];if(!t)return e.push(R.json({limit:"16mb"})),e.push(R.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(R.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(R.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(R.raw(r));}return e}function fr(t,e){for(let o of e)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=mr(s);Object.entries(i).forEach(([c,l])=>{t[c](n,...a,Bt(c,n,l));});}}async function Jt(t,{combinedModules:e,channels:o}){let r=R();r.use(ur()),fr(r,e),r.use(R.json({limit:"16mb"})),r.use(R.urlencoded({extended:true,limit:"16mb"})),r.use(Wt()),r.use(Zt()),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:l}=a.params,f=await Ie(a);try{let m=await it(l,a.body.args,f);c.json({data:m,typeMap:a$2(m)});}catch(m){hr(c,l,m);}}),await t.init(),t.middlewares&&r.use(t.middlewares()),r.all("*",(a,c)=>t.handler(a,c)),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=pr.createServer(r),i$1=pe()?.provider;i$1&&i$1.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
|
|
16
16
|
Application started on ${a}
|
|
17
|
-
`);});}async function Ie(t){let e=O.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=O.object({screenWidth:O.number(),screenHeight:O.number(),windowWidth:O.number(),windowHeight:O.number(),pixelRatio:O.number(),orientation:O.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},r={ip:gr(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!P()){let{session:i,user:s,roles:a}=await L(e);return {clientInfo:o,connectionInfo:r,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:oe()}}function hr(t,e,o){if(console.error(`Error in method ${e}:`,o),o instanceof a$3)t.status(o.status).send(o.message);else if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let n=o.flatten(),i=Object.entries(n.fieldErrors).map(([c,l])=>`${c}: ${(l??[]).join(", ")}`).join("; "),s=n.formErrors.join("; "),a=[i,s].filter(Boolean).join("; ");t.status(400).send(a);}else t.status(500).send(o instanceof Error?o.message:String(o));}function gr(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function Er({modules:t=[],roles:e$1={},defaultRoles:o={},server:r=Ft,migrations:n=[],email:i={},auth:s={},websocket:a={}}){Gt.config(),Gt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";Mr().then(()=>{}).catch(()=>{});let f$1=[xt,Qe,Pt,jt,$t,Nt,Oe],m=[...f$1,...t];e(),Cr(f$1),Sr(t),Ke(e$1,o);let S=Dr(m);d$2(S);let x=xr(m),M=vr(m);l&&kr(m);let C=Tr(m);if(bt(C),c$1){let{configs:me,environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt}=await vt({configSchema:S,cronJobsMetadata:l?Lt():void 0,stores:x});c(me),f({environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt});}else c(Rr(S));dt(i),pt(s),Vt({...a,provider:a.provider||at});let Ue=P();if(Ue&&(await Xe(),_r(x)),l&&Ut(n),Ue)for(let me of x)me.createIndexes();c$1&&(await g(),kt()),l&&It().catch(console.error),await Jt(r,{combinedModules:m,channels:M});}function Sr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))we(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))et(`${e.name}.${o}`,r);}}function Cr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))tt(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))ot(`${e.name}.${o}`,r);}}function xr(t){return t.flatMap(e=>e.stores)}function vr(t){return t.flatMap(e=>e.channels)}function Tr(t){return t.flatMap(e=>e.rateLimits)}function Dr(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=n;}return e}function kr(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))Mt(`${e.name}.${o}`,r);}function _r(t){let e=re();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ar={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Or(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Rr(t){let e=[];for(let[o,r]of Object.entries(Ar)){let n=process.env[o],i=t[r];if(n){let s=i?.type??"string";e.push({key:r,type:s,value:Or(n,s)});}}return e}async function Mr(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Ir(),n=await import('./package-
|
|
17
|
+
`);});}async function Ie(t){let e=O.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=O.object({screenWidth:O.number(),screenHeight:O.number(),windowWidth:O.number(),windowHeight:O.number(),pixelRatio:O.number(),orientation:O.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},r={ip:gr(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!P()){let{session:i,user:s,roles:a}=await L(e);return {clientInfo:o,connectionInfo:r,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:oe()}}function hr(t,e,o){if(console.error(`Error in method ${e}:`,o),o instanceof a$3)t.status(o.status).send(o.message);else if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let n=o.flatten(),i=Object.entries(n.fieldErrors).map(([c,l])=>`${c}: ${(l??[]).join(", ")}`).join("; "),s=n.formErrors.join("; "),a=[i,s].filter(Boolean).join("; ");t.status(400).send(a);}else t.status(500).send(o instanceof Error?o.message:String(o));}function gr(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function Er({modules:t=[],roles:e$1={},defaultRoles:o={},server:r=Ft,migrations:n=[],email:i={},auth:s={},websocket:a={}}){Gt.config(),Gt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";Mr().then(()=>{}).catch(()=>{});let f$1=[xt,Qe,Pt,jt,$t,Nt,Oe],m=[...f$1,...t];e(),Cr(f$1),Sr(t),Ke(e$1,o);let S=Dr(m);d$2(S);let x=xr(m),M=vr(m);l&&kr(m);let C=Tr(m);if(bt(C),c$1){let{configs:me,environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt}=await vt({configSchema:S,cronJobsMetadata:l?Lt():void 0,stores:x});c(me),f({environmentId:Ht,appAlias:Kt,environmentAlias:Yt,telemetry:Xt});}else c(Rr(S));dt(i),pt(s),Vt({...a,provider:a.provider||at});let Ue=P();if(Ue&&(await Xe(),_r(x)),l&&Ut(n),Ue)for(let me of x)me.createIndexes();c$1&&(await g(),kt()),l&&It().catch(console.error),await Jt(r,{combinedModules:m,channels:M});}function Sr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))we(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))et(`${e.name}.${o}`,r);}}function Cr(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))tt(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))ot(`${e.name}.${o}`,r);}}function xr(t){return t.flatMap(e=>e.stores)}function vr(t){return t.flatMap(e=>e.channels)}function Tr(t){return t.flatMap(e=>e.rateLimits)}function Dr(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=n;}return e}function kr(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))Mt(`${e.name}.${o}`,r);}function _r(t){let e=re();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ar={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Or(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Rr(t){let e=[];for(let[o,r]of Object.entries(Ar)){let n=process.env[o],i=t[r];if(n){let s=i?.type??"string";e.push({key:r,type:s,value:Or(n,s)});}}return e}async function Mr(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Ir(),n=await import('./package-QH2M7AMM.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Lo.hostname(),environmentId:o})});}}async function Ir(){try{let t=Re.join(process.cwd(),"package.json"),e=await yr.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Qt(t){await k.deleteMany({userId:t}),await v.deleteMany({userId:t});}async function Pr(t){await Qt(t),await p.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function Ur(t){await Qt(t),await p.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Pe=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let r=pe().provider;if(!r){j$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:e,data:o});}};function jr(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
|
|
18
18
|
export{F as LiveData,E as Module,Pe as ServerChannel,w as Store,L as authenticate,j as consumeRateLimit,we as createQuery,p as dbUsers,Ur as deleteUser,Pr as disableUser,d as schema,jr as sendEmail,Er as startApp};//# sourceMappingURL=server.js.map
|
|
19
19
|
//# sourceMappingURL=server.js.map
|