modelence 0.6.18 → 0.6.20
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-OEVRIT3I.js → chunk-433L4YFD.js} +3 -3
- package/dist/{chunk-OEVRIT3I.js.map → chunk-433L4YFD.js.map} +1 -1
- package/dist/{chunk-EY7KRL57.js → chunk-CDNHR3S5.js} +2 -2
- package/dist/chunk-CDNHR3S5.js.map +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{package-DSL4EF4B.js → package-W4YNP6NS.js} +2 -2
- package/dist/{package-DSL4EF4B.js.map → package-W4YNP6NS.js.map} +1 -1
- package/dist/server.d.ts +6 -492
- package/dist/server.js +7 -6
- package/dist/server.js.map +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/types-D6nwUab6.d.ts +543 -0
- package/dist/{types-CmI2APz9.d.ts → types-Ds1ESQSs.d.ts} +3 -1
- package/dist/types.d.ts +5 -27
- package/package.json +1 -1
- package/dist/chunk-EY7KRL57.js.map +0 -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-433L4YFD.js';import {Command}from'commander';import {readFileSync,promises,createWriteStream,writeFileSync}from'fs';import {fileURLToPath}from'url';import X,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import j from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import se from'archiver';import ee from'open';var C=".modelence.env";async function I(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 L(){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 R(e){return String(e).replace(/"/g,'\\"')}async function U(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 x(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await U(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(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}="${R(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 g=null,b=null;function J(){if(!g)throw new Error("Environment variables not loaded");return g}function S(){if(!b)throw new Error("Configuration not loaded");return b}function D(e){return `${J().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function w(){let{serverDir:e,serverEntry:o}=S();return join(e,o).replace(/\\/g,"/")}function O(){return S().postBuildCommand}function T(e){let o=N("build");return o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function N(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function h(){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");b=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await j.readFile(join(process.cwd(),".modelence.env"),"utf-8");g=parse(e);}catch(e){if(e.code==="ENOENT")g={};else throw e}}async function H(){let e=O();if(e){console.log("Running post-build command..."),execSync(e);return}await Q();}async function Q(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:X.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function Z(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[w()],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 E(){console.log("Building Modelence project...");try{let e=T();await j.rm(e,{recursive:!0,force:!0}),await Z(),await H(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await j.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function P(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 ee(r);let s=await ne(e,t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:s})),{token:s}}async function ne(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await re(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 re(e,o){let t=await fetch(`${e}/api/cli/token?code=${o}`,{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:r}=await t.json();return r}async function $(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||D("");await E(),await ae(r);let{token:i}=await P(s),{bundleName:a}=await ce(e.app,e.env,r,i,s);await promises.unlink(r),await le(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function ae(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=se("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,m)=>{o.on("close",n),o.on("error",m),t.on("error",m);});t.pipe(o);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server",join(".modelence","build"),".next"];for(let n of s)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.file(p(n),{name:n});for(let n of i)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.directory(p(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ce(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(),m=await promises.readFile(t),k=await fetch(a,{method:"PUT",body:new Uint8Array(m),headers:{"Content-Type":"application/zip"}});if(!k.ok)throw new Error(`Failed to upload bundle: ${k.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${n}`),{bundleName:n}}async function le(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=w(),o=X.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var he=fileURLToPath(import.meta.url),Ee=dirname(he),ve=JSON.parse(readFileSync(join(Ee,"../../package.json"),"utf-8")),u=new Command().name("modelence").description("Modelence CLI tool").version(ve.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 x(e);});u.command("build").description("Build the application").action(async()=>{await h(),await E();});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 h(),await $(e);});u.command("dev").description("Start development server").action(async()=>{await h(),B();});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.6.
|
|
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,g as n,h as o,x as p,j as q,b as r,v as s};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var s="module",i="modelence",r="0.6.20",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:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",x={"@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/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",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0"},j={"@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"},b={react:">=18.0.0","react-dom":">=18.0.0"},v={type:s,name:i,version:r,description:o,main:n,types:p,exports:c,files:d,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:x,dependencies:j,peerDependencies:b};
|
|
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,g as n,h as o,x as p,j as q,b as r,v as s};//# sourceMappingURL=chunk-433L4YFD.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-433L4YFD.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,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,QAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,mBACTC,CAAAA,CAAW,CACT,IAAK,iBAAA,CACL,UAAA,CAAY,mBACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,UAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,EAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,MAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,0DAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA,CAAO,+CACT,CAAA,CACAC,CAAAA,CAAY,wBACZC,CAAAA,CAAmB,CACjB,kBAAmB,QAAA,CACnB,eAAA,CAAiB,QAAA,CACjB,sBAAA,CAAwB,QAAA,CACxB,gBAAA,CAAkB,SAClB,iBAAA,CAAmB,SAAA,CACnB,aAAA,CAAe,SAAA,CACf,cAAA,CAAgB,SAAA,CAChB,mBAAoB,SAAA,CACpB,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-
|
|
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,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,QAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,mBACTC,CAAAA,CAAW,CACT,IAAK,iBAAA,CACL,UAAA,CAAY,mBACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,UAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,EAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,MAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,0DAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA,CAAO,+CACT,CAAA,CACAC,CAAAA,CAAY,wBACZC,CAAAA,CAAmB,CACjB,kBAAmB,QAAA,CACnB,eAAA,CAAiB,QAAA,CACjB,sBAAA,CAAwB,QAAA,CACxB,gBAAA,CAAkB,SAClB,iBAAA,CAAmB,SAAA,CACnB,aAAA,CAAe,SAAA,CACf,cAAA,CAAgB,SAAA,CAChB,mBAAoB,SAAA,CACpB,kBAAA,CAAoB,QAAA,CACpB,kCAAA,CAAoC,SAAA,CACpC,2BAAA,CAA6B,U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.20\",\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\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\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/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 \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\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"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import P from'elastic-apm-node';import A from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import u from'process';var m={},y={},v=false;function c(t){return y[t]?.value}function U(){if(!v)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(m).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:y[t]?.value??e.default}]))}function $(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!m[e]||(y[e]={key:e,type:o,value:r});}),v=true;}function F(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),m=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function L({elasticCloudId:t,elasticApiKey:e}){let o=u.stdout.write,r=u.stderr.write;u.stdout.write=function(n,...s){return x(n.toString(),i.stdout),o.call(u.stdout,n,...s)},u.stderr.write=function(n,...s){return x(n.toString(),i.stderr),r.call(u.stderr,n,...s)},h();}function x(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=z++),t[r]===`
|
|
2
|
-
`?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function R(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{E(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{b(o,{timestamp:r,source:"console",sequenceId:n});});}function h(){setTimeout(()=>{R(),h();},1e3);}var l=null;function V(){}function X(t){l=Object.assign({},l,t);}function I(){return l?.environmentId}function S(){return l?.appAlias}function T(){return l?.environmentAlias}function K(){return l?.telemetry?.serviceName}function a(){return !!l?.telemetry?.isEnabled}var j=false,p=null,C=null,ot=async()=>{if(j)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');j=true,a()&&await O();};async function O(){let t=c("_system.elastic.apmEndpoint"),e=c("_system.elastic.cloudId"),o=c("_system.elastic.apiKey"),r=S()??"unknown",n=T()??"unknown",s=I()??"unknown",f=K();p=P.start({serviceName:f,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let g=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});g.on("error",_=>{console.error("Elasticsearch Transport Error:",_);}),C=A.createLogger({level:"debug",defaultMeta:{serviceName:f},format:A.format.combine(A.format.json()),transports:[g]}),L({elasticCloudId:e,elasticApiKey:o});}function w(){if(!p)throw new Error("APM is not initialized");return p}function d(){if(!C)throw new Error("Logger is not initialized");return C}function M(){return c("_system.log.level")}function W(t,e){M()==="debug"&&(a()?d().debug(t,e):console.debug(t,e));}function E(t,e){["debug","info"].includes(M())&&(a()?d().info(t,e):console.info(t,e));}function b(t,e){a()?d().error(t,e):console.error(t,e);}function q(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let r=w(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:f,context:g}={})=>{g&&r.setCustomContext(g),n.end(s,f);},setContext:s=>{r.setCustomContext(s);}}}function D(t){if(!a()){console.error(t);return}w().captureError(t);}export{c as a,U as b,$ as c,F as d,V as e,X as f,ot as g,W as h,E as i,b as j,q as k,D as l};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
`?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function R(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{E(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{b(o,{timestamp:r,source:"console",sequenceId:n});});}function h(){setTimeout(()=>{R(),h();},1e3);}var l=null;function V(){}function X(t){l=Object.assign({},l,t);}function I(){return l?.environmentId}function S(){return l?.appAlias}function T(){return l?.environmentAlias}function K(){return l?.telemetry?.serviceName}function a(){return !!l?.telemetry?.isEnabled}var j=false,p=null,C=null,ot=async()=>{if(j)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');j=true,a()&&await O();};async function O(){let t=c("_system.elastic.apmEndpoint"),e=c("_system.elastic.cloudId"),o=c("_system.elastic.apiKey"),r=S()??"unknown",n=T()??"unknown",s=I()??"unknown",f=K();p=P.start({serviceName:f,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let g=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});g.on("error",_=>{console.error("Elasticsearch Transport Error:",_);}),C=A.createLogger({level:"debug",defaultMeta:{serviceName:f},format:A.format.combine(A.format.json()),transports:[g]}),L({elasticCloudId:e,elasticApiKey:o});}function w(){if(!p)throw new Error("APM is not initialized");return p}function d(){if(!C)throw new Error("Logger is not initialized");return C}function M(){return c("_system.log.level")}function W(t,e){M()==="debug"&&(a()?d().debug(t,e):console.debug(t,e));}function E(t,e){["debug","info"].includes(M())&&(a()?d().info(t,e):console.info(t,e));}function b(t,e){a()?d().error(t,e):console.error(t,e);}function q(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let r=w(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:f,context:g}={})=>{g&&r.setCustomContext(g),n.end(s,f);},setContext:s=>{r.setCustomContext(s);}}}function D(t){if(!a()){console.error(t);return}w().captureError(t);}export{c as a,U as b,$ as c,F as d,V as e,X as f,ot as g,W as h,E as i,b as j,q as k,D as l};//# sourceMappingURL=chunk-CDNHR3S5.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-CDNHR3S5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","getLogLevel","logDebug","message","startTransaction","name","context","transaction","result","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,CAAAA,CAAUC,CAAAA,CAAgB,CACxC,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAAA,CAGF,OAAO,MAAA,CAAO,YACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CACxB,OAAO,CAAC,CAACM,CAAAA,CAAGC,CAAM,IAAMA,CAAAA,CAAO,QAAQ,CAAA,CACvC,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKG,CAAM,IACT,CACLH,CAAAA,CACA,CACE,GAAA,CAAAA,EACA,IAAA,CAAMG,CAAAA,CAAO,IAAA,CACb,KAAA,CAAON,EAAOG,CAAG,CAAA,EAAG,KAAA,EAASG,CAAAA,CAAO,OACtC,CACF,CACD,CACL,CACF,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAAsB,CAChDA,CAAAA,CAAQ,OAAA,CAAQ,CAAC,CAAE,IAAAL,CAAAA,CAAK,IAAA,CAAAM,CAAAA,CAAM,KAAA,CAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBP,EAAI,WAAA,EAAY,CAAE,UAAA,CAAW,UAAU,GAEvC,CAACJ,CAAAA,CAAaI,CAAG,CAA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,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-CDNHR3S5.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key - The configuration key to retrieve\n * @returns The configuration value (string, number, or boolean)\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the site URL\n * const siteUrl = getConfig('_system.site.url');\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_URL=https://myapp.com\n * ```\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the current environment (e.g., 'development', 'staging', 'production')\n * const env = getConfig('_system.env');\n *\n * if (env === 'production') {\n * // Enable production features\n * }\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_ENV=production\n * ```\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport,\n ],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\nimport { getConfig } from '@/config/server';\n\nfunction getLogLevel() {\n return getConfig('_system.log.level') as 'debug' | 'info' | 'error';\n}\n\nexport function logDebug(message: string, args: object) {\n if (getLogLevel() === 'debug') {\n if (isTelemetryEnabled()) {\n getLogger().debug(message, args);\n } else {\n console.debug(message, args);\n }\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (['debug', 'info'].includes(getLogLevel())) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n } else {\n console.info(message, args);\n }\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n } else {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as ConfigKey, a as WebsocketClientProvider, c as ClientChannel } from './types-
|
|
1
|
+
import { b as ConfigKey, a as WebsocketClientProvider, c as ClientChannel } from './types-Ds1ESQSs.js';
|
|
2
2
|
import React from 'react';
|
|
3
3
|
import 'http';
|
|
4
4
|
import 'mongodb';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { C as ConfigSchema, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-
|
|
1
|
+
export { C as ConfigSchema, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-Ds1ESQSs.js';
|
|
2
2
|
export { M as ModelenceConfig } from './index-CwdohC5n.js';
|
|
3
3
|
import 'http';
|
|
4
4
|
import 'mongodb';
|
|
@@ -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-433L4YFD.js';//# sourceMappingURL=package-W4YNP6NS.js.map
|
|
2
|
+
//# sourceMappingURL=package-W4YNP6NS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-W4YNP6NS.js"}
|