@lensmcp/cluster 1.20.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/basic-ssl.js +1 -1
- package/build-scope-patterns.js +1 -1
- package/create-webpack-dev.js +1 -1
- package/create-webpack-prod.js +1 -1
- package/executors/build/build.impl.js +1 -1
- package/executors/gateway/gateway-errors.js +1 -1
- package/executors/gateway/gateway.impl.js +1 -1
- package/executors/gateway/gateway.lib.js +1 -1
- package/executors/gateway/health-check.js +1 -1
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/main.prod-gateway.js +2 -2
- package/executors/gateway/main.rollout.js +4 -4
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/metrics.js +1 -1
- package/executors/gateway/otel-tracing.js +1 -1
- package/executors/gateway/prod-gateway.lib.js +1 -1
- package/executors/gateway/prod-runtime/access-log.js +1 -1
- package/executors/gateway/prod-runtime/app.js +1 -1
- package/executors/gateway/prod-runtime/auth.js +1 -1
- package/executors/gateway/prod-runtime/cors.js +1 -1
- package/executors/gateway/prod-runtime/edge.js +1 -1
- package/executors/gateway/prod-runtime/handler.js +1 -1
- package/executors/gateway/prod-runtime/hooks.js +1 -1
- package/executors/gateway/prod-runtime/observability.js +1 -1
- package/executors/gateway/prod-runtime/rollout.js +1 -1
- package/executors/gateway/prod-runtime/routing.js +1 -1
- package/executors/gateway/prod-runtime/server.js +1 -1
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/prod-runtime/upgrade.js +2 -2
- package/executors/gateway/prod-runtime/upstream.js +1 -1
- package/executors/gateway/providers-prod.js +1 -1
- package/executors/gateway/rate-limit.js +2 -2
- package/executors/gateway/registry-source.js +1 -1
- package/executors/gateway/rollout-ops.js +2 -2
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/chooser.js +7 -7
- package/executors/gateway/runtime/control.js +1 -1
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/hmr-reload.js +1 -1
- package/executors/gateway/runtime/hooks.js +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.js +3 -3
- package/executors/gateway/runtime/observability.js +2 -2
- package/executors/gateway/runtime/pod-env.js +2 -2
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/scope.js +1 -1
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/service-keys.js +1 -1
- package/executors/gateway/runtime/types.js +1 -1
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/workspace-registry.js +1 -1
- package/executors/gateway/ssrf-guard.js +1 -1
- package/executors/serve/serve.impl.js +1 -1
- package/executors/trust/trust.impl.js +3 -3
- package/gateway.js +1 -1
- package/index.js +1 -1
- package/main.devserver.js +5 -5
- package/package.json +4 -4
- package/tsgo-check-plugin.js +4 -4
- package/typecheck-bus.js +3 -3
package/main.devserver.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}}const u=a(i=>d[(i-1)%d.length],"colorFor"),
|
|
3
|
-
`+String($),"stack")}}),A=a(($,T)=>{const
|
|
4
|
-
`;
|
|
1
|
+
"use strict";var pe=Object.defineProperty;var h=(o,d)=>pe(o,"name",{value:d,configurable:!0});var ie=Object.defineProperty,a=h((o,d)=>ie(o,"name",{value:d,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),node_child_process_1=require("node:child_process"),http=tslib_1.__importStar(require("node:http")),readline=tslib_1.__importStar(require("node:readline")),inspector=tslib_1.__importStar(require("node:inspector")),util=tslib_1.__importStar(require("node:util")),httpProxy=require("http-proxy"),{prettyFactory}=require("pino-pretty"),BUNDLE_PATH=process.env.BUNDLE_PATH?.trim()||"./main.js",SERVICE_NAME=process.env.SERVICE_NAME||"",SERVICE_PREFIX=process.env.SERVE_PREFIX?`/${process.env.SERVE_PREFIX}`:"",GATEWAY_MIDDLEWARE_PATH=process.env.GATEWAY_MIDDLEWARE||"",GATEWAY_CONFIG=(()=>{const o=process.env.GATEWAY_CONFIG;if(!o)return{};try{return JSON.parse(o)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const o=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof o=="function"?o:typeof o.default=="function"?o.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(o){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,o)}function applyGatewayMiddleware(o){if(gatewayMiddleware)try{gatewayMiddleware(o,GATEWAY_CONFIG)}catch(d){console.error("[gateway] Middleware error:",d)}}h(applyGatewayMiddleware,"applyGatewayMiddleware"),a(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(o,d){if(o.startsWith("*.")){const g=o.slice(1);return d.endsWith(g)||d===o.slice(2)}return d===o}h(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchGatewayRoute(o){if(GATEWAY_ROUTES.length===0)return;const d=(o.headers.host||"").split(":")[0],g=o.url||"/";for(const f of GATEWAY_ROUTES)if(!(f.host&&!hostMatches(f.host,d))&&!(f.prefix&&!g.startsWith(f.prefix)))return f}h(matchGatewayRoute,"matchGatewayRoute"),a(matchGatewayRoute,"matchGatewayRoute");const WORKER_NAMES=(()=>{try{return JSON.parse(process.env.WORKERS||"[]")}catch{return[]}})(),LENSMCP_WS_KEY=process.env.LENSMCP_WS_KEY||"",SOCK_DIR=LENSMCP_WS_KEY?path.join(os.tmpdir(),LENSMCP_WS_KEY,`${SERVICE_NAME||"lensmcp-cluster"}-devserver`):path.join(os.tmpdir(),`${SERVICE_NAME||"lensmcp-cluster"}-devserver`);function childSockPath(o){return path.join(SOCK_DIR,`child-${o}.sock`)}h(childSockPath,"childSockPath"),a(childSockPath,"childSockPath");function sockOwnerPath(o){return`${o}.owner`}h(sockOwnerPath,"sockOwnerPath"),a(sockOwnerPath,"sockOwnerPath");function claimSock(o,d=process.pid){try{fs.mkdirSync(path.dirname(o),{recursive:!0})}catch{}try{fs.writeFileSync(sockOwnerPath(o),String(d))}catch{}try{fs.unlinkSync(o)}catch{}}h(claimSock,"claimSock"),a(claimSock,"claimSock");function cleanupSock(o,d=process.pid){if(o){try{const g=fs.readFileSync(sockOwnerPath(o),"utf8").trim();if(g&&g!==String(d))return}catch{}try{fs.unlinkSync(o)}catch{}try{fs.unlinkSync(sockOwnerPath(o))}catch{}}}h(cleanupSock,"cleanupSock"),a(cleanupSock,"cleanupSock");async function importFresh(spec){process.env.DEVSERVER_MODE="1";const resolved=path.isAbsolute(spec)?spec:path.join(__dirname,spec);return eval(`delete require.cache["${resolved}"]`),eval(`require("${resolved}")`)}h(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(o,d){let g=null;return(...f)=>{g&&clearTimeout(g),g=setTimeout(()=>o(...f),d)}}if(h(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){const o=a(g=>{if(!inspector.url())try{inspector.open(g,"127.0.0.1",!1)}catch(m){console.warn(`[child] inspector.open(${g}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,m.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const f=inspector.url();f&&process.send&&process.send({type:"inspector-url",url:f})},"openInspector"),d=Number(process.env.CHILD_DEBUG_PORT||"");Number.isInteger(d)&&d>1024&&o(d);try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let g=null,f=!1,m=!1,H=a((p,u)=>{u.statusCode=503,u.end("starting")},"delegate");async function P(){if(f)return m=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),g;if(f=!0,process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(w,k)=>{console.error(`[child] uncaughtException (${k}):`,w)}),process.on("unhandledRejection",w=>{const k=w instanceof Error?w.stack||w.message:String(w);k.includes("FronteggContextScope")||k.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",w)}),await importFresh(BUNDLE_PATH),typeof global.createChildApp!="function")throw f=!1,new Error(`Bundle '${BUNDLE_PATH}' does not export createChildApp() and the zero-touch bridge is not active. Either install @lensmcp/node-instrumentation (a plain NestFactory.create + app.listen main.ts then just works) or set global.createChildApp in main.ts when DEVSERVER_MODE === '1'.`);const p=await global.createChildApp(),u=g;return g=p,H=p.handler,console.log("[child] Swapped to fresh app (previous closing in background)"),u&&u.close().catch(w=>console.error("[child] background close error:",w)),f=!1,m?(m=!1,P()):p}h(P,"I"),a(P,"swapNow");const B=debounce(async()=>{try{console.log("[child] /webpack/reload"),await P()}catch(p){console.error("[child] reload failed:",p)}},250),C=http.createServer((p,u)=>{if(p.method==="POST"&&p.url==="/webpack/reload"){u.writeHead(200,{"content-type":"application/json"}),u.end(JSON.stringify({ok:!0})),B();return}H(p,u)}),_=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(_),process.exit(0)});try{await P();const p=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);console.log(`[child] Using bundle: ${p}`),claimSock(_),C.listen(_,()=>{console.log(`[child] Listening on ${_}`),process.send&&process.send({type:"ready",socketPath:_})})}catch(p){console.error("[child] Startup error:",p),process.send&&process.send({type:"boot-error",error:String(p?.stack||p)}),process.exitCode=1;return}process.on("message",async p=>{if(!(!p||typeof p!="object")){if(p.type==="debug-open"){const u=Number(p.port);o(Number.isInteger(u)&&u>1024?u:0);return}if(p.type==="reload")try{await P(),process.send&&process.send({type:"reloaded",socketPath:_})}catch(u){console.error("[child] reload error:",u),process.send&&process.send({type:"reload-error",error:String(u?.stack||u)})}}}),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const x=a(async p=>{console.log(`[child ${p}] shutting down\u2026`);const u=g?.close().catch(k=>console.error("[child] close error:",k)),w=new Promise(k=>C.close(()=>k()));cleanupSock(_),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([u,w]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(p=>{process.on(p,()=>{inspector?.close?.(),x(p)})})})()}else{let o=h(function(i){x.push(i),x.length>_&&x.splice(0,x.length-_),B?.write(i.replace(C,""));for(const y of p)try{y.res.write(y.plain?i.replace(C,""):i)}catch{p.delete(y)}},"p");a(o,"emitLogLine");const d=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],g="\x1B[0m",f=Math.max(1,Number(process.env.CHILD_COUNT||1));let m=(()=>{const i=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(i)&&i>1024?i:0})();const H=20,P=process.env.LENSMCP_LOG_FILE||"",B=P?(()=>{try{return fs.mkdirSync(path.dirname(P),{recursive:!0}),fs.createWriteStream(P,{flags:"a"})}catch(i){return console.warn(`[parent] cannot open log file ${P}:`,i.message),null}})():null,C=/\x1b\[[0-9;]*m/g,_=2e3,x=[],p=new Set;for(const i of["log","info","warn","error"]){const y=console[i].bind(console);console[i]=(...E)=>{y(...E),o(E.map(A=>typeof A=="string"?A:util.inspect(A)).join(" ")+`
|
|
2
|
+
`)}}const u=a(i=>d[(i-1)%d.length],"colorFor"),w=a(i=>{if(f===1)return"";const y=`[child#${i}] `;return`${u(i)}${y}${g}`},"tagFor"),k=a(i=>i.startsWith("{")&&i.endsWith("}"),"isJsonLog"),Z=a((i,y)=>{const E=prettyFactory({sync:!0,colorize:!0,crlf:!0,messageKey:"message",errorLikeObjectKeys:["err","error"],errorProps:"type,message,stack",ignore:["logContext","context","hostname","req","res","err.driverError","module","cloudEnvironment","frontegg-application-id","frontegg-tenant-id","frontegg-trace-id","frontegg-vendor-id","host","service","version","err","error"].join(","),messageFormat:"{if module}[{module}] {end}{if context}[{context}] {end}{if logContext}[{logContext}] {end}{message}",customPrettifiers:{stack:a($=>`
|
|
3
|
+
`+String($),"stack")}}),A=a(($,T)=>{const v=$==="stdout"?process.stdout:process.stderr,b=k(T)?E(T):`${T}
|
|
4
|
+
`;v.write(`${y}${b}`),o(`${y}${b}`)},"write"),G=a(($,T)=>{if(!$)return;const v=readline.createInterface({input:$});v.on("line",b=>A(T,b)),v.on("close",()=>{})},"attach");G(i.stdout,"stdout"),G(i.stderr,"stderr")},"wireProcLogging"),se=a(i=>Z(i.proc,w(i.id)),"wireChildLogging");(async()=>{fs.mkdirSync(SOCK_DIR,{recursive:!0});const i=httpProxy.createProxyServer({});let y=Number(process.env.PORT)||0;y||(y=9090);const E=[],A=new Set;function G(){let e=0;for(;A.has(e);)e++;return A.add(e),e}h(G,"G"),a(G,"allocDebugSlot");let $=1,T=0,v=!1,b=f,O=[];function K(){return E.filter(e=>e.healthy&&typeof e.socketPath=="string")}h(K,"Q"),a(K,"healthyChildren");function M(){const e=K();if(e.length===0)return null;const t=T%e.length;return T=(T+1)%e.length,e[t]}h(M,"U"),a(M,"pickChild");async function U(){const e=$++,t=childSockPath(e);cleanupSock(t);const l=["--enable-source-maps"];__filename.endsWith(".ts")&&l.unshift("--require","@swc-node/register");const n=m?G():-1,c=(0,node_child_process_1.fork)(__filename,{env:{...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...n>=0&&{CHILD_DEBUG_PORT:String(m+n)}},stdio:["inherit","pipe","pipe","ipc"],execArgv:l}),r={id:e,proc:c,healthy:!1,lastError:null,debugSlot:n};return c.on("message",S=>{if(!S||typeof S!="object")return;const s=S;s.type==="ready"?(r.socketPath=String(s.socketPath),r.healthy=!0,console.log(`[parent] Child#${r.id} ready on socket ${r.socketPath}`)):s.type==="inspector-url"?(r.inspectorUrl=String(s.url),console.log(`[parent] Child#${r.id} Debugger listening on ${s.url}`)):s.type==="reloaded"?(r.socketPath=String(s.socketPath),r.healthy=!0,console.log(`[parent] Child#${r.id} hot-swapped on socket ${r.socketPath}`)):s.type==="reload-error"?(r.lastError=String(s.error||"unknown reload error"),console.error(`[parent] Child#${r.id} reload error: ${r.lastError}`),r.healthy=!1):s.type==="boot-error"&&(r.lastError=String(s.error||"unknown boot error"),console.error(`[parent] Child#${r.id} boot error: ${r.lastError}`),r.healthy=!1)}),c.on("exit",(S,s)=>{r.debugSlot>=0&&(A.delete(r.debugSlot),r.debugSlot=-1);const R=s==="SIGINT"||s==="SIGTERM"||S===0;if(R?console.log(`[parent] Child#${r.id} exited cleanly (code=${S}, signal=${s??"none"})`):(console.error(`[parent] Child#${r.id} crashed (code=${S}, signal=${s??"none"})`),r.lastError||(r.lastError=`Child exited abnormally (code=${S}, signal=${s??"none"})`)),r.healthy=!1,cleanupSock(r.socketPath,r.proc.pid),r.socketPath=void 0,!R&&!v){const N=E.indexOf(r);N>=0&&E.splice(N,1);const ne=Date.now();if(O=O.filter(q=>ne-q<3e4),O.length>=5){console.error(`[parent] crash-loop detected (${O.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}O.push(ne),setTimeout(()=>{const q=E.filter(le=>le.proc.killed===!1).length;!v&&q<b&&(console.log(`[parent] respawning a crashed pod (${q}/${b} live)`),U().catch(()=>{}))},1500).unref?.()}}),E.push(r),se(r),r}h(U,"K"),a(U,"spawnChild");async function V(e){b=Math.max(b,e);const t=E.filter(n=>n.proc.killed===!1),l=e-t.length;for(let n=0;n<l;n++)await U()}h(V,"Z"),a(V,"ensurePoolSize");async function ee(){const e=E.filter(t=>!t.healthy||typeof t.socketPath!="string");await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const l=E.indexOf(t);l>=0&&E.splice(l,1),await U()}))}h(ee,"oe"),a(ee,"respawnUnhealthy");const I=[];function J(e){const t=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),l=path.join(t,`${e}.js`);if(!fs.existsSync(l))return console.error(`[parent] Worker "${e}" bundle not found: ${l}`),null;const n=["--enable-source-maps"];__filename.endsWith(".ts")&&n.unshift("--require","@swc-node/register");try{n.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const c=(m||9229)+H+Math.max(0,WORKER_NAMES.indexOf(e));n.push(m?`--inspect=127.0.0.1:${c}`:`--inspect-port=127.0.0.1:${c}`);const r=(0,node_child_process_1.fork)(l,{env:process.env,stdio:["inherit","pipe","pipe","ipc"],execArgv:n}),S={name:e,proc:r,debugPort:c};return I.push(S),Z(r,`\x1B[35m[worker:${e}] \x1B[0m`),r.on("exit",(s,R)=>{R==="SIGINT"||R==="SIGTERM"||s===0||console.error(`[parent] Worker "${e}" crashed (code=${s}, signal=${R??"none"})`);const N=I.indexOf(S);N>=0&&I.splice(N,1)}),console.log(`[parent] Worker "${e}" started (pid=${r.pid})`),S}h(J,"q"),a(J,"spawnWorkerProcess");function te(){for(const e of[...I])try{e.proc.kill("SIGTERM")}catch{}I.length=0;for(const e of WORKER_NAMES)J(e)}h(te,"ne"),a(te,"restartWorkers");const ae=debounce(async()=>{const e=K();if(e.length>0){console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)t.proc.send?.({type:"reload"})}await ee(),WORKER_NAMES.length>0&&te()},200),W=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),ae();return}if(e.method==="POST"&&e.url==="/webpack/scale"){let c="";e.on("data",r=>{c+=r}),e.on("end",async()=>{let r=0;try{r=Number(JSON.parse(c||"{}").pods)||0}catch{}r=Math.max(1,Math.min(r,16)),await V(r),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:r}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const c=new URL(e.url,"http://localhost").searchParams,r=Math.min(Math.max(Number(c.get("tail")??"100")||0,0),_),S=c.get("follow")!=="0",s=c.get("plain")==="1";t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const R=r===0?"":x.slice(-r).join("");if(t.write(s?R.replace(C,""):R),!S){t.end();return}const N={res:t,plain:s};p.add(N),e.on("close",()=>p.delete(N));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){const c=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(c)&&c>1024&&(m=c),m||(m=9229);const r=E.filter(s=>s.proc.exitCode===null&&s.proc.signalCode===null);for(const s of r){s.debugSlot<0&&(s.debugSlot=G());try{s.proc.send?.({type:"debug-open",port:m+s.debugSlot})}catch{}}for(const s of I)try{s.proc.kill("SIGUSR1")}catch{}const S=Date.now()+2e3;for(;Date.now()<S&&r.some(s=>!s.inspectorUrl);)await new Promise(s=>setTimeout(s,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:m,pods:r.map(s=>({id:s.id,inspectorUrl:s.inspectorUrl??null})),workers:I.map(s=>({name:s.name,port:s.debugPort}))},null,2)+`
|
|
5
5
|
`);return}const l=matchGatewayRoute(e);if(l?.prependPrefix&&!e.url?.startsWith(l.prependPrefix)&&(e.url=l.prependPrefix+(e.url??"/")),l?.target){applyGatewayMiddleware(e),i.web(e,t,{target:l.target,autoRewrite:typeof l.target=="string",changeOrigin:!0},c=>{console.error(`[parent] proxy error to ${l.target}:`,c),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${l.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),t.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const n=M();if(!n){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const c=E.map(r=>`#${r.id}: ${r.lastError??"no error recorded"}`).join(`
|
|
6
6
|
`);t.end(`No healthy children available. POST /webpack/reload to recover.
|
|
7
7
|
|
|
8
8
|
Last errors:
|
|
9
9
|
${c}`);return}i.web(e,t,{target:{socketPath:n.socketPath},headers:{"x-proxy-child-id":String(n.id)}},c=>{console.error(`[parent] proxy error to Child#${n.id}:`,c),n.healthy=!1,n.lastError=String(c?.stack||c),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from Child#${n.id}. Try /webpack/reload.
|
|
10
|
-
${n.lastError}`)})},"requestHandler");let
|
|
10
|
+
${n.lastError}`)})},"requestHandler");let D,L,X;const Y=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(n=>n.host).filter(n=>!!n),l=path.join(process.cwd(),"node_modules",".cache","davnx-webpack");L=e.getCertificateSync(l,SERVICE_NAME||"lensmcp.dev",t),X=e.caCertPath(),D=require("node:https").createServer({key:L,cert:L},W)}else D=http.createServer(W);const re=a((e,t,l)=>{const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){i.ws(e,t,l,{target:n.target,changeOrigin:!0},()=>t.destroy());return}const c=M();if(!c){t.destroy();return}i.ws(e,t,l,{target:{socketPath:c.socketPath}},()=>t.destroy())},"upgradeHandler");D.on("upgrade",re),D.on("error",e=>{if(e.code==="EADDRINUSE"){console.warn(`[parent] public port ${y} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected). Give this service a distinct cluster.port to silence this.`);return}console.error("[parent] public server error:",e)}),await V(f);for(const e of WORKER_NAMES)J(e);D.listen(y,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${y}`),SERVICE_PREFIX&&console.log(`[parent] Service prefix: "${SERVICE_PREFIX}" (enforced \u2014 requests without it will get 404)`),gatewayMiddleware&&console.log(`[parent] Gateway middleware: ACTIVE (${GATEWAY_MIDDLEWARE_PATH})`),GATEWAY_ROUTES.length>0&&console.log(`[parent] Gateway routes: ${GATEWAY_ROUTES.map(t=>`${t.host??"*"}${t.prefix??"/"}\u2192${t.target??"children"}`).join(" ")}`),X&&(console.log("[parent] HTTPS dev CA (trust ONCE, then rotations/new hostnames stay green):"),console.log(`[parent] sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${X}`)),console.log(`POST ${e}://localhost:${y}/webpack/reload to trigger rolling swap/respawn`)});const j=Number(process.env.INTERNAL_PORT||0);if(j>0){const e=a((l,n)=>{const c=M();if(!c){n.statusCode=503,n.setHeader("content-type","text/plain; charset=utf-8"),n.end("No healthy children available.");return}i.web(l,n,{target:{socketPath:c.socketPath}},r=>{c.healthy=!1,c.lastError=String(r?.stack||r),n.statusCode=502,n.end(`Upstream error from Child#${c.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(l,n,c)=>{const r=M();if(!r){n.destroy();return}i.ws(l,n,c,{target:{socketPath:r.socketPath}},()=>n.destroy())}),t.on("error",l=>{console.warn(`[parent] internal port ${j} unavailable (${l.code}).`)}),t.listen(j,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${j}`)}),Y.push(t)}const ce=(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of ce){if(!Number.isInteger(e)||e===Number(y))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:L,cert:L},W):http.createServer(W);t.on("upgrade",re),t.on("error",l=>{console.warn(`[parent] extra port ${e} unavailable (${l.code}) \u2014 main port still up.`)}),t.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),Y.push(t)}const z=path.join(SOCK_DIR,"parent.sock");claimSock(z);const Q=http.createServer(W);Q.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),Q.listen(z),Y.push(Q);const oe=a(async e=>{v=!0,console.log(`[${e}] [parent] shutting down\u2026`),cleanupSock(z);for(const t of Y)try{t.close()}catch{}for(const t of I)try{t.proc.kill("SIGTERM")}catch{}for(const t of E){try{t.proc.kill("SIGTERM")}catch{}t.socketPath&&cleanupSock(t.socketPath,t.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}setTimeout(()=>process.exit(0),700).unref()},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{oe(e)}));const F=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(F)&&F>0){const e=setInterval(()=>{try{process.kill(F,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${F}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),oe("gateway-gone")}},5e3);e.unref()}})()}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/cluster",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.1",
|
|
4
4
|
"description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -65,9 +65,9 @@
|
|
|
65
65
|
}
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@lensmcp/core": "1.20.
|
|
69
|
-
"@lensmcp/node-instrumentation": "1.20.
|
|
70
|
-
"@lensmcp/nx-plugin": "1.20.
|
|
68
|
+
"@lensmcp/core": "1.20.1",
|
|
69
|
+
"@lensmcp/node-instrumentation": "1.20.1",
|
|
70
|
+
"@lensmcp/nx-plugin": "1.20.1",
|
|
71
71
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
|
72
72
|
"fork-ts-checker-webpack-plugin": "^9.0.0",
|
|
73
73
|
"glob": "^11.0.0",
|
package/tsgo-check-plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)?
|
|
3
|
-
`);const
|
|
4
|
-
`)[0]?.slice(0,300)??""}
|
|
1
|
+
"use strict";var d=Object.defineProperty;var l=(s,t)=>d(s,"name",{value:t,configurable:!0});var u=Object.defineProperty,r=l((s,t)=>u(s,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=void 0,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(s){return s==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}l(shimNames,"shimNames"),r(shimNames,"shimNames");function isExecutableFile(s,t){try{if(!fs.statSync(s).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(s,fs.constants.X_OK),!0}catch{return!1}}l(isExecutableFile,"isExecutableFile"),r(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let s=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const i=path.join(s,"package.json");if(fs.existsSync(i))try{const{name:e}=JSON.parse(fs.readFileSync(i,"utf8"));if(e===exports.TSGO_PACKAGE)return s}catch{}const o=path.dirname(s);if(o===s)break;s=o}}catch{}return null}l(resolveTsgoPackageDir,"resolveTsgoPackageDir"),r(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(s){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(s,"package.json"),"utf8")),i=typeof t=="string"?t:t?.tsgo;return i?path.join(s,i):null}catch{return null}}l(packageDeclaredBin,"packageDeclaredBin"),r(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(s,t){const i=path.resolve(s,"..","..",".bin"),o=shimNames(t).map(n=>path.join(i,n)),e=t==="win32"?null:packageDeclaredBin(s);return e?[e,...o]:o}l(ownBinCandidates,"ownBinCandidates"),r(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(s,t,i={}){const o=i.platform??process.platform,e=i.isExecutable??(p=>isExecutableFile(p,o));if(t)return e(t)?t:null;for(const p of shimNames(o)){const a=path.join(s,"node_modules",".bin",p);if(e(a))return a}const n=(i.ownPackageDir??resolveTsgoPackageDir)();return n?ownBinCandidates(n,o).find(e)??null:null}l(resolveTsgoBin,"resolveTsgoBin"),r(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(s){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:s.workspaceRoot,project:s.appName,tool:"tsgo",tsConfig:s.tsConfig,output:"",durationMs:0,toolError:s.detail,...s.eventFile?{eventFile:s.eventFile}:{}})}catch{}}l(reportTsgoUnavailable,"reportTsgoUnavailable"),r(reportTsgoUnavailable,"reportTsgoUnavailable");function writeShimTsconfig(s,t,i){const o=path.join(i,"tmp","lensmcp-tsgo");fs.mkdirSync(o,{recursive:!0});const e=path.join(o,`${s}.tsconfig.json`);return fs.writeFileSync(e,JSON.stringify({extends:t,compilerOptions:{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null}},null,2)),e}l(writeShimTsconfig,"writeShimTsconfig"),r(writeShimTsconfig,"writeShimTsconfig");class TsgoCheckPlugin{static{l(this,"TsgoCheckPlugin")}static{r(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.inflight=null,this.shimPath=null,this.disabled=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn}apply(t){t.hooks.done.tap("TsgoCheckPlugin",i=>{i.hasErrors()||this.schedule()})}schedule(){this.disabled||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.run(),this.opts.debounceMs??500),this.timer.unref?.())}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){const t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath);if(!t){this.disabled=!0;const n=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;console.warn(`[tsgo] ${this.opts.appName}: ${n}.`),this.publish({output:"",durationMs:0,toolError:n});return}this.inflight&&(this.inflight.kill("SIGTERM"),this.inflight=null),this.shimPath||(this.shimPath=writeShimTsconfig(this.opts.appName,this.opts.tsConfig,this.opts.workspaceRoot));const i=Date.now(),o=this.spawnImpl(t,["--noEmit","--pretty","false","-p",this.shimPath],{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"]});this.inflight=o;let e="";o.stdout?.on("data",n=>{e+=n.toString()}),o.stderr?.on("data",n=>{e+=n.toString()}),o.on("error",()=>{this.inflight===o&&(this.inflight=null),console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.publish({output:"",durationMs:Date.now()-i,toolError:`failed to spawn ${t}`})}),o.on("close",(n,p)=>{if(this.inflight===o&&(this.inflight=null),p)return;const a=Date.now()-i,h=(a/1e3).toFixed(1);if(n===0){console.log(`[tsgo] ${this.opts.appName}: types clean (${h}s)`),this.publish({output:"",durationMs:a});return}e.trim()&&process.stdout.write(e.endsWith(`
|
|
2
|
+
`)?e:`${e}
|
|
3
|
+
`);const c=(e.match(/error TS\d+/g)??[]).length;console.log(`[tsgo] ${this.opts.appName}: ${c} type error${c===1?"":"s"} (${h}s)`),this.publish({output:e,durationMs:a,...c===0?{toolError:`tsgo exited ${n} with no diagnostics: ${firstLine(e)}`}:{}})})}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(s){return s.trim().split(`
|
|
4
|
+
`)[0]?.slice(0,300)??""}l(firstLine,"firstLine"),r(firstLine,"firstLine");
|
package/typecheck-bus.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)){const o=parseTscDiagnosticLine(
|
|
1
|
+
"use strict";var g=Object.defineProperty;var s=(t,e)=>g(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,i=s((t,e)=>f(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_DIAGNOSTICS_PER_RUN=void 0,exports.stripAnsi=stripAnsi,exports.parseTscDiagnosticLine=parseTscDiagnosticLine,exports.parseTscOutput=parseTscOutput,exports.buildTypecheckRunEvents=buildTypecheckRunEvents,exports.resolveEventFile=resolveEventFile,exports.appendTypecheckEvents=appendTypecheckEvents,exports.publishTypecheckRun=publishTypecheckRun;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})(),DIAG_LINE_REGEX=/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/,ANSI_CSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function stripAnsi(t){return t.replace(ANSI_CSI,"")}s(stripAnsi,"stripAnsi"),i(stripAnsi,"stripAnsi");function parseTscDiagnosticLine(t){const e=stripAnsi(t).trim();if(!e)return null;const n=DIAG_LINE_REGEX.exec(e);if(!n)return null;const[,o,l,u,c,a,p]=n;return!o||!l||!u||!c||!a||!p?null:{file:o,line:Number(l),column:Number(u),severity:c==="warning"?"warning":"error",code:a,message:p}}s(parseTscDiagnosticLine,"parseTscDiagnosticLine"),i(parseTscDiagnosticLine,"parseTscDiagnosticLine");function parseTscOutput(t){const e=[];for(const n of t.split(`
|
|
2
|
+
`)){const o=parseTscDiagnosticLine(n);o&&e.push(o)}return e}s(parseTscOutput,"parseTscOutput"),i(parseTscOutput,"parseTscOutput"),exports.MAX_DIAGNOSTICS_PER_RUN=200;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}s(makeId,"makeId"),i(makeId,"makeId");function buildTypecheckRunEvents(t){const e=(t.now??Date.now)(),n=t.idImpl??makeId,o="pending",l={sessionId:o,source:"typescript",category:"typecheck",context:{sessionId:o,projectName:t.project}},u={project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{}},c=t.diagnostics.filter(r=>r.severity==="error"),a=t.diagnostics.slice(0,exports.MAX_DIAGNOSTICS_PER_RUN),p=[];if(!t.toolError){p.push({...l,id:n(),timestamp:e,severity:"info",title:`tsc clear: ${t.project}`,message:`typecheck run starting for ${t.project}`,fingerprint:`tsc:${t.project}:run-start`,raw:{...u,kind:"typecheck-run",phase:"start"}});for(const r of a)p.push({...l,id:n(),timestamp:e,severity:r.severity,title:`${r.code}: ${r.message}`,message:r.message,location:{file:r.file,line:r.line,column:r.column},fingerprint:`tsc:${t.project}:${r.file}:${r.line}:${r.column}:${r.code}`,raw:{...u,kind:"typecheck-diagnostic",code:r.code}})}const d=t.toolError?"error":c.length>0?"failing":"clean";return p.push({...l,id:n(),timestamp:e,severity:"info",title:`typecheck run: ${t.project} \u2014 ${t.toolError?"tool error":`${c.length} error${c.length===1?"":"s"}`} (${t.durationMs}ms)`,...t.toolError?{message:t.toolError}:{},fingerprint:`tsc:${t.project}:run-end`,raw:{...u,kind:"typecheck-run",phase:"end",status:d,durationMs:t.durationMs,errorCount:c.length,warningCount:t.diagnostics.length-c.length,...t.diagnostics.length>a.length?{truncatedDiagnostics:t.diagnostics.length-a.length}:{},...t.toolError?{error:t.toolError}:{}}}),p}s(buildTypecheckRunEvents,"buildTypecheckRunEvents"),i(buildTypecheckRunEvents,"buildTypecheckRunEvents");function resolveEventFile(t){return process.env.LENSMCP_EVENT_FILE||path.join(t,".lensmcp","events.jsonl")}s(resolveEventFile,"resolveEventFile"),i(resolveEventFile,"resolveEventFile");let ensuredDir=null;function ensureDir(t){const e=path.dirname(t);ensuredDir!==e&&(fs.mkdirSync(e,{recursive:!0}),ensuredDir=e)}s(ensureDir,"ensureDir"),i(ensureDir,"ensureDir");function appendTypecheckEvents(t,e){if(e.length===0)return;const n=e.map(o=>JSON.stringify(o)).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`;try{ensureDir(
|
|
4
|
+
`;try{ensureDir(t),busHygiene?.maybeRotateEventFile(t,n.length),fs.appendFileSync(t,n)}catch(o){if(o?.code==="ENOENT"){try{ensuredDir=null,ensureDir(t),fs.appendFileSync(t,n)}catch{}return}}}s(appendTypecheckEvents,"appendTypecheckEvents"),i(appendTypecheckEvents,"appendTypecheckEvents");function publishTypecheckRun(t){const e=buildTypecheckRunEvents({project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{},diagnostics:t.toolError?[]:parseTscOutput(t.output),durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{}});return appendTypecheckEvents(t.eventFile??resolveEventFile(t.workspaceRoot),e),e}s(publishTypecheckRun,"publishTypecheckRun"),i(publishTypecheckRun,"publishTypecheckRun");
|