@lensmcp/cluster 1.25.78 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/build-scope-patterns.d.ts +1 -11
  2. package/build-scope-patterns.js +1 -1
  3. package/create-webpack-prod.d.ts +1 -27
  4. package/create-webpack-prod.js +1 -1
  5. package/executors/build/build.impl.js +1 -1
  6. package/executors/gateway/daemon.d.ts +43 -0
  7. package/executors/gateway/daemon.js +1 -0
  8. package/executors/gateway/gateway.lib.d.ts +1 -1
  9. package/executors/gateway/gateway.lib.js +1 -1
  10. package/executors/gateway/jwks-verify.d.ts +1 -79
  11. package/executors/gateway/jwks-verify.js +1 -1
  12. package/executors/gateway/main.rollout.d.ts +2 -1
  13. package/executors/gateway/main.rollout.js +1 -24
  14. package/executors/gateway/manifest.d.ts +1 -418
  15. package/executors/gateway/manifest.js +1 -1
  16. package/executors/gateway/prod-runtime/trust.d.ts +1 -80
  17. package/executors/gateway/prod-runtime/trust.js +1 -1
  18. package/executors/gateway/rate-limit.d.ts +1 -81
  19. package/executors/gateway/rate-limit.js +1 -18
  20. package/executors/gateway/runtime/auth.d.ts +1 -1
  21. package/executors/gateway/runtime/auth.js +1 -1
  22. package/executors/gateway/runtime/dev-auth.d.ts +3 -2
  23. package/executors/gateway/runtime/dev-auth.js +1 -1
  24. package/executors/gateway/runtime/discovery.js +1 -1
  25. package/executors/gateway/runtime/edge.d.ts +2 -2
  26. package/executors/gateway/runtime/edge.js +1 -1
  27. package/executors/gateway/runtime/handler.js +1 -1
  28. package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
  29. package/executors/gateway/runtime/lens-children.js +1 -1
  30. package/executors/gateway/runtime/lens-modules.d.ts +13 -0
  31. package/executors/gateway/runtime/lens-modules.js +1 -0
  32. package/executors/gateway/runtime/lifecycle.js +1 -1
  33. package/executors/gateway/runtime/observability.js +1 -1
  34. package/executors/gateway/runtime/proxy.js +1 -1
  35. package/executors/gateway/runtime/route-registry.js +1 -1
  36. package/executors/gateway/runtime/serve-launch.d.ts +27 -0
  37. package/executors/gateway/runtime/serve-launch.js +3 -3
  38. package/executors/gateway/runtime/server.d.ts +1 -1
  39. package/executors/gateway/runtime/server.js +2 -2
  40. package/executors/gateway/runtime/services-decl.d.ts +24 -0
  41. package/executors/gateway/runtime/services-decl.js +1 -0
  42. package/executors/gateway/runtime/shared-build.d.ts +2 -2
  43. package/executors/gateway/runtime/shared-build.js +3 -3
  44. package/executors/gateway/runtime/types.d.ts +9 -3
  45. package/executors/gateway/runtime/upgrade.js +1 -1
  46. package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
  47. package/executors/gateway/runtime/workspace-auth.js +1 -1
  48. package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
  49. package/executors/gateway/runtime/workspace-middleware.js +1 -1
  50. package/executors/serve/lens-run.d.ts +6 -0
  51. package/executors/serve/lens-run.js +1 -0
  52. package/executors/serve/schema.d.ts +2 -0
  53. package/executors/serve/schema.json +4 -0
  54. package/executors/serve/serve.impl.js +1 -1
  55. package/executors/trust/run.d.ts +19 -0
  56. package/executors/trust/run.js +1 -0
  57. package/executors/trust/trust.impl.js +5 -5
  58. package/gateway.d.ts +7 -19
  59. package/gateway.js +1 -1
  60. package/gc-notice.d.ts +3 -1
  61. package/gc-notice.js +1 -1
  62. package/main.devserver.js +7 -7
  63. package/package.json +6 -34
  64. package/pod-memory.d.ts +19 -2
  65. package/pod-memory.js +1 -1
  66. package/tsgo-check-plugin.d.ts +3 -2
  67. package/tsgo-check-plugin.js +3 -3
  68. package/typecheck-bus.d.ts +17 -0
  69. package/typecheck-bus.js +4 -3
  70. package/executors/gateway/body-stall.d.ts +0 -62
  71. package/executors/gateway/body-stall.js +0 -1
  72. package/executors/gateway/canonical-path.d.ts +0 -65
  73. package/executors/gateway/canonical-path.js +0 -1
  74. package/executors/gateway/client-ip.d.ts +0 -82
  75. package/executors/gateway/client-ip.js +0 -1
  76. package/executors/gateway/gateway-errors.d.ts +0 -43
  77. package/executors/gateway/gateway-errors.js +0 -1
  78. package/executors/gateway/health-check.d.ts +0 -52
  79. package/executors/gateway/health-check.js +0 -1
  80. package/executors/gateway/jwt-claims.d.ts +0 -51
  81. package/executors/gateway/jwt-claims.js +0 -1
  82. package/executors/gateway/main.prod-gateway.d.ts +0 -1
  83. package/executors/gateway/main.prod-gateway.js +0 -2
  84. package/executors/gateway/metrics.d.ts +0 -36
  85. package/executors/gateway/metrics.js +0 -1
  86. package/executors/gateway/otel-tracing.d.ts +0 -46
  87. package/executors/gateway/otel-tracing.js +0 -1
  88. package/executors/gateway/prod-config.d.ts +0 -130
  89. package/executors/gateway/prod-config.js +0 -1
  90. package/executors/gateway/prod-gateway.lib.d.ts +0 -19
  91. package/executors/gateway/prod-gateway.lib.js +0 -1
  92. package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
  93. package/executors/gateway/prod-runtime/access-log.js +0 -1
  94. package/executors/gateway/prod-runtime/app.d.ts +0 -30
  95. package/executors/gateway/prod-runtime/app.js +0 -1
  96. package/executors/gateway/prod-runtime/auth.d.ts +0 -29
  97. package/executors/gateway/prod-runtime/auth.js +0 -1
  98. package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
  99. package/executors/gateway/prod-runtime/body-stall.js +0 -1
  100. package/executors/gateway/prod-runtime/cors.d.ts +0 -18
  101. package/executors/gateway/prod-runtime/cors.js +0 -1
  102. package/executors/gateway/prod-runtime/edge.d.ts +0 -44
  103. package/executors/gateway/prod-runtime/edge.js +0 -1
  104. package/executors/gateway/prod-runtime/handler.d.ts +0 -33
  105. package/executors/gateway/prod-runtime/handler.js +0 -1
  106. package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
  107. package/executors/gateway/prod-runtime/hooks.js +0 -1
  108. package/executors/gateway/prod-runtime/observability.d.ts +0 -24
  109. package/executors/gateway/prod-runtime/observability.js +0 -1
  110. package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
  111. package/executors/gateway/prod-runtime/rollout.js +0 -1
  112. package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
  113. package/executors/gateway/prod-runtime/route-limits.js +0 -1
  114. package/executors/gateway/prod-runtime/routing.d.ts +0 -3
  115. package/executors/gateway/prod-runtime/routing.js +0 -1
  116. package/executors/gateway/prod-runtime/server.d.ts +0 -17
  117. package/executors/gateway/prod-runtime/server.js +0 -1
  118. package/executors/gateway/prod-runtime/types.d.ts +0 -335
  119. package/executors/gateway/prod-runtime/types.js +0 -1
  120. package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
  121. package/executors/gateway/prod-runtime/upgrade.js +0 -16
  122. package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
  123. package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
  124. package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
  125. package/executors/gateway/prod-runtime/upstream.js +0 -1
  126. package/executors/gateway/providers-prod.d.ts +0 -54
  127. package/executors/gateway/providers-prod.js +0 -1
  128. package/executors/gateway/registry-source.d.ts +0 -68
  129. package/executors/gateway/registry-source.js +0 -2
  130. package/executors/gateway/rollout-ops.d.ts +0 -53
  131. package/executors/gateway/rollout-ops.js +0 -2
  132. package/executors/gateway/ssrf-guard.d.ts +0 -96
  133. package/executors/gateway/ssrf-guard.js +0 -1
  134. package/executors/gateway/workspace-auth.d.ts +0 -100
  135. package/executors/gateway/workspace-auth.js +0 -1
@@ -1 +1 @@
1
- "use strict";var M=Object.defineProperty;var d=(t,r)=>M(t,"name",{value:r,configurable:!0});var g=Object.defineProperty,s=d((t,r)=>g(t,"name",{value:r,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.unavailableMiddleware=void 0,exports.guestMiddlewarePolicy=guestMiddlewarePolicy,exports.findGatewayMiddleware=findGatewayMiddleware,exports.loadMiddleware=loadMiddleware,exports.createWorkspaceMiddleware=createWorkspaceMiddleware;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),workspace_auth_1=require("../workspace-auth");function guestMiddlewarePolicy(t=process.env){const r=t.LENSMCP_GUEST_MIDDLEWARE;return r==="owner"||r==="none"?r:"own"}d(guestMiddlewarePolicy,"guestMiddlewarePolicy"),s(guestMiddlewarePolicy,"guestMiddlewarePolicy");function findGatewayMiddleware(t,r){for(const i of Object.values(r)){let a;try{a=JSON.parse(fs.readFileSync(path.join(t,i.root,"project.json"),"utf8"))}catch{continue}for(const o of Object.values(a.targets??{}))if(o?.executor==="@lensmcp/cluster:gateway"&&typeof o.options?.middleware=="string"&&o.options.middleware)return o.options.middleware}}d(findGatewayMiddleware,"findGatewayMiddleware"),s(findGatewayMiddleware,"findGatewayMiddleware");function loadMiddleware(t){const r=require.resolve(t);delete require.cache[r];const i=require(r);return(0,workspace_auth_1.validateMiddleware)(i.default??i)}d(loadMiddleware,"loadMiddleware"),s(loadMiddleware,"loadMiddleware");const unavailableMiddleware=s(()=>{throw new Error("Gateway middleware unavailable")},"unavailableMiddleware");exports.unavailableMiddleware=unavailableMiddleware;const loadFailure=s(t=>{const r=t;return typeof r?.code=="string"?r.code:typeof r?.name=="string"?r.name:"error"},"loadFailure");function release(t,r,i,a){const o=i?.dispose;if(typeof o=="function")try{const e=o.call(i);e&&typeof e.catch=="function"&&e.catch(n=>console.warn(`[gateway] a middleware's dispose failed (${loadFailure(n)})`))}catch(e){console.warn(`[gateway] a middleware's dispose failed (${loadFailure(e)})`)}let l=t;try{l=fs.realpathSync(t)}catch{}const c=[t,l].map(e=>e.endsWith(path.sep)?e:e+path.sep);for(const e of Object.keys(a))(r.includes(e)||c.some(n=>e.startsWith(n)))&&delete a[e]}d(release,"release"),s(release,"release");function createWorkspaceMiddleware(t){const r=t.policy??"own",i=t.load??loadMiddleware,a=new Map,o=new Map,l=t.cache??require.cache,c=s(e=>{const n=o.get(e);n&&release(n.root,n.loaded,a.get(e),l),o.delete(e)},"letGo");return{set(e,n,p){if(e===t.ownerKey)return;if(c(e),!p){a.set(e,void 0);return}const u=path.resolve(n,p),f=new Set(Object.keys(l));try{const w=i(u);o.set(e,{root:n,loaded:Object.keys(l).filter(y=>!f.has(y))}),a.set(e,w),r==="own"&&console.log(`[gateway] '${e}' routes run its own middleware: ${u}`)}catch(w){a.set(e,exports.unavailableMiddleware),console.warn(`[gateway] could not load '${e}''s middleware ${u} (${loadFailure(w)}) \u2014 its routes refuse every request until it registers again`)}},drop(e){c(e),a.delete(e)},for(e){if(e===void 0||e===t.ownerKey||r==="owner")return t.owner;if(r!=="none")return a.get(e)}}}d(createWorkspaceMiddleware,"createWorkspaceMiddleware"),s(createWorkspaceMiddleware,"createWorkspaceMiddleware");
1
+ "use strict";var M=Object.defineProperty;var s=(t,r)=>M(t,"name",{value:r,configurable:!0});var g=Object.defineProperty,d=s((t,r)=>g(t,"name",{value:r,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.unavailableMiddleware=void 0,exports.guestMiddlewarePolicy=guestMiddlewarePolicy,exports.findGatewayMiddleware=findGatewayMiddleware,exports.loadMiddleware=loadMiddleware,exports.createWorkspaceMiddleware=createWorkspaceMiddleware;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),workspace_auth_1=require("edgeward/workspace-auth");function guestMiddlewarePolicy(t=process.env){const r=t.LENSMCP_GUEST_MIDDLEWARE;return r==="owner"||r==="none"?r:"own"}s(guestMiddlewarePolicy,"guestMiddlewarePolicy"),d(guestMiddlewarePolicy,"guestMiddlewarePolicy");function findGatewayMiddleware(t,r){for(const i of Object.values(r)){let a;try{a=JSON.parse(fs.readFileSync(path.join(t,i.root,"project.json"),"utf8"))}catch{continue}for(const o of Object.values(a.targets??{}))if(o?.executor==="@lensmcp/cluster:gateway"&&typeof o.options?.middleware=="string"&&o.options.middleware)return o.options.middleware}}s(findGatewayMiddleware,"findGatewayMiddleware"),d(findGatewayMiddleware,"findGatewayMiddleware");function loadMiddleware(t){const r=require.resolve(t);delete require.cache[r];const i=require(r);return(0,workspace_auth_1.validateMiddleware)(i.default??i)}s(loadMiddleware,"loadMiddleware"),d(loadMiddleware,"loadMiddleware");const unavailableMiddleware=d(()=>{throw new Error("Gateway middleware unavailable")},"unavailableMiddleware");exports.unavailableMiddleware=unavailableMiddleware;const loadFailure=d(t=>{const r=t;return typeof r?.code=="string"?r.code:typeof r?.name=="string"?r.name:"error"},"loadFailure");function release(t,r,i,a){const o=i?.dispose;if(typeof o=="function")try{const e=o.call(i);e&&typeof e.catch=="function"&&e.catch(n=>console.warn(`[gateway] a middleware's dispose failed (${loadFailure(n)})`))}catch(e){console.warn(`[gateway] a middleware's dispose failed (${loadFailure(e)})`)}let l=t;try{l=fs.realpathSync(t)}catch{}const c=[t,l].map(e=>e.endsWith(path.sep)?e:e+path.sep);for(const e of Object.keys(a))(r.includes(e)||c.some(n=>e.startsWith(n)))&&delete a[e]}s(release,"release"),d(release,"release");function createWorkspaceMiddleware(t){const r=t.policy??"own",i=t.load??loadMiddleware,a=new Map,o=new Map,l=t.cache??require.cache,c=d(e=>{const n=o.get(e);n&&release(n.root,n.loaded,a.get(e),l),o.delete(e)},"letGo");return{set(e,n,p){if(e===t.ownerKey)return;if(c(e),!p){a.set(e,void 0);return}const u=path.resolve(n,p),f=new Set(Object.keys(l));try{const w=i(u);o.set(e,{root:n,loaded:Object.keys(l).filter(y=>!f.has(y))}),a.set(e,w),r==="own"&&console.log(`[gateway] '${e}' routes run its own middleware: ${u}`)}catch(w){a.set(e,exports.unavailableMiddleware),console.warn(`[gateway] could not load '${e}''s middleware ${u} (${loadFailure(w)}) \u2014 its routes refuse every request until it registers again`)}},drop(e){c(e),a.delete(e)},for(e){if(e===void 0||e===t.ownerKey||r==="owner")return t.owner;if(r!=="none")return a.get(e)}}}s(createWorkspaceMiddleware,"createWorkspaceMiddleware"),d(createWorkspaceMiddleware,"createWorkspaceMiddleware");
@@ -0,0 +1,6 @@
1
+ interface LensTarget {
2
+ project: string;
3
+ target: string;
4
+ }
5
+ export declare function run(_cwd: string, root: string, target: LensTarget, overrides: Record<string, unknown>, _isVerbose: boolean, taskGraph: unknown): Promise<number>;
6
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";var f=Object.defineProperty;var o=(r,e)=>f(r,"name",{value:e,configurable:!0});var p=Object.defineProperty,c=o((r,e)=>p(r,"name",{value:e,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.run=run;const tslib_1=require("tslib"),serve_impl_1=tslib_1.__importDefault(require("./serve.impl"));async function run(r,e,t,a,v,u){const s=a.lensServe,n=u?.lens?.projectRoot;if(!s||n===void 0)return console.error("[lens-run] the gateway sent no serve options for this service"),1;let i=!1;for await(const l of(0,serve_impl_1.default)(s,{root:e,projectName:t.project,targetName:t.target,projectsConfigurations:{projects:{[t.project]:{root:n}}}}))i=l.success;return i?0:1}o(run,"run"),c(run,"run");
@@ -50,6 +50,8 @@ export interface ServeExecutorSchema {
50
50
  nodeExternalsConfig?: NodeExternalsConfig;
51
51
  webpackConfigPath?: string;
52
52
  serviceName?: string;
53
+ /** The devserver's public port, over `config/config.<env>.yaml`'s. */
54
+ port?: number;
53
55
  servePrefix?: string;
54
56
  gateway?: GatewayConfig;
55
57
  /** Plain-http listener straight to the children - service-to-service calls, no gateway middleware. */
@@ -143,6 +143,10 @@
143
143
  "type": "string",
144
144
  "description": "Service name for config resolution and socket directory naming. Overrides the value from config YAML. Does not affect URL prefix — use servePrefix for that."
145
145
  },
146
+ "port": {
147
+ "type": "number",
148
+ "description": "The devserver's public port. Overrides the value from config YAML."
149
+ },
146
150
  "servePrefix": {
147
151
  "type": "string",
148
152
  "description": "URL path prefix for the devserver (e.g. 'agenshield' → /agenshield/). Empty string means no prefix. Independent of serviceName.",
@@ -1 +1 @@
1
- "use strict";var _e=Object.defineProperty;var i=(e,o)=>_e(e,"name",{value:o,configurable:!0});var ve=Object.defineProperty,s=i((e,o)=>ve(e,"name",{value:o,configurable:!0}),"s");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")),node_child_process_1=require("node:child_process"),yaml=tslib_1.__importStar(require("js-yaml")),child_process_env_1=require("../../child-process-env"),dev_devtool_1=require("../../dev-devtool"),devserver_host_1=require("../../devserver-host"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach"),stop_on_signal_1=require("./stop-on-signal"),compile_retry_1=require("../../compile-retry"),config_files_1=require("../../config-files"),signature_1=require("../../shared-build/signature");function definedEnv(e){const o={};for(const[j,n]of Object.entries(e))typeof n=="string"&&(o[j]=n);return o}i(definedEnv,"definedEnv"),s(definedEnv,"definedEnv");const frozen=s(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,o){process.env.NODE_ENV="development";const j=o.projectsConfigurations.projects[o.projectName],n=o.root,S=path.join(n,j.root),Q=e.outputPath?path.join(n,e.outputPath):path.join(n,"dist",j.root),ee=e.configEnv||"development",A=path.join(n,"config",`config.${ee}.yaml`),q=3050;let d=q,a=o.projectName,O={};fs.existsSync(A)?(O=yaml.load(fs.readFileSync(A,"utf8")),d=Number(O.port)||d,a=O.serviceName||a):console.warn(`[serve] ${o.projectName}: no config file at ${A} \u2014 public devserver port defaults to ${q}. If another service also lacks its config, both bind ${q} \u2192 EADDRINUSE. Add config/config.${ee}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(a=e.serviceName);const I=e.servePrefix??"",y=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),ce=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),g=e.logFile?path.resolve(n,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(g){fs.mkdirSync(path.dirname(g),{recursive:!0}),fs.writeFileSync(g,"",{mode:384});try{fs.chmodSync(g,384)}catch{}}let M,F;e.gateway?.middleware&&(M=path.resolve(S,e.gateway.middleware),F=JSON.stringify(O));const ae=e.entryFile||"./src/deployments/service/main.ts",le=e.tsConfigFile||"./tsconfig.app.json",ue=path.resolve(S,ae),oe=path.resolve(S,le),pe=(e.workers||[]).map(r=>({entryName:r.name,entryPath:path.resolve(S,r.entryPath)})),m={appName:o.projectName,appRoot:S,outputDir:Q,main:ue,tsConfig:oe,assets:e.assets||[],additionalEntryPoints:pe,port:d,serviceName:a,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:n,orgScopes:e.orgScopes||[],bundlePackages:e.bundlePackages||[],nodeExternalsConfig:e.nodeExternalsConfig,webpackConfigPath:e.webpackConfigPath,httpsReload:e.gateway?.https===!0,...e.devtool!==void 0&&{devtool:e.devtool}};let l=null,U=!1,G=!1,B=!1,h=!1;const re=path.join(__dirname,"../../main.devserver.js"),te=path.join(__dirname,"../../main.devserver.ts"),W=!fs.existsSync(re)&&fs.existsSync(te),L=W?te:re,de=path.join(Q,"main.js");function H(){l&&!l.killed&&(l.kill("SIGTERM"),l=null)}i(H,"Q"),s(H,"cleanup");function R(){h=!0,H()}i(R,"W"),s(R,"stop");const he=(0,stop_on_signal_1.stopOnSignal)({stop:R,close:s(()=>b(),"close")});process.on("exit",R);function P(){if(h||U)return;if(!fs.existsSync(L)){console.error(`[serve] devserver script not found at ${L}`);return}const r=(0,child_process_env_1.childProcessEnv)({...process.env,PORT:String(d),SERVICE_NAME:a,SERVE_PREFIX:I,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||o.projectName||a,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(n,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:de,...M&&{GATEWAY_MIDDLEWARE:M},...F&&{GATEWAY_CONFIG:F},...e.gateway?.routes?.length&&{GATEWAY_ROUTES:JSON.stringify(e.gateway.routes)},...e.gateway?.https&&{GATEWAY_HTTPS:"1"},...e.gateway?.extraPorts?.length&&{GATEWAY_EXTRA_PORTS:JSON.stringify(e.gateway.extraPorts)},...e.internalPort&&{INTERNAL_PORT:String(e.internalPort)},...y&&{LENSMCP_DEBUG_PORT:String(y)},...g&&{LENSMCP_LOG_FILE:g},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:B?"1":"0"});if((0,devserver_host_1.devserverInProcessOffered)()&&(!W||require.extensions[".ts"])){U=!0;for(const[u,f]of Object.entries(r))f!==void 0&&(process.env[u]=f);(0,devserver_host_1.markDevserverInProcess)(),require(L),J("in this process");return}const v=["--enable-source-maps"];W&&v.unshift("--require","@swc-node/register");const c=(0,node_child_process_1.fork)(L,{cwd:n,env:r,stdio:["inherit","inherit","inherit","ipc"],execArgv:v,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(n),a,"dev"))});l=c,c.on("exit",(u,f)=>{l===c&&(l=null),!(f||u===0||h)&&(console.error(`[serve] devserver exited unexpectedly (code=${u}, signal=${f}) \u2014 respawning in 1.5s`),setTimeout(()=>{!h&&!l&&G&&P()},1500).unref?.())}),J()}i(P,"j"),s(P,"startDevServer");function J(r){console.log(`[serve] Devserver started on port ${d} (service: ${a}${I?`, prefix: /${I}`:""}${r?`, ${r}`:""})`),y?(console.warn(`[serve] DEBUGGER ENABLED for ${a}. Node's inspector has NO authentication \u2014 the ws:// UUID is the whole credential, and any account on this host that obtains it runs code as you. Do not enable this on a shared machine.`),ce?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${y}+slot (workers ${y}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${y}. Unset it to bind ephemeral ports instead.`):console.log(`[serve] Debug: pod inspectors bind an EPHEMERAL 127.0.0.1 port. Get the ws:// URLs with \`lensmcp debug ${a}\` (the owner-only control socket); a devserver run in your own terminal also prints them there. Set LENSMCP_DEBUG_FIXED_PORTS=1 if your IDE needs a fixed attach port.`)):console.log(`[serve] Debug on demand: \`lensmcp debug ${a}\` opens pod inspectors without a restart`),g&&console.log(`[serve] Logs teed to ${g} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}i(J,"ee"),s(J,"announceDevServer");function fe(){if(!l||l.killed){console.log("[serve] Devserver not running, restarting..."),P();return}fetch(`http://localhost:${d}/webpack/reload`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(()=>console.log("[serve] Notified devserver to reload")).catch(r=>{console.warn("[serve] Failed to notify devserver, restarting...",r.message),H(),P()})}i(fe,"me"),s(fe,"_notifyDevServerReload");let D=null;const V=[];function _(r){if(D){const v=D;D=null,v(r)}else V.push(r)}i(_,"w"),s(_,"pushResult");function se(){return V.length>0?Promise.resolve(V.shift()):new Promise(r=>{D=r})}i(se,"de"),s(se,"waitForNext");let b=s(()=>{},"closeBuild");function Y(){return!G||!l&&!U?(G=!0,P(),!0):!1}i(Y,"re"),s(Y,"builtOk");function X(){try{return JSON.stringify((0,signature_1.transpileCompilerOptions)(m.tsConfig,n))}catch{return}}i(X,"te"),s(X,"compileShape");function C(){if(h)return;const{createDevWebpackConfig:r}=require("../../create-webpack-dev"),v=require("webpack"),c=m.webpackConfigPath?path.resolve(m.appRoot,m.webpackConfigPath):void 0;if(c)try{delete require.cache[require.resolve(c)]}catch{}const u=r(m),{watch:f,...t}=u,z=(0,config_files_1.configFilesOf)(m),K=X(),{TsgoCheckPlugin:ge}=require("../../tsgo-check-plugin"),me=process.env.LENSMCP_TYPECHECK!=="off"&&!(t.plugins??[]).some(p=>p instanceof ge);let $,Z=!1;t.plugins=[...t.plugins??[],new config_files_1.ConfigFilesPlugin({files:s(()=>z,"files"),changed:s(p=>{let w=!1;if(!c||!p.includes(c)){const N=X();if(N===void 0)return;if(N===K){if(!me||p.every(k=>k===m.tsConfig))return;w=!0}}Z=($===void 0||Z)&&w,$=p.map(N=>path.relative(n,N)).sort().join(", ")},"changed")})];const T=v(t);B=(0,dev_devtool_1.bundleCarriesSourceMaps)(T.options.devtool);let E;const x=(0,compile_retry_1.createFailureRetry)(()=>{h||!E||(console.log(`[serve] ${o.projectName}: compiling again after the failure`),E.invalidate())}),ie=s((p,w)=>{if($!==void 0&&E&&!h){console.log(Z?`[serve] ${o.projectName}: ${$} changed what it type-checks with \u2014 fork-ts-checker reads that only when it starts, so a new compiler checks it`:`[serve] ${o.projectName}: ${$} changed what it compiles with \u2014 compiling again with a new compiler`),x.dispose();const k=E;E=void 0,setImmediate(()=>k.close(()=>C()));return}if(p){if(console.error("[serve] Webpack error:",p),E&&!h){const{delayMs:k,retry:Ee}=x.failed();console.log(`[serve] ${o.projectName}: compiling again in ${Math.round(k/1e3)} s (retry ${Ee}) \u2014 webpack does not after a failure like this`)}_({success:!1});return}x.succeeded();const N=w.hasErrors();if(console.info(w.toString({colors:!0,chunks:!1,assets:!0})),N){_({success:!1});return}Y(),_({success:!0,baseUrl:`http://localhost:${d}`})},"onBuild");if(frozen()){console.log(`[serve] ${o.projectName}: frozen \u2014 compiling once, no file watcher`),T.run((p,w)=>{ie(p,w),T.close(()=>{})});return}E=T.watch(u.watchOptions||{},ie),b=s(()=>{x.dispose(),E?.close(()=>{})},"closeBuild")}i(C,"L"),s(C,"compileOnItsOwn");function ne(r){const v=r.accepted.projects.filter(t=>t!==o.projectName);console.log(`[serve] ${o.projectName}: compiled by the workspace's shared compilation ${r.accepted.group.slice(0,8)}${v.length?` with ${v.join(", ")}`:""} \u2014 no webpack in this process`);const c=new devserver_notifier_1.DevserverNotifier(d,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(a)),u=(0,attach_1.createAttachedTypecheck)({appName:o.projectName,tsConfig:oe,workspaceRoot:n,memoryLimit:e.memoryLimit||8192});let f;b=s(()=>{r.close(),u.dispose()},"closeBuild"),r.listen(t=>{if(!h)switch(t.type){case"watch-run":c.watchRun(t.paths);return;case"watch-closed":c.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${t.message}`),c.failed(`the shared compiler failed: ${t.message}`),_({success:!1});return;case"refused":console.log(`[serve] ${o.projectName}: compiling on its own from now on \u2014 ${t.reason}`),b(),C();return;case"built":{if(console.info(t.text),B=t.sourceMaps,u.built(t),!t.ok){c.failed(),_({success:!1});return}const z=t.hash!==f;f=t.hash;const K=Y();c.built(z&&!K),_({success:!0,baseUrl:`http://localhost:${d}`});return}default:return}})}if(i(ne,"fe"),s(ne,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const r=await(0,attach_1.joinSharedBuild)({project:o.projectName,target:o.targetName??"serve-hmr",...o.configurationName?{configuration:o.configurationName}:{},options:m,targetOptions:{...e},env:definedEnv(process.env)});r.kind==="attached"?ne(r.session):(console.log(`[serve] ${o.projectName}: compiling on its own \u2014 ${r.reason}`),C())}else C();try{for(;;)yield await se()}finally{R(),b(),he()}}i(serveExecutor,"serveExecutor"),s(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
1
+ "use strict";var _e=Object.defineProperty;var i=(e,o)=>_e(e,"name",{value:o,configurable:!0});var ve=Object.defineProperty,s=i((e,o)=>ve(e,"name",{value:o,configurable:!0}),"s");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")),node_child_process_1=require("node:child_process"),yaml=tslib_1.__importStar(require("js-yaml")),child_process_env_1=require("../../child-process-env"),dev_devtool_1=require("../../dev-devtool"),devserver_host_1=require("../../devserver-host"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach"),stop_on_signal_1=require("./stop-on-signal"),compile_retry_1=require("../../compile-retry"),config_files_1=require("../../config-files"),signature_1=require("../../shared-build/signature");function definedEnv(e){const o={};for(const[j,n]of Object.entries(e))typeof n=="string"&&(o[j]=n);return o}i(definedEnv,"definedEnv"),s(definedEnv,"definedEnv");const frozen=s(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,o){process.env.NODE_ENV="development";const j=o.projectsConfigurations.projects[o.projectName],n=o.root,S=path.join(n,j.root),Q=e.outputPath?path.join(n,e.outputPath):path.join(n,"dist",j.root),ee=e.configEnv||"development",A=path.join(n,"config",`config.${ee}.yaml`),q=3050;let u=q,a=o.projectName,O={};fs.existsSync(A)?(O=yaml.load(fs.readFileSync(A,"utf8")),u=Number(O.port)||u,a=O.serviceName||a):e.port||console.warn(`[serve] ${o.projectName}: no config file at ${A} \u2014 public devserver port defaults to ${q}. If another service also lacks its config, both bind ${q} \u2192 EADDRINUSE. Add config/config.${ee}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(a=e.serviceName),e.port&&(u=e.port);const I=e.servePrefix??"",y=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),ce=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),g=e.logFile?path.resolve(n,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(g){fs.mkdirSync(path.dirname(g),{recursive:!0}),fs.writeFileSync(g,"",{mode:384});try{fs.chmodSync(g,384)}catch{}}let M,F;e.gateway?.middleware&&(M=path.resolve(S,e.gateway.middleware),F=JSON.stringify(O));const ae=e.entryFile||"./src/deployments/service/main.ts",le=e.tsConfigFile||"./tsconfig.app.json",ue=path.resolve(S,ae),oe=path.resolve(S,le),pe=(e.workers||[]).map(r=>({entryName:r.name,entryPath:path.resolve(S,r.entryPath)})),m={appName:o.projectName,appRoot:S,outputDir:Q,main:ue,tsConfig:oe,assets:e.assets||[],additionalEntryPoints:pe,port:u,serviceName:a,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:n,orgScopes:e.orgScopes||[],bundlePackages:e.bundlePackages||[],nodeExternalsConfig:e.nodeExternalsConfig,webpackConfigPath:e.webpackConfigPath,httpsReload:e.gateway?.https===!0,...e.devtool!==void 0&&{devtool:e.devtool}};let l=null,U=!1,G=!1,B=!1,h=!1;const re=path.join(__dirname,"../../main.devserver.js"),te=path.join(__dirname,"../../main.devserver.ts"),W=!fs.existsSync(re)&&fs.existsSync(te),L=W?te:re,de=path.join(Q,"main.js");function H(){l&&!l.killed&&(l.kill("SIGTERM"),l=null)}i(H,"Q"),s(H,"cleanup");function R(){h=!0,H()}i(R,"W"),s(R,"stop");const he=(0,stop_on_signal_1.stopOnSignal)({stop:R,close:s(()=>b(),"close")});process.on("exit",R);function P(){if(h||U)return;if(!fs.existsSync(L)){console.error(`[serve] devserver script not found at ${L}`);return}const r=(0,child_process_env_1.childProcessEnv)({...process.env,PORT:String(u),SERVICE_NAME:a,SERVE_PREFIX:I,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||o.projectName||a,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(n,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:de,...M&&{GATEWAY_MIDDLEWARE:M},...F&&{GATEWAY_CONFIG:F},...e.gateway?.routes?.length&&{GATEWAY_ROUTES:JSON.stringify(e.gateway.routes)},...e.gateway?.https&&{GATEWAY_HTTPS:"1"},...e.gateway?.extraPorts?.length&&{GATEWAY_EXTRA_PORTS:JSON.stringify(e.gateway.extraPorts)},...e.internalPort&&{INTERNAL_PORT:String(e.internalPort)},...y&&{LENSMCP_DEBUG_PORT:String(y)},...g&&{LENSMCP_LOG_FILE:g},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:B?"1":"0"});if((0,devserver_host_1.devserverInProcessOffered)()&&(!W||require.extensions[".ts"])){U=!0;for(const[p,f]of Object.entries(r))f!==void 0&&(process.env[p]=f);(0,devserver_host_1.markDevserverInProcess)(),require(L),J("in this process");return}const v=["--enable-source-maps"];W&&v.unshift("--require","@swc-node/register");const c=(0,node_child_process_1.fork)(L,{cwd:n,env:r,stdio:["inherit","inherit","inherit","ipc"],execArgv:v,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(n),a,"dev"))});l=c,c.on("exit",(p,f)=>{l===c&&(l=null),!(f||p===0||h)&&(console.error(`[serve] devserver exited unexpectedly (code=${p}, signal=${f}) \u2014 respawning in 1.5s`),setTimeout(()=>{!h&&!l&&G&&P()},1500).unref?.())}),J()}i(P,"j"),s(P,"startDevServer");function J(r){console.log(`[serve] Devserver started on port ${u} (service: ${a}${I?`, prefix: /${I}`:""}${r?`, ${r}`:""})`),y?(console.warn(`[serve] DEBUGGER ENABLED for ${a}. Node's inspector has NO authentication \u2014 the ws:// UUID is the whole credential, and any account on this host that obtains it runs code as you. Do not enable this on a shared machine.`),ce?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${y}+slot (workers ${y}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${y}. Unset it to bind ephemeral ports instead.`):console.log(`[serve] Debug: pod inspectors bind an EPHEMERAL 127.0.0.1 port. Get the ws:// URLs with \`lensmcp debug ${a}\` (the owner-only control socket); a devserver run in your own terminal also prints them there. Set LENSMCP_DEBUG_FIXED_PORTS=1 if your IDE needs a fixed attach port.`)):console.log(`[serve] Debug on demand: \`lensmcp debug ${a}\` opens pod inspectors without a restart`),g&&console.log(`[serve] Logs teed to ${g} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}i(J,"ee"),s(J,"announceDevServer");function fe(){if(!l||l.killed){console.log("[serve] Devserver not running, restarting..."),P();return}fetch(`http://localhost:${u}/webpack/reload`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(()=>console.log("[serve] Notified devserver to reload")).catch(r=>{console.warn("[serve] Failed to notify devserver, restarting...",r.message),H(),P()})}i(fe,"me"),s(fe,"_notifyDevServerReload");let D=null;const V=[];function _(r){if(D){const v=D;D=null,v(r)}else V.push(r)}i(_,"w"),s(_,"pushResult");function se(){return V.length>0?Promise.resolve(V.shift()):new Promise(r=>{D=r})}i(se,"de"),s(se,"waitForNext");let b=s(()=>{},"closeBuild");function Y(){return!G||!l&&!U?(G=!0,P(),!0):!1}i(Y,"re"),s(Y,"builtOk");function X(){try{return JSON.stringify((0,signature_1.transpileCompilerOptions)(m.tsConfig,n))}catch{return}}i(X,"te"),s(X,"compileShape");function C(){if(h)return;const{createDevWebpackConfig:r}=require("../../create-webpack-dev"),v=require("webpack"),c=m.webpackConfigPath?path.resolve(m.appRoot,m.webpackConfigPath):void 0;if(c)try{delete require.cache[require.resolve(c)]}catch{}const p=r(m),{watch:f,...t}=p,z=(0,config_files_1.configFilesOf)(m),K=X(),{TsgoCheckPlugin:ge}=require("../../tsgo-check-plugin"),me=process.env.LENSMCP_TYPECHECK!=="off"&&!(t.plugins??[]).some(d=>d instanceof ge);let $,Z=!1;t.plugins=[...t.plugins??[],new config_files_1.ConfigFilesPlugin({files:s(()=>z,"files"),changed:s(d=>{let w=!1;if(!c||!d.includes(c)){const N=X();if(N===void 0)return;if(N===K){if(!me||d.every(k=>k===m.tsConfig))return;w=!0}}Z=($===void 0||Z)&&w,$=d.map(N=>path.relative(n,N)).sort().join(", ")},"changed")})];const T=v(t);B=(0,dev_devtool_1.bundleCarriesSourceMaps)(T.options.devtool);let E;const x=(0,compile_retry_1.createFailureRetry)(()=>{h||!E||(console.log(`[serve] ${o.projectName}: compiling again after the failure`),E.invalidate())}),ie=s((d,w)=>{if($!==void 0&&E&&!h){console.log(Z?`[serve] ${o.projectName}: ${$} changed what it type-checks with \u2014 fork-ts-checker reads that only when it starts, so a new compiler checks it`:`[serve] ${o.projectName}: ${$} changed what it compiles with \u2014 compiling again with a new compiler`),x.dispose();const k=E;E=void 0,setImmediate(()=>k.close(()=>C()));return}if(d){if(console.error("[serve] Webpack error:",d),E&&!h){const{delayMs:k,retry:Ee}=x.failed();console.log(`[serve] ${o.projectName}: compiling again in ${Math.round(k/1e3)} s (retry ${Ee}) \u2014 webpack does not after a failure like this`)}_({success:!1});return}x.succeeded();const N=w.hasErrors();if(console.info(w.toString({colors:!0,chunks:!1,assets:!0})),N){_({success:!1});return}Y(),_({success:!0,baseUrl:`http://localhost:${u}`})},"onBuild");if(frozen()){console.log(`[serve] ${o.projectName}: frozen \u2014 compiling once, no file watcher`),T.run((d,w)=>{ie(d,w),T.close(()=>{})});return}E=T.watch(p.watchOptions||{},ie),b=s(()=>{x.dispose(),E?.close(()=>{})},"closeBuild")}i(C,"L"),s(C,"compileOnItsOwn");function ne(r){const v=r.accepted.projects.filter(t=>t!==o.projectName);console.log(`[serve] ${o.projectName}: compiled by the workspace's shared compilation ${r.accepted.group.slice(0,8)}${v.length?` with ${v.join(", ")}`:""} \u2014 no webpack in this process`);const c=new devserver_notifier_1.DevserverNotifier(u,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(a)),p=(0,attach_1.createAttachedTypecheck)({appName:o.projectName,tsConfig:oe,workspaceRoot:n,memoryLimit:e.memoryLimit||8192});let f;b=s(()=>{r.close(),p.dispose()},"closeBuild"),r.listen(t=>{if(!h)switch(t.type){case"watch-run":c.watchRun(t.paths);return;case"watch-closed":c.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${t.message}`),c.failed(`the shared compiler failed: ${t.message}`),_({success:!1});return;case"refused":console.log(`[serve] ${o.projectName}: compiling on its own from now on \u2014 ${t.reason}`),b(),C();return;case"built":{if(console.info(t.text),B=t.sourceMaps,p.built(t),!t.ok){c.failed(),_({success:!1});return}const z=t.hash!==f;f=t.hash;const K=Y();c.built(z&&!K),_({success:!0,baseUrl:`http://localhost:${u}`});return}default:return}})}if(i(ne,"fe"),s(ne,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const r=await(0,attach_1.joinSharedBuild)({project:o.projectName,target:o.targetName??"serve-hmr",...o.configurationName?{configuration:o.configurationName}:{},options:m,targetOptions:{...e},env:definedEnv(process.env)});r.kind==="attached"?ne(r.session):(console.log(`[serve] ${o.projectName}: compiling on its own \u2014 ${r.reason}`),C())}else C();try{for(;;)yield await se()}finally{R(),b(),he()}}i(serveExecutor,"serveExecutor"),s(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
@@ -0,0 +1,19 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import type { TrustExecutorSchema } from './schema';
3
+ /**
4
+ * Trust without `nx run` (planning/global G4, zero-touch): `node <@lensmcp/cluster>/executors/trust/run.js --root
5
+ * <workspace> [--project <p>] [--target <t>]`. The options are the workspace's `@lensmcp/cluster:trust` target's when it
6
+ * declares one; a workspace with only a `lensmcp.json` trusts the hosts its services declare.
7
+ */
8
+ export declare const TRUST_EXECUTOR = "@lensmcp/cluster:trust";
9
+ export type TrustPlan = {
10
+ ok: true;
11
+ options: TrustExecutorSchema;
12
+ context: ExecutorContext;
13
+ from: string;
14
+ } | {
15
+ ok: false;
16
+ error: string;
17
+ };
18
+ export declare function planTrust(root: string, project?: string, target?: string): TrustPlan;
19
+ export declare function main(argv: readonly string[]): Promise<number>;
@@ -0,0 +1 @@
1
+ "use strict";var j=Object.defineProperty;var c=(r,t)=>j(r,"name",{value:t,configurable:!0});var l=Object.defineProperty,u=c((r,t)=>l(r,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TRUST_EXECUTOR=void 0,exports.planTrust=planTrust,exports.main=main;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),daemon_1=require("../gateway/daemon");exports.TRUST_EXECUTOR="@lensmcp/cluster:trust";function planTrust(r,t,n){const s=(0,daemon_1.lensmcpJsonProblem)(r);if(s)return{ok:!1,error:s};const i=(0,daemon_1.readProjectFiles)(r),a=t?i.find(o=>o.name===t):void 0;if(t&&!a)return{ok:!1,error:`no project '${t}' in ${r}`};let e;for(const o of a?[a]:i){for(const[p,f]of Object.entries(o.targets))if(!(n?p!==n:f.executor!==exports.TRUST_EXECUTOR)){e={project:o.name,target:p,options:f.options??{}};break}if(e)break}if(!e&&!fs.existsSync(path.join(r,"lensmcp.json")))return{ok:!1,error:`no project in ${r} declares ${exports.TRUST_EXECUTOR}, and it has no lensmcp.json`};const m={root:r,cwd:r,isVerbose:!1,...e?{projectName:e.project,targetName:e.target}:{},projectsConfigurations:{version:2,projects:Object.fromEntries(i.map(o=>[o.name,{root:o.root,targets:o.targets}]))}};return{ok:!0,options:e?.options??{},context:m,from:e?`${e.project}:${e.target}`:"lensmcp.json"}}c(planTrust,"planTrust"),u(planTrust,"planTrust");async function main(r){const t=u(a=>{const e=r.indexOf(a);return e>=0?r[e+1]:void 0},"value"),n=t("--root");if(!n)return console.error("usage: run.js --root <workspace> [--project <p>] [--target <t>]"),2;const s=planTrust(path.resolve(n),t("--project"),t("--target"));if("error"in s)return console.error(`[trust] ${s.error}`),1;const{default:i}=require("./trust.impl");return(await i(s.options,s.context)).success?0:1}c(main,"main"),u(main,"main"),require.main===module&&main(process.argv.slice(2)).then(r=>process.exit(r),r=>{console.error(r instanceof Error?r.stack??r.message:String(r)),process.exit(1)});
@@ -1,6 +1,6 @@
1
- "use strict";var f=Object.defineProperty;var l=(r,t)=>f(r,"name",{value:t,configurable:!0});var h=Object.defineProperty,d=l((r,t)=>h(r,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=trustExecutor,exports.missingHostLines=missingHostLines,exports.collectHosts=collectHosts;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),node_dns_1=require("node:dns"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),basic_ssl_1=require("../../basic-ssl"),checkout_cache_1=require("../../checkout-cache"),hostname_1=require("./hostname");async function trustExecutor(r,t){const e=(0,checkout_cache_1.checkoutCacheDir)(t.root,"davnx-webpack"),n=(0,basic_ssl_1.ensureCaSync)(e),c=process.env.LENSMCP_TRUST_HOSTS_ONLY==="1",s=collectHosts(r,t);if(s.length===0&&console.log("[trust] no concrete hostnames found (only wildcards?) \u2014 keychain step only."),process.platform!=="darwin"){console.log("[trust] non-macOS platform \u2014 do these manually:"),console.log(` \u2022 trust ${n} in your OS/browser store (Linux: update-ca-certificates / certutil)`);for(const p of s)console.log(` \u2022 /etc/hosts: "127.0.0.1 ${p}" and "::1 ${p}"`);return{success:!0}}const o=caSha256Fingerprint(n),a=c||o!==void 0&&(0,node_child_process_1.spawnSync)("security",["find-certificate","-a","-c","lensmcp local dev CA","-Z","/Library/Keychains/System.keychain"],{encoding:"utf8"}).stdout?.includes(o)===!0;if(c)console.log("[trust] hosts-only: a shared daemon serves TLS with its own CA \u2014 skipping the keychain step.");else if(a)console.log("[trust] CA already in the System keychain \u2014 skipping.");else{if(console.log(`[trust] adding CA to the System keychain (sudo will prompt): ${n}`),(0,node_child_process_1.spawnSync)("sudo",["security","add-trusted-cert","-d","-r","trustRoot","-k","/Library/Keychains/System.keychain",n],{stdio:"inherit"}).status!==0)return console.error("[trust] add-trusted-cert failed \u2014 rerun in a terminal so sudo can prompt."),{success:!1};console.log("[trust] CA trusted. Restart your browser once (it caches certificate verdicts).")}const u=fs.readFileSync("/etc/hosts","utf8"),i=missingHostLines(s,u,await resolveAll(s));if(i.length===0)console.log("[trust] /etc/hosts already complete (both families for every hostname, by a line or by the OS resolver).");else{if(console.log(`[trust] appending to /etc/hosts (sudo):
2
- ${i.join(`
3
- `)}`),(0,node_child_process_1.spawnSync)("sudo",["tee","-a","/etc/hosts"],{input:i.join(`
1
+ "use strict";var y=Object.defineProperty;var f=(r,e)=>y(r,"name",{value:e,configurable:!0});var h=Object.defineProperty,u=f((r,e)=>h(r,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=trustExecutor,exports.missingHostLines=missingHostLines,exports.collectHosts=collectHosts;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),services_decl_1=require("../gateway/runtime/services-decl"),node_dns_1=require("node:dns"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),basic_ssl_1=require("../../basic-ssl"),checkout_cache_1=require("../../checkout-cache"),hostname_1=require("./hostname");async function trustExecutor(r,e){const t=(0,checkout_cache_1.checkoutCacheDir)(e.root,"davnx-webpack"),n=(0,basic_ssl_1.ensureCaSync)(t),i=process.env.LENSMCP_TRUST_HOSTS_ONLY==="1",s=collectHosts(r,e);if(s.length===0&&console.log("[trust] no concrete hostnames found (only wildcards?) \u2014 keychain step only."),process.platform!=="darwin"){console.log("[trust] non-macOS platform \u2014 do these manually:"),console.log(` \u2022 trust ${n} in your OS/browser store (Linux: update-ca-certificates / certutil)`);for(const c of s)console.log(` \u2022 /etc/hosts: "127.0.0.1 ${c}" and "::1 ${c}"`);return{success:!0}}const a=caSha256Fingerprint(n),o=i||a!==void 0&&(0,node_child_process_1.spawnSync)("security",["find-certificate","-a","-c","lensmcp local dev CA","-Z","/Library/Keychains/System.keychain"],{encoding:"utf8"}).stdout?.includes(a)===!0;if(i)console.log("[trust] hosts-only: a shared daemon serves TLS with its own CA \u2014 skipping the keychain step.");else if(o)console.log("[trust] CA already in the System keychain \u2014 skipping.");else{if(console.log(`[trust] adding CA to the System keychain (sudo will prompt): ${n}`),(0,node_child_process_1.spawnSync)("sudo",["security","add-trusted-cert","-d","-r","trustRoot","-k","/Library/Keychains/System.keychain",n],{stdio:"inherit"}).status!==0)return console.error("[trust] add-trusted-cert failed \u2014 rerun in a terminal so sudo can prompt."),{success:!1};console.log("[trust] CA trusted. Restart your browser once (it caches certificate verdicts).")}const d=fs.readFileSync("/etc/hosts","utf8"),l=missingHostLines(s,d,await resolveAll(s));if(l.length===0)console.log("[trust] /etc/hosts already complete (both families for every hostname, by a line or by the OS resolver).");else{if(console.log(`[trust] appending to /etc/hosts (sudo):
2
+ ${l.join(`
3
+ `)}`),(0,node_child_process_1.spawnSync)("sudo",["tee","-a","/etc/hosts"],{input:l.join(`
4
4
  `)+`
5
- `,stdio:["pipe","ignore","inherit"]}).status!==0)return console.error("[trust] /etc/hosts update failed."),{success:!1};(0,node_child_process_1.spawnSync)("sudo",["dscacheutil","-flushcache"],{stdio:"inherit"}),(0,node_child_process_1.spawnSync)("sudo",["killall","-HUP","mDNSResponder"],{stdio:"inherit"})}if(!c){const p=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",n,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${p.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const p of s)console.log(`[trust] ${p} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}l(trustExecutor,"trustExecutor"),d(trustExecutor,"trustExecutor");function caSha256Fingerprint(r){const t=(0,node_child_process_1.spawnSync)("openssl",["x509","-in",r,"-noout","-fingerprint","-sha256"],{encoding:"utf8"});if(t.status!==0||!t.stdout)return;const e=t.stdout.split("=")[1]?.replaceAll(":","").trim().toUpperCase();return e&&/^[0-9A-F]{64}$/.test(e)?e:void 0}l(caSha256Fingerprint,"caSha256Fingerprint"),d(caSha256Fingerprint,"caSha256Fingerprint");function missingHostLines(r,t,e){const n=d((s,o)=>t.split(`
6
- `).some(a=>{const u=a.trim();if(u.startsWith("#"))return!1;const i=u.split(/\s+/);return i[0]===s&&i.slice(1).includes(o)}),"hasEntry"),c=[];for(const s of r)!n("127.0.0.1",s)&&!e.get(s)?.v4&&c.push(`127.0.0.1 ${s}`),!n("::1",s)&&!e.get(s)?.v6&&c.push(`::1 ${s}`);return c}l(missingHostLines,"missingHostLines"),d(missingHostLines,"missingHostLines");async function resolveAll(r){const t=d(e=>new Promise(n=>{const c=setTimeout(()=>n({v4:!1,v6:!1}),2e3);(0,node_dns_1.lookup)(e,{all:!0},(s,o)=>{if(clearTimeout(c),s||!Array.isArray(o))return n({v4:!1,v6:!1});n({v4:o.some(a=>a.family===4&&a.address.startsWith("127.")),v6:o.some(a=>a.family===6&&a.address==="::1")})})}),"one");return new Map(await Promise.all(r.map(async e=>[e,await t(e)])))}l(resolveAll,"resolveAll"),d(resolveAll,"resolveAll");function collectHosts(r,t){const e=[],n=t.projectName?t.projectsConfigurations?.projects[t.projectName]:void 0,c=r.serveTarget??"serve-hmr",s=n?.targets?.[c]?.options?.gateway?.routes??[];for(const o of s)o.host&&(0,hostname_1.isValidHostname)(o.host)?e.push(o.host):o.host&&console.warn(`[trust] ignoring invalid hostname in ${c} routes: ${JSON.stringify(o.host)}`);for(const o of Object.values(t.projectsConfigurations?.projects??{}))try{const a=JSON.parse(fs.readFileSync(path.join(t.root,o.root,"project.json"),"utf8")),u=a.cluster??a.davnx,i=u?.host;i&&!(0,hostname_1.isValidHostname)(i)&&console.warn(`[trust] ignoring invalid hostname in ${o.root}/project.json: ${JSON.stringify(i)}`),i&&(0,hostname_1.isValidHostname)(i)&&(e.push(i),u?.service&&u.internalHost!==!1&&e.push(typeof u.internalHost=="string"?u.internalHost:`internal.${i}`))}catch{}return[...new Set([...e,"lensmcp.local",...r.hosts??[]])]}l(collectHosts,"collectHosts"),d(collectHosts,"collectHosts");
5
+ `,stdio:["pipe","ignore","inherit"]}).status!==0)return console.error("[trust] /etc/hosts update failed."),{success:!1};(0,node_child_process_1.spawnSync)("sudo",["dscacheutil","-flushcache"],{stdio:"inherit"}),(0,node_child_process_1.spawnSync)("sudo",["killall","-HUP","mDNSResponder"],{stdio:"inherit"})}if(!i){const c=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",n,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${c.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const c of s)console.log(`[trust] ${c} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}f(trustExecutor,"trustExecutor"),u(trustExecutor,"trustExecutor");function caSha256Fingerprint(r){const e=(0,node_child_process_1.spawnSync)("openssl",["x509","-in",r,"-noout","-fingerprint","-sha256"],{encoding:"utf8"});if(e.status!==0||!e.stdout)return;const t=e.stdout.split("=")[1]?.replaceAll(":","").trim().toUpperCase();return t&&/^[0-9A-F]{64}$/.test(t)?t:void 0}f(caSha256Fingerprint,"caSha256Fingerprint"),u(caSha256Fingerprint,"caSha256Fingerprint");function missingHostLines(r,e,t){const n=u((s,a)=>e.split(`
6
+ `).some(o=>{const d=o.trim();if(d.startsWith("#"))return!1;const l=d.split(/\s+/);return l[0]===s&&l.slice(1).includes(a)}),"hasEntry"),i=[];for(const s of r)!n("127.0.0.1",s)&&!t.get(s)?.v4&&i.push(`127.0.0.1 ${s}`),!n("::1",s)&&!t.get(s)?.v6&&i.push(`::1 ${s}`);return i}f(missingHostLines,"missingHostLines"),u(missingHostLines,"missingHostLines");async function resolveAll(r){const e=u(t=>new Promise(n=>{const i=setTimeout(()=>n({v4:!1,v6:!1}),2e3);(0,node_dns_1.lookup)(t,{all:!0},(s,a)=>{if(clearTimeout(i),s||!Array.isArray(a))return n({v4:!1,v6:!1});n({v4:a.some(o=>o.family===4&&o.address.startsWith("127.")),v6:a.some(o=>o.family===6&&o.address==="::1")})})}),"one");return new Map(await Promise.all(r.map(async t=>[t,await e(t)])))}f(resolveAll,"resolveAll"),u(resolveAll,"resolveAll");function collectHosts(r,e){const t=[],n=e.projectName?e.projectsConfigurations?.projects[e.projectName]:void 0,i=r.serveTarget??"serve-hmr",s=n?.targets?.[i]?.options?.gateway?.routes??[];for(const o of s)o.host&&(0,hostname_1.isValidHostname)(o.host)?t.push(o.host):o.host&&console.warn(`[trust] ignoring invalid hostname in ${i} routes: ${JSON.stringify(o.host)}`);const{services:a}=(0,services_decl_1.lensmcpServices)(e.root);for(const[o,d]of Object.entries(e.projectsConfigurations?.projects??{}))try{const l=a[o]===void 0?JSON.parse(fs.readFileSync(path.join(e.root,d.root,"project.json"),"utf8")):void 0,{decl:c}=(0,services_decl_1.declFor)(a,o,l),p=c?.host;p&&!(0,hostname_1.isValidHostname)(p)&&console.warn(`[trust] ignoring invalid hostname in ${d.root}/project.json: ${JSON.stringify(p)}`),p&&(0,hostname_1.isValidHostname)(p)&&(t.push(p),c?.service&&c.internalHost!==!1&&t.push(typeof c.internalHost=="string"?c.internalHost:`internal.${p}`))}catch{}return[...new Set([...t,"lensmcp.local",...r.hosts??[]])]}f(collectHosts,"collectHosts"),u(collectHosts,"collectHosts");
package/gateway.d.ts CHANGED
@@ -1,21 +1,9 @@
1
1
  /**
2
- * `@lensmcp/cluster/gateway` — the PRODUCTION gateway's public, extendable surface.
3
- *
4
- * This is the **deployable edge** (`startProdGateway` — Fastify + undici reverse
5
- * proxy, manifest-driven, the thing `Dockerfile.prod-gateway` runs). A consumer
6
- * (e.g. tetros' `server/apps/gateway`) imports from here to run or extend it with
7
- * its own providers/middleware and ship a specialized image.
8
- *
9
- * ⚠️ This is NOT the DEV cluster gateway. The dev gateway is the
10
- * `@lensmcp/cluster:gateway` nx EXECUTOR (`gateway.lib.ts` → `startGateway`) — a
11
- * local-only HTTPS front door on :443 that fronts unix-socket pods for
12
- * development. The two share a routing core (`manifest.ts`) but are separate
13
- * lifecycles: dev = an nx target you run locally; prod = a containerized service
14
- * you deploy. Kept on a separate subpath so the build-time webpack-config exports
15
- * in the main `@lensmcp/cluster` entry never pull in fastify/undici.
2
+ * `@lensmcp/cluster/gateway` — the production gateway, which moved to the `edgeward` package. This path re-exports
3
+ * it for one transition release; import from `edgeward` instead.
16
4
  */
17
- export { startProdGateway, type ProdGatewayOptions, type ProdGatewayHandle, type ServiceStatus, } from './executors/gateway/prod-gateway.lib';
18
- export { staticManifestProvider, endpointsPodProvider } from './executors/gateway/providers-prod';
19
- export { createRegistryProviders, redisRegistrySource, type RegistrySource, type RedisLike, DEFAULT_REGISTRY_PREFIX, } from './executors/gateway/registry-source';
20
- export { type RouteManifest, type RouteMount, type AuthMode, type AuthPolicy, type ManifestProvider, type PodProvider, type Upstream, type Route, manifestFromClusterDecl, } from './executors/gateway/manifest';
21
- export { dispatchMiddleware, requestToken, workloadToken, validateMiddleware, type EdgeMiddleware, type EdgeMiddlewareContext, type MiddlewarePhase, type OriginalTokenInput, type WorkspaceAuthModuleV1, } from './executors/gateway/workspace-auth';
5
+ export { startProdGateway, type ProdGatewayOptions, type ProdGatewayHandle, type ServiceStatus, } from 'edgeward';
6
+ export { staticManifestProvider, endpointsPodProvider } from 'edgeward';
7
+ export { createRegistryProviders, redisRegistrySource, type RegistrySource, type RedisLike, DEFAULT_REGISTRY_PREFIX, } from 'edgeward';
8
+ export { type RouteManifest, type RouteMount, type AuthMode, type AuthPolicy, type ManifestProvider, type PodProvider, type Upstream, type Route, manifestFromClusterDecl, } from 'edgeward';
9
+ export { dispatchMiddleware, requestToken, workloadToken, validateMiddleware, type EdgeMiddleware, type EdgeMiddlewareContext, type MiddlewarePhase, type OriginalTokenInput, type WorkspaceAuthModuleV1, } from 'edgeward';
package/gateway.js CHANGED
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var i=(r,t)=>a(r,"name",{value:t,configurable:!0});var o=Object.defineProperty,e=i((r,t)=>o(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateMiddleware=exports.workloadToken=exports.requestToken=exports.dispatchMiddleware=exports.manifestFromClusterDecl=exports.DEFAULT_REGISTRY_PREFIX=exports.redisRegistrySource=exports.createRegistryProviders=exports.endpointsPodProvider=exports.staticManifestProvider=exports.startProdGateway=void 0;var prod_gateway_lib_1=require("./executors/gateway/prod-gateway.lib");Object.defineProperty(exports,"startProdGateway",{enumerable:!0,get:e(function(){return prod_gateway_lib_1.startProdGateway},"get")});var providers_prod_1=require("./executors/gateway/providers-prod");Object.defineProperty(exports,"staticManifestProvider",{enumerable:!0,get:e(function(){return providers_prod_1.staticManifestProvider},"get")}),Object.defineProperty(exports,"endpointsPodProvider",{enumerable:!0,get:e(function(){return providers_prod_1.endpointsPodProvider},"get")});var registry_source_1=require("./executors/gateway/registry-source");Object.defineProperty(exports,"createRegistryProviders",{enumerable:!0,get:e(function(){return registry_source_1.createRegistryProviders},"get")}),Object.defineProperty(exports,"redisRegistrySource",{enumerable:!0,get:e(function(){return registry_source_1.redisRegistrySource},"get")}),Object.defineProperty(exports,"DEFAULT_REGISTRY_PREFIX",{enumerable:!0,get:e(function(){return registry_source_1.DEFAULT_REGISTRY_PREFIX},"get")});var manifest_1=require("./executors/gateway/manifest");Object.defineProperty(exports,"manifestFromClusterDecl",{enumerable:!0,get:e(function(){return manifest_1.manifestFromClusterDecl},"get")});var workspace_auth_1=require("./executors/gateway/workspace-auth");Object.defineProperty(exports,"dispatchMiddleware",{enumerable:!0,get:e(function(){return workspace_auth_1.dispatchMiddleware},"get")}),Object.defineProperty(exports,"requestToken",{enumerable:!0,get:e(function(){return workspace_auth_1.requestToken},"get")}),Object.defineProperty(exports,"workloadToken",{enumerable:!0,get:e(function(){return workspace_auth_1.workloadToken},"get")}),Object.defineProperty(exports,"validateMiddleware",{enumerable:!0,get:e(function(){return workspace_auth_1.validateMiddleware},"get")});
1
+ "use strict";var n=Object.defineProperty;var d=(r,t)=>n(r,"name",{value:t,configurable:!0});var o=Object.defineProperty,e=d((r,t)=>o(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateMiddleware=exports.workloadToken=exports.requestToken=exports.dispatchMiddleware=exports.manifestFromClusterDecl=exports.DEFAULT_REGISTRY_PREFIX=exports.redisRegistrySource=exports.createRegistryProviders=exports.endpointsPodProvider=exports.staticManifestProvider=exports.startProdGateway=void 0;var edgeward_1=require("edgeward");Object.defineProperty(exports,"startProdGateway",{enumerable:!0,get:e(function(){return edgeward_1.startProdGateway},"get")});var edgeward_2=require("edgeward");Object.defineProperty(exports,"staticManifestProvider",{enumerable:!0,get:e(function(){return edgeward_2.staticManifestProvider},"get")}),Object.defineProperty(exports,"endpointsPodProvider",{enumerable:!0,get:e(function(){return edgeward_2.endpointsPodProvider},"get")});var edgeward_3=require("edgeward");Object.defineProperty(exports,"createRegistryProviders",{enumerable:!0,get:e(function(){return edgeward_3.createRegistryProviders},"get")}),Object.defineProperty(exports,"redisRegistrySource",{enumerable:!0,get:e(function(){return edgeward_3.redisRegistrySource},"get")}),Object.defineProperty(exports,"DEFAULT_REGISTRY_PREFIX",{enumerable:!0,get:e(function(){return edgeward_3.DEFAULT_REGISTRY_PREFIX},"get")});var edgeward_4=require("edgeward");Object.defineProperty(exports,"manifestFromClusterDecl",{enumerable:!0,get:e(function(){return edgeward_4.manifestFromClusterDecl},"get")});var edgeward_5=require("edgeward");Object.defineProperty(exports,"dispatchMiddleware",{enumerable:!0,get:e(function(){return edgeward_5.dispatchMiddleware},"get")}),Object.defineProperty(exports,"requestToken",{enumerable:!0,get:e(function(){return edgeward_5.requestToken},"get")}),Object.defineProperty(exports,"workloadToken",{enumerable:!0,get:e(function(){return edgeward_5.workloadToken},"get")}),Object.defineProperty(exports,"validateMiddleware",{enumerable:!0,get:e(function(){return edgeward_5.validateMiddleware},"get")});
package/gc-notice.d.ts CHANGED
@@ -26,9 +26,11 @@ export interface LensGcMark {
26
26
  /** Which collection: pod-memory's trigger (`idle`, `swap+30s`, …), or the recycle bound's `live-heap`. */
27
27
  trigger?: string;
28
28
  gcMs?: number;
29
+ /** How long requests in flight held it back, when they did. */
30
+ deferredMs?: number;
29
31
  }
30
32
  /** Pod: run `gc` with the notice up and the mark set. Returns what `gc` returns. */
31
- export declare function withGcNotice<T>(sockPath: string | undefined, gc: () => T, now?: () => number, trigger?: string): T;
33
+ export declare function withGcNotice<T>(sockPath: string | undefined, gc: () => T, now?: () => number, trigger?: string, deferredMs?: number): T;
32
34
  export declare function clearGcNotice(sockPath: string): void;
33
35
  /** Gateway: is this pod inside a GC it announced, and recently enough to be believed? */
34
36
  export declare function inAnnouncedGc(sockPath: string, now?: number, maxMs?: number): boolean;
package/gc-notice.js CHANGED
@@ -1 +1 @@
1
- "use strict";var _=Object.defineProperty;var o=(e,t)=>_(e,"name",{value:t,configurable:!0});var i=Object.defineProperty,n=o((e,t)=>i(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_GC_MARK=exports.GC_NOTICE_SUFFIX=void 0,exports.gcNoticePath=gcNoticePath,exports.gcNoticeMaxMs=gcNoticeMaxMs,exports.withGcNotice=withGcNotice,exports.clearGcNotice=clearGcNotice,exports.inAnnouncedGc=inAnnouncedGc;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),node_perf_hooks_1=require("node:perf_hooks");exports.GC_NOTICE_SUFFIX=".gc";function gcNoticePath(e){return`${e}${exports.GC_NOTICE_SUFFIX}`}o(gcNoticePath,"gcNoticePath"),n(gcNoticePath,"gcNoticePath");function gcNoticeMaxMs(e=process.env){const t=Number(e.LENSMCP_POD_GC_NOTICE_MAX_MS);return e.LENSMCP_POD_GC_NOTICE_MAX_MS!==void 0&&e.LENSMCP_POD_GC_NOTICE_MAX_MS!==""&&Number.isFinite(t)&&t>=0?t:6e4}o(gcNoticeMaxMs,"gcNoticeMaxMs"),n(gcNoticeMaxMs,"gcNoticeMaxMs"),exports.LENS_GC_MARK=Symbol.for("lensmcp.lensGc");function withGcNotice(e,t,s=Date.now,r){if(e)try{fs.writeFileSync(gcNoticePath(e),String(s()),{mode:384})}catch{}const c={startedAt:node_perf_hooks_1.performance.now(),at:s(),...r?{trigger:r}:{}};globalThis[exports.LENS_GC_MARK]=c;try{return t()}finally{c.endedAt=node_perf_hooks_1.performance.now(),c.gcMs=Math.round(c.endedAt-c.startedAt),e&&clearGcNotice(e)}}o(withGcNotice,"withGcNotice"),n(withGcNotice,"withGcNotice");function clearGcNotice(e){try{fs.unlinkSync(gcNoticePath(e))}catch{}}o(clearGcNotice,"clearGcNotice"),n(clearGcNotice,"clearGcNotice");function inAnnouncedGc(e,t=Date.now(),s=gcNoticeMaxMs()){try{const r=Number(fs.readFileSync(gcNoticePath(e),"utf8").trim());return Number.isFinite(r)&&r>0&&t-r>=0&&t-r<s}catch{return!1}}o(inAnnouncedGc,"inAnnouncedGc"),n(inAnnouncedGc,"inAnnouncedGc");
1
+ "use strict";var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});var _=Object.defineProperty,n=o((e,t)=>_(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_GC_MARK=exports.GC_NOTICE_SUFFIX=void 0,exports.gcNoticePath=gcNoticePath,exports.gcNoticeMaxMs=gcNoticeMaxMs,exports.withGcNotice=withGcNotice,exports.clearGcNotice=clearGcNotice,exports.inAnnouncedGc=inAnnouncedGc;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),node_perf_hooks_1=require("node:perf_hooks");exports.GC_NOTICE_SUFFIX=".gc";function gcNoticePath(e){return`${e}${exports.GC_NOTICE_SUFFIX}`}o(gcNoticePath,"gcNoticePath"),n(gcNoticePath,"gcNoticePath");function gcNoticeMaxMs(e=process.env){const t=Number(e.LENSMCP_POD_GC_NOTICE_MAX_MS);return e.LENSMCP_POD_GC_NOTICE_MAX_MS!==void 0&&e.LENSMCP_POD_GC_NOTICE_MAX_MS!==""&&Number.isFinite(t)&&t>=0?t:6e4}o(gcNoticeMaxMs,"gcNoticeMaxMs"),n(gcNoticeMaxMs,"gcNoticeMaxMs"),exports.LENS_GC_MARK=Symbol.for("lensmcp.lensGc");function withGcNotice(e,t,i=Date.now,r,s){if(e)try{fs.writeFileSync(gcNoticePath(e),String(i()),{mode:384})}catch{}const c={startedAt:node_perf_hooks_1.performance.now(),at:i(),...r?{trigger:r}:{},...s&&s>0?{deferredMs:Math.round(s)}:{}};globalThis[exports.LENS_GC_MARK]=c;try{return t()}finally{c.endedAt=node_perf_hooks_1.performance.now(),c.gcMs=Math.round(c.endedAt-c.startedAt),e&&clearGcNotice(e)}}o(withGcNotice,"withGcNotice"),n(withGcNotice,"withGcNotice");function clearGcNotice(e){try{fs.unlinkSync(gcNoticePath(e))}catch{}}o(clearGcNotice,"clearGcNotice"),n(clearGcNotice,"clearGcNotice");function inAnnouncedGc(e,t=Date.now(),i=gcNoticeMaxMs()){try{const r=Number(fs.readFileSync(gcNoticePath(e),"utf8").trim());return Number.isFinite(r)&&r>0&&t-r>=0&&t-r<i}catch{return!1}}o(inAnnouncedGc,"inAnnouncedGc"),n(inAnnouncedGc,"inAnnouncedGc");
package/main.devserver.js CHANGED
@@ -9,16 +9,16 @@
9
9
  const at = owner && Array.isArray(owner.children) ? owner.children.indexOf(previous) : -1;
10
10
  if (at >= 0) owner.children.splice(at, 1);
11
11
  }
12
- })()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(d,_){let f=null;return(...m)=>{f&&clearTimeout(f),f=setTimeout(()=>d(...m),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const d=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const m=inspector.url();m&&tell(process,{type:"inspector-url",url:m})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&d(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,m=!1,W,re=!1;const Ve=(0,hot_swap_registries_1.registryPruningEnabled)(),ge=a((r,c)=>{const l=(0,hot_swap_registries_1.describePrune)(r,c);l&&console.log(l)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const we=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),C=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const l=c(r);return{count:Number(l?.count??0),...l?.oldestStartedAt?{oldestStartedAt:l.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),$e=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),me=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),be=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[l,h]of r.abandoned)(l.writableEnded||c-h>=Z)&&r.abandoned.delete(l);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const l of r.open??[])l.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:C(r.workGen).count}},"owedBy"),ne=a((r,c,l=`${c}s`)=>`${r} ${r===1?c:l}`,"plural");async function We(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<be);){const l=F.values().next().value;if(!l||l.closed)break;const h=oe(l);if(h.unanswered===0&&h.work===0)break;const E=(l.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(l.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${be} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(v=>{setTimeout(v,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(We,"He"),a(We,"holdForOwedWork");const O=(0,swap_recycle_1.swapRecyclePolicy)();let ye,se=0;const Je=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const S=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let Ee=!1;const B=a(()=>{if(!Ee)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:S,state:a(()=>({gen:j.gen??0,swaps:se,...ye===void 0?{}:{baseline:ye},busy:m||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Oe(),"onRetained"),gc:a(r=>(0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,r),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,"live-heap")&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),U=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,l=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>l.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Te(){if(!(!U||ie))try{const r=U();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Te,"De"),a(Te,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const Fe=a(()=>O.settleMs<=0||!m&&!re&&J.size===0&&Date.now()-D>=O.settleMs,"settled");let Y;function ae(r){if(!(!O.enabled||g||b)){if(O.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,Fe()?X(r):ae(r)},O.settleMs),Y.unref?.()}}u(ae,"_e"),a(ae,"recycleCheckWhenSettled");const ce=a(()=>{if(O.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const l of J.values())r-l>=O.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!O.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,l=a(E=>{const v=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:ce(),settled:Fe(),...ye===void 0?{}:{baselineBytes:ye},...v?{retained:{generation:v.gen,ageMs:Date.now()-v.closedAt,gcs:v.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(O,l(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(O,l(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let le;function Oe(){if(!O.enabled||O.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+O.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}le||(le=setTimeout(()=>{le=void 0,k.measure("retention-check").catch(()=>{})},c),le.unref?.())}u(Oe,"je"),a(Oe,"retainedRecycleCheck");function ve(r,c){const l={};c&&(l.module=c),r&&(l.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(l.nestApp=h,h.container&&typeof h.container=="object")){l.container=h.container;const E=rootModuleOf(h.container);E&&(l.rootModule=E)}}catch{}return l}u(ve,"Ne"),a(ve,"generationTargets");async function de(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const l=O.enabled&&O.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(O.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},O.stuckCloseMs):void 0;l?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),l&&clearTimeout(l),r.app=null,r.abandoned=void 0,r.handler=(E,v)=>{v.statusCode=503,v.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,ve(h,r.module)),r.module=void 0}if(r.superseded){try{ge((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(de,"me"),a(de,"closeGeneration");async function pe(r){const c=Date.now();r.drainingSince=c;const l=a(()=>({inflight:r.inflight+V(r),work:C(r.workGen).count}),"busy"),h=l();if(h.inflight>0||h.work>0){for(;F.size>=be;){const I=F.values().next().value;if(!I)break;const $=oe(I),z=Math.round((Date.now()-(I.drainingSince??c))/1e3);if($.unanswered===0&&$.streams===0&&$.work===0){await de(I);continue}await de(I,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${be} (each holds a whole app: DI container, DB pool, queue workers). `+($.unanswered>0||$.work>0?`It was replaced ${z}s ago and had still not answered ${ne($.unanswered,"request")}`+($.work?` or finished ${ne($.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne($.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;we>0&&Date.now()-c<we;){if(r.closed)return;const I=l();if(I.inflight===0&&I.work===0)break;await new Promise($=>{setTimeout($,250).unref?.()})}if(r.closed)return;const E=l(),v=me(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(v?`Previous app still processing ${v.running} queue job(s); ${v.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${we}ms) if this is legitimate work.`):(Date.now()-c>250||v?.runningAtStop||v?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(v?` (it finished ${v.finishedAfterStop} queue job(s) after the swap; ${v.takenAfterStop} were taken after the swap)`:"")),await de(r)}u(pe,"ye"),a(pe,"drainThenClose");async function ue(){if(m)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;m=!0,D=Date.now(),await We(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Ve)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,l=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw m=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw m=!1,D=Date.now(),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'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),ge((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw m=!1,D=Date.now(),takeImportedModule(),P}const v=j;h?.size&&(v.app?v.superseded=h:ge((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const I=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...I?{module:I}:{},...l===void 0?{}:{workGen:l}};const $=ve(E,void 0).container;$&&(x.add(new WeakRef($)),Ee=!0);const z=v.app&&l!==void 0?$e(l):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Te(),v.app&&(se+=1,pe(v).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(v.gen,()=>v.closed===!0&&!J.has(v))),m=!1,D=Date.now(),re?(re=!1,ue()):E}u(ue,"Ee"),a(ue,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await ue()}catch(r){console.error("[child] reload failed:",r)}},250),he=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const h=r.headers["x-internal-token"],E=process.env.LENSMCP_SERVICE_KEY;if(E&&h!==E){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const v=C();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:m,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:v.count,oldestWorkAt:v.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const l=j;l.inflight+=1,(l.open??=new Set).add(c),l.oldestAt===void 0&&(l.oldestAt=Date.now()),c.on("close",()=>{l.inflight-=1,l.open?.delete(c),Z>0&&!l.closed&&!c.headersSent&&!c.writableEnded&&((l.abandoned??=new Map).set(c,Date.now()),l.abandoned.size>256&&V(l)),l.inflight===0&&(l.oldestAt=void 0),k.activity()}),l.handler(r,c)});he.keepAliveTimeout=0;const N=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(N),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const l=(0,schema_first_instance_1.prewarmZodFor)(r);l?.created&&console.log(`[child] zod${l.version?` ${l.version}`:""}: built ${l.created} throwaway schemas first, so none of the bundle's own is the first of its class`)}catch{}if((0,redis_disconnect_fix_1.redisDisconnectFixEnabled)())try{const l=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);l?.patched&&console.log(`[child] ioredis${l.versions.length?` ${l.versions.join(", ")}`:""}: a disconnect() between reconnect attempts now ends the client \u2014 it used to leave a queue worker's close() waiting for good`)}catch{}await ue(),ye=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock(N);let c=!1;he.on("error",l=>{if(c){console.error("[child] server error:",l);return}console.error(`[child] could not listen on ${N} (${l.code??l.message}) \u2014 exiting; the devserver starts another pod`),tell(process,{type:"boot-error",error:`could not listen on ${N}: ${String(l?.stack||l)}`}),cleanupSock(N),process.exitCode=1,setTimeout(()=>process.exit(1),100)}),he.listen(N,()=>{c=!0,console.log(`[child] Listening on ${N}`),tell(process,{type:"ready",socketPath:N})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);d(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){q();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await ue(),tell(process,{type:"reloaded",socketPath:N,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(l=>{tell(process,{type:"heap-snapshot-result",id:r.id,...l})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const l=H(),h=k.tracker.views().map($=>$.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const v=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:l,...r.available?{available:r.available}:{}});if(v)return c({ok:!1,refused:v,live:l});console.log(`[child] writing a heap snapshot (${Math.round(l/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const I=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:I.bytes,ms:I.ms,live:l,gen:j.gen??0,closedAlive:h})}catch(l){c({ok:!1,error:l?.message??String(l)})}finally{Se=!1}}u(Me,"Ye"),a(Me,"takeHeapSnapshot");async function q(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename(N,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=$e(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(N),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Je).unref?.()}),cleanupSock(N),he.close();const l=Date.now();for(;Date.now()-l<we;){he.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&C().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(q,"B"),a(q,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const fe=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),l=new Promise(h=>he.close(()=>h()));cleanupSock(N),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,l]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){q("this generation was handed over to a newer one");return}inspector?.close?.(),fe(r)})})})()}else{let d=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),be?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const S=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(S):S)}catch{oe.delete(b)}},"ge");a(d,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",m=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ve="\x1B[0m",ge=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),we=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let C=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const $e=20;C&&(console.warn("[parent] DEBUGGER ENABLED \u2014 pods and workers open a Node inspector. Node's inspector has NO authentication: the ws:// URL's UUID is the whole credential, and any account on this host that obtains it can run code as you. Do not enable this on a shared machine. (issues/closed/codex-security-06)"),console.warn(usesFixedInspectorPorts()?`[parent] ${exports.DEBUG_FIXED_PORTS_ENV} is set \u2014 inspectors bind PREDICTABLE ports (${C}+slot, workers ${C}+${$e}+i). Any account on this host can connect to 127.0.0.1:${C} and read the session UUID from /json/list. Unset it to use ephemeral ports.`:`[parent] Inspectors bind an EPHEMERAL loopback port; attach via the printed "Debugger listening" URL, or \`lensmcp debug <service>\` (control socket). Set ${exports.DEBUG_FIXED_PORTS_ENV}=1 for fixed ports if your IDE needs a pre-configured attach port \u2014 any account on this host can then reach them.`));const me=process.env.LENSMCP_LOG_FILE||"",be=me?(()=>{try{fs.mkdirSync(path.dirname(me),{recursive:!0});const g=fs.createWriteStream(me,{flags:"a",mode:384});try{fs.chmodSync(me,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${me}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),S=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(S,ne,x):x)),d(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
13
- `)}}const We=a(g=>re[(g-1)%re.length],"colorFor"),O=a(g=>{if(ge===1)return"";const b=`[child#${g}] `;return`${We(g)}${b}${Ve}`},"tagFor"),ye=a(g=>g.startsWith("{")&&g.endsWith("}"),"isJsonLog"),se=a((g,b,S)=>{const K=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(B=>`
14
- `+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{S?.(k)}catch{}const U=ye(k)?K(k):`${k}
15
- `;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${U}`)),d(`${b}${U}`)},"write"),Ee=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",U=>x(k,U)),H.on("close",()=>{})},"attach");Ee(g.stdout,"stdout"),Ee(g.stderr,"stderr")},"wireProcLogging"),Je=a(g=>se(g.proc,O(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const S=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let Ee=1,B=0,k=!1,H=ge,U=[],ie=0;const Te=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Fe=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return S.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"J"),a(Y,"healthyChildren");let ae,ce=0,X;const le={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Oe(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==ce&&(ce=t.startedAt,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"started",t,{root:process.cwd()})));const s=(0,service_build_events_1.buildAccountOf)(e.failed);s&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"failed",s,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.unchanged);n&&n.startedAt===ce&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"unchanged",n,{root:process.cwd()})))}u(Oe,"je"),a(Oe,"recordBuildProgress");function ve(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Oe(t),"failed"in t&&delete t.failed,"unchanged"in t&&delete t.unchanged,ae=t;for(const s of S)tell(s.proc,{type:"watcher",testimony:t})}}u(ve,"Ne"),a(ve,"recordWatcherTestimony");function de(e,t=256*1024){return new Promise(s=>{let n="",i=!1;e.on("data",o=>{i||(n+=o,n.length>t&&(i=!0))}),e.on("end",()=>{if(i||!n)return s(void 0);try{s(JSON.parse(n))}catch{s(void 0)}}),e.on("error",()=>s(void 0))})}u(de,"me"),a(de,"readJsonBody");function pe(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(pe,"ye"),a(pe,"pickChild");function ue(e,t){const s=`Child#${e.id}`,n=SERVICE_NAME||f,i=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(s,o)}`),m.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:i}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,i))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,i))}}u(ue,"Ee"),a(ue,"recordPodMemory");const Pe=new Map;let he=0;async function N(){const e=Ee++,t=childSockPath(e);cleanupSock(t);const s=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&s.unshift("--require","@swc-node/register"),s.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const n=C?x():-1,i=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...n>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(C,n))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:s,execPath:we("pod")}),o={id:e,proc:i,healthy:!1,lastError:null,debugSlot:n,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return i.on("error",y=>console.error(`[parent] Child#${e}: ${y.message}`)),i.on("message",y=>{if(!y||typeof y!="object")return;const p=y;if(p.type==="ready")o.socketPath=String(p.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),ae&&tell(i,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Te==="process"?P():tell(i,{type:"reload"}));else if(p.type==="recycle-request")v(o,String(p.reason||"it has outgrown its bound"));else if(p.type==="inspector-url")o.inspectorUrl=String(p.url),console.log(`[parent] Child#${o.id} Debugger listening on ${p.url}`);else if(p.type==="reloaded"){if(q.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(p.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=p.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else p.type==="reload-error"?(o.lastError=String(p.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):p.type==="boot-error"?(o.lastError=String(p.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):p.type==="pod-memory"||p.type==="pod-memory-retained"||p.type==="pod-memory-released"?ue(o,p):p.type==="heap-snapshot-result"&&Pe.get(Number(p.id))?.(p)}),i.on("exit",(y,p)=>{o.booting=!1;for(const A of o.memory.retained.values()){const M={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,M)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),M,Date.now()))}o.memory.retained.clear(),o.memory.latest&&m.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:y,signal:p},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=p==="SIGINT"||p==="SIGTERM"||y===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${y}, signal=${p??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${y}, signal=${p??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,y,p,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${y}, signal=${p??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=S.indexOf(o);A>=0&&S.splice(A,1);const M=Date.now();if(U=U.filter(T=>M-T<3e4),U.length>=5){console.error(`[parent] crash-loop detected (${U.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}U.push(M),setTimeout(()=>{const T=S.filter(Q=>Q.proc.killed===!1).length;!k&&T<H&&(console.log(`[parent] respawning a crashed pod (${T}/${H} live)`),N().catch(()=>{}))},1500).unref?.()}}),S.push(o),Je(o),o}u(N,"N"),a(N,"spawnChild");async function Se(e){H=Math.max(H,e);const t=S.filter(n=>n.proc.killed===!1),s=e-t.length;for(let n=0;n<s;n++)await N()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=S.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!Fe(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const s=S.indexOf(t);s>=0&&S.splice(s,1),await N()}))}u(Me,"Ye"),a(Me,"respawnUnhealthy");const q=new Set;let fe=!1,r=0;const c=3e4,l=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const s=Date.now(),n=await N(),i=Date.now()+J;for(;!n.healthy&&!n.lastError&&!D(n)&&Date.now()<i;){if(t.superseded?.()){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${n.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!n.healthy){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${n.id} did not come up (${n.lastError??"no answer in time"})`}}return E(e),{fresh:n,readyMs:Date.now()-s}}u(h,"_"),a(h,"replacePod");function E(e){const t=S.indexOf(e);if(t>=0&&S.splice(t,1),e.healthy=!1,D(e))return;q.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const s=setTimeout(()=>{if(!D(e)){console.error(`[parent] Child#${e.id} was still running ${l}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},l);if(s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),q.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"m"),a(E,"retirePod");async function v(e,t){const s=a(i=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${i}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!S.includes(e))return;if(fe)return s("another pod is already being replaced");const n=Date.now()-r;if(n<c)return s(`a pod was replaced ${Math.round(n/1e3)}s ago`);fe=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const i=await h(e);if("why"in i){i.why!=="shutting down"&&s(i.why);return}r=Date.now(),console.log(`[parent] Child#${i.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${i.fresh.proc.pid})`)}catch(i){s(`could not start a successor: ${i?.message??String(i)}`)}finally{fe=!1}}u(v,"y"),a(v,"recyclePod");let I,$=!1,z=0;function P(){if(I){$=!0;return}I=(async()=>{do{$=!1;const e=ie;for(;fe&&!k;)await new Promise(s=>{setTimeout(s,100).unref?.()});let t=!1;for(const s of Y().filter(n=>n.bootReloadSeq<e)){if(k)break;if(!(!S.includes(s)||!s.healthy)){fe=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${s.id} keeps serving the previous build until it is ready.`);const n=await h(s,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in n){if(n.superseded){z+=1,console.log(`[parent] ${n.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${s.id} keeps serving.`),t=!0;break}n.why!=="shutting down"&&console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 ${n.why}`);continue}z=0,console.log(`[parent] Child#${n.fresh.id} took over from Child#${s.id} with the new build (pid ${s.proc.pid} \u2192 ${n.fresh.proc.pid}, ready in ${(n.readyMs/1e3).toFixed(1)}s while Child#${s.id} served)`),m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(n.fresh),{generation:1,swaps:0,swapMs:n.readyMs,draining:q.size,handoff:{fromPid:s.proc.pid??0}},X,{root:process.cwd()}))}catch(n){console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 could not start a successor: ${n?.message??String(n)}`)}finally{fe=!1}}}t&&($=!0)}while($&&!k)})().finally(()=>{I=void 0})}u(P,"A"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...q].filter(s=>!D(s));for(;t.length>=e;){const s=t.shift();console.error(`[parent] Child#${s.id} (pid ${s.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{s.proc.kill("SIGTERM")}catch{}}}u(ee,"q"),a(ee,"capRetiring");const G=[],He=new Map,Ue=a(e=>{let t=He.get(e);return t||He.set(e,t={crashes:0,restarts:0}),t},"watchOf"),Xe=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),tt=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function ze(e,t){const s=e.name,n=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),i=path.join(n,`${s}.js`),o=Ue(s);if(!fs.existsSync(i))return console.error(`[parent] Worker "${s}" bundle not found: ${i}`),o.missing=i,m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(s,0),{ranMs:0,reason:`its bundle was not built (${path.basename(i)} is not in ${n})`})),null;o.missing=void 0;const y=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&y.unshift("--require","@swc-node/register"),tt&&y.push("--require",tt);try{y.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const p=inspectorPortFor(C||9229,$e+Math.max(0,WORKER_NAMES.indexOf(s)));y.push(C?`--inspect=127.0.0.1:${p}`:`--inspect-port=127.0.0.1:${p}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(i,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:y,execPath:we(`w-${s}`)}),A={name:s,spec:e,proc:w,debugPort:p,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",T=>console.error(`[parent] Worker "${s}": ${T.message}`)),se(w,`\x1B[35m[worker:${s}] \x1B[0m`,T=>{A.tail.push(T);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec(T);Q&&(A.inspectorUrl=Q[1])});const M=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const T=Date.now()-A.startedAt;console.log(`[parent] Worker "${s}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)(T)} without a crash, after ${o.crashes} in a row`),m.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(s,w.pid??0),{ranMs:T,afterCrashes:o.crashes}))}o.crashes=0}},Xe.stableMs);return M.unref?.(),w.on("exit",(T,Q)=>{clearTimeout(M);const ke=G.indexOf(A);ke>=0&&G.splice(ke,1),rt(A,T,Q)}),console.log(`[parent] Worker "${s}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),m.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(s,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(ze,"Ze"),a(ze,"spawnWorkerProcess");function rt(e,t,s){const{name:n}=e,i=e.proc.pid??0,o=Date.now()-e.startedAt,y=(0,worker_supervisor_1.workerExitVerdict)(t,s,e.stopping||k);if(y.kind==="stopped")return;const p=Ue(n);if(y.kind==="exited"){p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${n}" (pid=${i}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,i),{ranMs:o}));return}p.crashes+=1,p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(p.crashes,Xe),A=p.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${n}" crashed (code=${t}, signal=${s??"none"}, pid=${i}, after ${(0,worker_supervisor_1.spanOf)(o)})${y.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${p.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(Xe.maxMs)})`:""}`,t,s,e.tail.snapshot())),m.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(n,i),{code:t,signal:s,ranMs:o,crashes:p.crashes,restarts:p.restarts,nextInMs:w,external:y.external,lines:e.tail.snapshot()})),clearTimeout(p.pending),p.nextAt=Date.now()+w,p.pending=setTimeout(()=>{p.pending=void 0,p.nextAt=void 0,!(k||G.some(M=>M.name===n))&&(p.restarts+=1,qe(e.spec,"respawn"))},w),p.pending.unref?.()}u(rt,"ct"),a(rt,"workerEnded");function qe(e,t){const s=Ue(e.name);s.waiting=void 0;const n=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!n){ze(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${n.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const i=a(()=>{s.waiting===i&&(s.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&ze(e,t)},"go");s.waiting=i,n.proc.once("exit",i)}u(qe,"Ve"),a(qe,"startWorker");const ot=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),nt=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function Be(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(Be,"Je"),a(Be,"killDrainingWorker");function Qe(e){e.stopping=!0,tell(e.proc,{type:worker_retire_1.RETIRE_MESSAGE});try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(n=>n.name===e.name);for(;t.length>=nt;)Be(t.shift(),`was still running when a later reload replaced its successor (cap ${nt})`);te.add(e);const s=setTimeout(()=>Be(e,`was still running ${ot}ms after SIGTERM`),ot);s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),te.delete(e)})}u(Qe,"rt"),a(Qe,"retireWorker");function je(){for(const e of He.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(je,"qe"),a(je,"cancelWorkerStarts");function st(){for(const e of[...G])Qe(e);G.length=0,je();for(const e of WORKER_SPECS)Ue(e.name).crashes=0,qe(e,"reload")}u(st,"lt"),a(st,"restartWorkers");function it(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const s=G.find(o=>o.name===t.name),n=He.get(t.name),i=s?"running":n?.pending?(n.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":n?.waiting?"waiting":n?.missing?"missing":n?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:i,port:t.port,env:Object.keys(t.env),...s?{pid:s.proc.pid,upMs:e-s.startedAt}:{},crashes:n?.crashes??0,restarts:n?.restarts??0,...n?.nextAt?{nextInMs:Math.max(0,n.nextAt-e)}:{},...n?.lastEnd?{lastEnd:n.lastEnd}:{},...n?.missing?{missing:n.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(it,"dt"),a(it,"workersView");const ht=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Te==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&st()},200),at=a((e,t)=>{const s=(0,notice_generation_1.noticeGeneration)(e.headers);return s===void 0||s===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:s})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${s} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ce=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),de(e).then(i=>{const o=i;X=(0,service_build_events_1.buildAccountOf)(o?.build),ce=0,ve(o?.watcher)}),ht();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;const i=await de(e);ve(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let i="";e.on("data",o=>{i+=o}),e.on("end",async()=>{let o=0;try{o=Number(JSON.parse(i||"{}").pods)||0}catch{}o=Math.max(1,Math.min(o,16)),await Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const i=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(i.get("tail")??"100")||0,0),Z),y=i.get("follow")!=="0",p=i.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),M=p?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(M):M),!y){t.end();return}const T={res:t,plain:p,redact:w};oe.add(T),e.on("close",()=>oe.delete(T));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(i)&&i>1024&&(C=i),C||(C=9229);const o=S.filter(p=>p.proc.exitCode===null&&p.proc.signalCode===null);for(const p of o)p.debugSlot<0&&(p.debugSlot=x()),tell(p.proc,{type:"debug-open",port:inspectorPortFor(C,p.debugSlot)});for(const p of G)try{p.proc.kill("SIGUSR1")}catch{}const y=Date.now()+2e3;for(;Date.now()<y&&o.some(p=>!p.inspectorUrl);)await new Promise(p=>setTimeout(p,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:C,fixedPorts:usesFixedInspectorPorts(),pods:o.map(p=>({id:p.id,inspectorUrl:p.inspectorUrl??null})),workers:G.map(p=>({name:p.name,port:p.debugPort||(0,inspector_secret_1.inspectorPortOf)(p.inspectorUrl),inspectorUrl:p.inspectorUrl??null}))},null,2)+`
12
+ })()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(d,_){let f=null;return(...m)=>{f&&clearTimeout(f),f=setTimeout(()=>d(...m),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const d=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const m=inspector.url();m&&tell(process,{type:"inspector-url",url:m})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&d(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,m=!1,W,re=!1;const Ve=(0,hot_swap_registries_1.registryPruningEnabled)(),ge=a((r,c)=>{const l=(0,hot_swap_registries_1.describePrune)(r,c);l&&console.log(l)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const we=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),I=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const l=c(r);return{count:Number(l?.count??0),...l?.oldestStartedAt?{oldestStartedAt:l.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),$e=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),me=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),be=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[l,h]of r.abandoned)(l.writableEnded||c-h>=Z)&&r.abandoned.delete(l);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const l of r.open??[])l.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:I(r.workGen).count}},"owedBy"),ne=a((r,c,l=`${c}s`)=>`${r} ${r===1?c:l}`,"plural");async function We(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<be);){const l=F.values().next().value;if(!l||l.closed)break;const h=oe(l);if(h.unanswered===0&&h.work===0)break;const E=(l.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(l.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${be} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(v=>{setTimeout(v,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(We,"He"),a(We,"holdForOwedWork");const M=(0,swap_recycle_1.swapRecyclePolicy)();let ye,se=0;const Je=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const S=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let Ee=!1;const B=a(()=>{if(!Ee)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:S,state:a(()=>({gen:j.gen??0,swaps:se,...ye===void 0?{}:{baseline:ye},busy:m||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Te(),"onRetained"),gc:a((r,c)=>(0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,r,c),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,"live-heap")&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),q=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,l=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>l.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Oe(){if(!(!q||ie))try{const r=q();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Oe,"De"),a(Oe,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const Fe=a(()=>M.settleMs<=0||!m&&!re&&J.size===0&&Date.now()-D>=M.settleMs,"settled");let Y;function ae(r){if(!(!M.enabled||g||b)){if(M.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,Fe()?X(r):ae(r)},M.settleMs),Y.unref?.()}}u(ae,"_e"),a(ae,"recycleCheckWhenSettled");const ce=a(()=>{if(M.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const l of J.values())r-l>=M.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!M.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,l=a(E=>{const v=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:ce(),settled:Fe(),...ye===void 0?{}:{baselineBytes:ye},...v?{retained:{generation:v.gen,ageMs:Date.now()-v.closedAt,gcs:v.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(M,l(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(M,l(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let le;function Te(){if(!M.enabled||M.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+M.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}le||(le=setTimeout(()=>{le=void 0,k.measure("retention-check").catch(()=>{})},c),le.unref?.())}u(Te,"je"),a(Te,"retainedRecycleCheck");function ve(r,c){const l={};c&&(l.module=c),r&&(l.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(l.nestApp=h,h.container&&typeof h.container=="object")){l.container=h.container;const E=rootModuleOf(h.container);E&&(l.rootModule=E)}}catch{}return l}u(ve,"Ne"),a(ve,"generationTargets");async function de(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const l=M.enabled&&M.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(M.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},M.stuckCloseMs):void 0;l?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),l&&clearTimeout(l),r.app=null,r.abandoned=void 0,r.handler=(E,v)=>{v.statusCode=503,v.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,ve(h,r.module)),r.module=void 0}if(r.superseded){try{ge((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(de,"me"),a(de,"closeGeneration");async function pe(r){const c=Date.now();r.drainingSince=c;const l=a(()=>({inflight:r.inflight+V(r),work:I(r.workGen).count}),"busy"),h=l();if(h.inflight>0||h.work>0){for(;F.size>=be;){const $=F.values().next().value;if(!$)break;const O=oe($),z=Math.round((Date.now()-($.drainingSince??c))/1e3);if(O.unanswered===0&&O.streams===0&&O.work===0){await de($);continue}await de($,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${be} (each holds a whole app: DI container, DB pool, queue workers). `+(O.unanswered>0||O.work>0?`It was replaced ${z}s ago and had still not answered ${ne(O.unanswered,"request")}`+(O.work?` or finished ${ne(O.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne(O.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;we>0&&Date.now()-c<we;){if(r.closed)return;const $=l();if($.inflight===0&&$.work===0)break;await new Promise(O=>{setTimeout(O,250).unref?.()})}if(r.closed)return;const E=l(),v=me(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(v?`Previous app still processing ${v.running} queue job(s); ${v.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${we}ms) if this is legitimate work.`):(Date.now()-c>250||v?.runningAtStop||v?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(v?` (it finished ${v.finishedAfterStop} queue job(s) after the swap; ${v.takenAfterStop} were taken after the swap)`:"")),await de(r)}u(pe,"ye"),a(pe,"drainThenClose");async function ue(){if(m)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;m=!0,D=Date.now(),await We(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Ve)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,l=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw m=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw m=!1,D=Date.now(),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'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),ge((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw m=!1,D=Date.now(),takeImportedModule(),P}const v=j;h?.size&&(v.app?v.superseded=h:ge((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const $=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...$?{module:$}:{},...l===void 0?{}:{workGen:l}};const O=ve(E,void 0).container;O&&(x.add(new WeakRef(O)),Ee=!0);const z=v.app&&l!==void 0?$e(l):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Oe(),v.app&&(se+=1,pe(v).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(v.gen,()=>v.closed===!0&&!J.has(v))),m=!1,D=Date.now(),re?(re=!1,ue()):E}u(ue,"Ee"),a(ue,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await ue()}catch(r){console.error("[child] reload failed:",r)}},250),he=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const E=r.headers["x-internal-token"],v=process.env.LENSMCP_SERVICE_KEY;if(v&&E!==v){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const $=I();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:m,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:$.count,oldestWorkAt:$.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const l=j;l.inflight+=1,(l.open??=new Set).add(c),l.oldestAt===void 0&&(l.oldestAt=Date.now());const h=k.request();c.on("close",()=>{l.inflight-=1,l.open?.delete(c),Z>0&&!l.closed&&!c.headersSent&&!c.writableEnded&&((l.abandoned??=new Map).set(c,Date.now()),l.abandoned.size>256&&V(l)),l.inflight===0&&(l.oldestAt=void 0),h()}),l.handler(r,c)});he.keepAliveTimeout=0;const N=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(N),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const l=(0,schema_first_instance_1.prewarmZodFor)(r);l?.created&&console.log(`[child] zod${l.version?` ${l.version}`:""}: built ${l.created} throwaway schemas first, so none of the bundle's own is the first of its class`)}catch{}if((0,redis_disconnect_fix_1.redisDisconnectFixEnabled)())try{const l=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);l?.patched&&console.log(`[child] ioredis${l.versions.length?` ${l.versions.join(", ")}`:""}: a disconnect() between reconnect attempts now ends the client \u2014 it used to leave a queue worker's close() waiting for good`)}catch{}await ue(),ye=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock(N);let c=!1;he.on("error",l=>{if(c){console.error("[child] server error:",l);return}console.error(`[child] could not listen on ${N} (${l.code??l.message}) \u2014 exiting; the devserver starts another pod`),tell(process,{type:"boot-error",error:`could not listen on ${N}: ${String(l?.stack||l)}`}),cleanupSock(N),process.exitCode=1,setTimeout(()=>process.exit(1),100)}),he.listen(N,()=>{c=!0,console.log(`[child] Listening on ${N}`),tell(process,{type:"ready",socketPath:N})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);d(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){U();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await ue(),tell(process,{type:"reloaded",socketPath:N,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(l=>{tell(process,{type:"heap-snapshot-result",id:r.id,...l})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const l=H(),h=k.tracker.views().map(O=>O.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const v=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:l,...r.available?{available:r.available}:{}});if(v)return c({ok:!1,refused:v,live:l});console.log(`[child] writing a heap snapshot (${Math.round(l/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const $=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:$.bytes,ms:$.ms,live:l,gen:j.gen??0,closedAlive:h})}catch(l){c({ok:!1,error:l?.message??String(l)})}finally{Se=!1}}u(Me,"Ye"),a(Me,"takeHeapSnapshot");async function U(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename(N,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=$e(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(N),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Je).unref?.()}),cleanupSock(N),he.close();const l=Date.now();for(;Date.now()-l<we;){he.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&I().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(U,"B"),a(U,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const fe=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),l=new Promise(h=>he.close(()=>h()));cleanupSock(N),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,l]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){U("this generation was handed over to a newer one");return}inspector?.close?.(),fe(r)})})})()}else{let d=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),be?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const S=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(S):S)}catch{oe.delete(b)}},"ge");a(d,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",m=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ve="\x1B[0m",ge=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),we=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let I=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const $e=20;I&&(console.warn("[parent] DEBUGGER ENABLED \u2014 pods and workers open a Node inspector. Node's inspector has NO authentication: the ws:// URL's UUID is the whole credential, and any account on this host that obtains it can run code as you. Do not enable this on a shared machine. (issues/closed/codex-security-06)"),console.warn(usesFixedInspectorPorts()?`[parent] ${exports.DEBUG_FIXED_PORTS_ENV} is set \u2014 inspectors bind PREDICTABLE ports (${I}+slot, workers ${I}+${$e}+i). Any account on this host can connect to 127.0.0.1:${I} and read the session UUID from /json/list. Unset it to use ephemeral ports.`:`[parent] Inspectors bind an EPHEMERAL loopback port; attach via the printed "Debugger listening" URL, or \`lensmcp debug <service>\` (control socket). Set ${exports.DEBUG_FIXED_PORTS_ENV}=1 for fixed ports if your IDE needs a pre-configured attach port \u2014 any account on this host can then reach them.`));const me=process.env.LENSMCP_LOG_FILE||"",be=me?(()=>{try{fs.mkdirSync(path.dirname(me),{recursive:!0});const g=fs.createWriteStream(me,{flags:"a",mode:384});try{fs.chmodSync(me,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${me}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),S=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(S,ne,x):x)),d(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
13
+ `)}}const We=a(g=>re[(g-1)%re.length],"colorFor"),M=a(g=>{if(ge===1)return"";const b=`[child#${g}] `;return`${We(g)}${b}${Ve}`},"tagFor"),ye=a(g=>g.startsWith("{")&&g.endsWith("}"),"isJsonLog"),se=a((g,b,S)=>{const K=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(B=>`
14
+ `+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{S?.(k)}catch{}const q=ye(k)?K(k):`${k}
15
+ `;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${q}`)),d(`${b}${q}`)},"write"),Ee=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",q=>x(k,q)),H.on("close",()=>{})},"attach");Ee(g.stdout,"stdout"),Ee(g.stderr,"stderr")},"wireProcLogging"),Je=a(g=>se(g.proc,M(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const S=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let Ee=1,B=0,k=!1,H=ge,q=[],ie=0;const Oe=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Fe=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return S.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"q"),a(Y,"healthyChildren");let ae,ce=0,X;const le={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Te(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==ce&&(ce=t.startedAt,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"started",t,{root:process.cwd()})));const s=(0,service_build_events_1.buildAccountOf)(e.failed);s&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"failed",s,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.unchanged);n&&n.startedAt===ce&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"unchanged",n,{root:process.cwd()})))}u(Te,"je"),a(Te,"recordBuildProgress");function ve(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Te(t),"failed"in t&&delete t.failed,"unchanged"in t&&delete t.unchanged,ae=t;for(const s of S)tell(s.proc,{type:"watcher",testimony:t})}}u(ve,"Ne"),a(ve,"recordWatcherTestimony");function de(e,t=256*1024){return new Promise(s=>{let n="",i=!1;e.on("data",o=>{i||(n+=o,n.length>t&&(i=!0))}),e.on("end",()=>{if(i||!n)return s(void 0);try{s(JSON.parse(n))}catch{s(void 0)}}),e.on("error",()=>s(void 0))})}u(de,"me"),a(de,"readJsonBody");function pe(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(pe,"ye"),a(pe,"pickChild");function ue(e,t){const s=`Child#${e.id}`,n=SERVICE_NAME||f,i=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(s,o)}`),m.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:i}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,i))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,i))}}u(ue,"Ee"),a(ue,"recordPodMemory");const Pe=new Map;let he=0;async function N(){const e=Ee++,t=childSockPath(e);cleanupSock(t);const s=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&s.unshift("--require","@swc-node/register"),s.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const n=I?x():-1,i=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...n>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(I,n))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:s,execPath:we("pod")}),o={id:e,proc:i,healthy:!1,lastError:null,debugSlot:n,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return i.on("error",y=>console.error(`[parent] Child#${e}: ${y.message}`)),i.on("message",y=>{if(!y||typeof y!="object")return;const p=y;if(p.type==="ready")o.socketPath=String(p.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),ae&&tell(i,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Oe==="process"?P():tell(i,{type:"reload"}));else if(p.type==="recycle-request")v(o,String(p.reason||"it has outgrown its bound"));else if(p.type==="inspector-url")o.inspectorUrl=String(p.url),console.log(`[parent] Child#${o.id} Debugger listening on ${p.url}`);else if(p.type==="reloaded"){if(U.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(p.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=p.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else p.type==="reload-error"?(o.lastError=String(p.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):p.type==="boot-error"?(o.lastError=String(p.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):p.type==="pod-memory"||p.type==="pod-memory-retained"||p.type==="pod-memory-released"?ue(o,p):p.type==="heap-snapshot-result"&&Pe.get(Number(p.id))?.(p)}),i.on("exit",(y,p)=>{o.booting=!1;for(const A of o.memory.retained.values()){const C={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,C)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),C,Date.now()))}o.memory.retained.clear(),o.memory.latest&&m.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:y,signal:p},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=p==="SIGINT"||p==="SIGTERM"||y===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${y}, signal=${p??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${y}, signal=${p??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,y,p,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${y}, signal=${p??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=S.indexOf(o);A>=0&&S.splice(A,1);const C=Date.now();if(q=q.filter(T=>C-T<3e4),q.length>=5){console.error(`[parent] crash-loop detected (${q.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}q.push(C),setTimeout(()=>{const T=S.filter(Q=>Q.proc.killed===!1).length;!k&&T<H&&(console.log(`[parent] respawning a crashed pod (${T}/${H} live)`),N().catch(()=>{}))},1500).unref?.()}}),S.push(o),Je(o),o}u(N,"T"),a(N,"spawnChild");async function Se(e){H=Math.max(H,e);const t=S.filter(n=>n.proc.killed===!1),s=e-t.length;for(let n=0;n<s;n++)await N()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=S.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!Fe(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const s=S.indexOf(t);s>=0&&S.splice(s,1),await N()}))}u(Me,"Ye"),a(Me,"respawnUnhealthy");const U=new Set;let fe=!1,r=0;const c=3e4,l=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const s=Date.now(),n=await N(),i=Date.now()+J;for(;!n.healthy&&!n.lastError&&!D(n)&&Date.now()<i;){if(t.superseded?.()){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${n.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!n.healthy){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${n.id} did not come up (${n.lastError??"no answer in time"})`}}return E(e),{fresh:n,readyMs:Date.now()-s}}u(h,"_"),a(h,"replacePod");function E(e){const t=S.indexOf(e);if(t>=0&&S.splice(t,1),e.healthy=!1,D(e))return;U.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const s=setTimeout(()=>{if(!D(e)){console.error(`[parent] Child#${e.id} was still running ${l}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},l);if(s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),U.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"y"),a(E,"retirePod");async function v(e,t){const s=a(i=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${i}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!S.includes(e))return;if(fe)return s("another pod is already being replaced");const n=Date.now()-r;if(n<c)return s(`a pod was replaced ${Math.round(n/1e3)}s ago`);fe=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const i=await h(e);if("why"in i){i.why!=="shutting down"&&s(i.why);return}r=Date.now(),console.log(`[parent] Child#${i.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${i.fresh.proc.pid})`)}catch(i){s(`could not start a successor: ${i?.message??String(i)}`)}finally{fe=!1}}u(v,"m"),a(v,"recyclePod");let $,O=!1,z=0;function P(){if($){O=!0;return}$=(async()=>{do{O=!1;const e=ie;for(;fe&&!k;)await new Promise(s=>{setTimeout(s,100).unref?.()});let t=!1;for(const s of Y().filter(n=>n.bootReloadSeq<e)){if(k)break;if(!(!S.includes(s)||!s.healthy)){fe=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${s.id} keeps serving the previous build until it is ready.`);const n=await h(s,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in n){if(n.superseded){z+=1,console.log(`[parent] ${n.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${s.id} keeps serving.`),t=!0;break}n.why!=="shutting down"&&console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 ${n.why}`);continue}z=0,console.log(`[parent] Child#${n.fresh.id} took over from Child#${s.id} with the new build (pid ${s.proc.pid} \u2192 ${n.fresh.proc.pid}, ready in ${(n.readyMs/1e3).toFixed(1)}s while Child#${s.id} served)`),m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(n.fresh),{generation:1,swaps:0,swapMs:n.readyMs,draining:U.size,handoff:{fromPid:s.proc.pid??0}},X,{root:process.cwd()}))}catch(n){console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 could not start a successor: ${n?.message??String(n)}`)}finally{fe=!1}}}t&&(O=!0)}while(O&&!k)})().finally(()=>{$=void 0})}u(P,"N"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...U].filter(s=>!D(s));for(;t.length>=e;){const s=t.shift();console.error(`[parent] Child#${s.id} (pid ${s.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{s.proc.kill("SIGTERM")}catch{}}}u(ee,"J"),a(ee,"capRetiring");const G=[],He=new Map,qe=a(e=>{let t=He.get(e);return t||He.set(e,t={crashes:0,restarts:0}),t},"watchOf"),Xe=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),tt=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function ze(e,t){const s=e.name,n=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),i=path.join(n,`${s}.js`),o=qe(s);if(!fs.existsSync(i))return console.error(`[parent] Worker "${s}" bundle not found: ${i}`),o.missing=i,m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(s,0),{ranMs:0,reason:`its bundle was not built (${path.basename(i)} is not in ${n})`})),null;o.missing=void 0;const y=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&y.unshift("--require","@swc-node/register"),tt&&y.push("--require",tt);try{y.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const p=inspectorPortFor(I||9229,$e+Math.max(0,WORKER_NAMES.indexOf(s)));y.push(I?`--inspect=127.0.0.1:${p}`:`--inspect-port=127.0.0.1:${p}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(i,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:y,execPath:we(`w-${s}`)}),A={name:s,spec:e,proc:w,debugPort:p,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",T=>console.error(`[parent] Worker "${s}": ${T.message}`)),se(w,`\x1B[35m[worker:${s}] \x1B[0m`,T=>{A.tail.push(T);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec(T);Q&&(A.inspectorUrl=Q[1])});const C=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const T=Date.now()-A.startedAt;console.log(`[parent] Worker "${s}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)(T)} without a crash, after ${o.crashes} in a row`),m.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(s,w.pid??0),{ranMs:T,afterCrashes:o.crashes}))}o.crashes=0}},Xe.stableMs);return C.unref?.(),w.on("exit",(T,Q)=>{clearTimeout(C);const ke=G.indexOf(A);ke>=0&&G.splice(ke,1),rt(A,T,Q)}),console.log(`[parent] Worker "${s}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),m.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(s,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(ze,"Ze"),a(ze,"spawnWorkerProcess");function rt(e,t,s){const{name:n}=e,i=e.proc.pid??0,o=Date.now()-e.startedAt,y=(0,worker_supervisor_1.workerExitVerdict)(t,s,e.stopping||k);if(y.kind==="stopped")return;const p=qe(n);if(y.kind==="exited"){p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${n}" (pid=${i}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,i),{ranMs:o}));return}p.crashes+=1,p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(p.crashes,Xe),A=p.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${n}" crashed (code=${t}, signal=${s??"none"}, pid=${i}, after ${(0,worker_supervisor_1.spanOf)(o)})${y.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${p.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(Xe.maxMs)})`:""}`,t,s,e.tail.snapshot())),m.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(n,i),{code:t,signal:s,ranMs:o,crashes:p.crashes,restarts:p.restarts,nextInMs:w,external:y.external,lines:e.tail.snapshot()})),clearTimeout(p.pending),p.nextAt=Date.now()+w,p.pending=setTimeout(()=>{p.pending=void 0,p.nextAt=void 0,!(k||G.some(C=>C.name===n))&&(p.restarts+=1,Ue(e.spec,"respawn"))},w),p.pending.unref?.()}u(rt,"ct"),a(rt,"workerEnded");function Ue(e,t){const s=qe(e.name);s.waiting=void 0;const n=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!n){ze(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${n.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const i=a(()=>{s.waiting===i&&(s.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&ze(e,t)},"go");s.waiting=i,n.proc.once("exit",i)}u(Ue,"Ve"),a(Ue,"startWorker");const ot=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),nt=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function Be(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(Be,"qe"),a(Be,"killDrainingWorker");function Qe(e){e.stopping=!0,tell(e.proc,{type:worker_retire_1.RETIRE_MESSAGE});try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(n=>n.name===e.name);for(;t.length>=nt;)Be(t.shift(),`was still running when a later reload replaced its successor (cap ${nt})`);te.add(e);const s=setTimeout(()=>Be(e,`was still running ${ot}ms after SIGTERM`),ot);s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),te.delete(e)})}u(Qe,"rt"),a(Qe,"retireWorker");function je(){for(const e of He.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(je,"Je"),a(je,"cancelWorkerStarts");function st(){for(const e of[...G])Qe(e);G.length=0,je();for(const e of WORKER_SPECS)qe(e.name).crashes=0,Ue(e,"reload")}u(st,"lt"),a(st,"restartWorkers");function it(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const s=G.find(o=>o.name===t.name),n=He.get(t.name),i=s?"running":n?.pending?(n.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":n?.waiting?"waiting":n?.missing?"missing":n?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:i,port:t.port,env:Object.keys(t.env),...s?{pid:s.proc.pid,upMs:e-s.startedAt}:{},crashes:n?.crashes??0,restarts:n?.restarts??0,...n?.nextAt?{nextInMs:Math.max(0,n.nextAt-e)}:{},...n?.lastEnd?{lastEnd:n.lastEnd}:{},...n?.missing?{missing:n.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(it,"dt"),a(it,"workersView");const ht=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Oe==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&st()},200),at=a((e,t)=>{const s=(0,notice_generation_1.noticeGeneration)(e.headers);return s===void 0||s===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:s})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${s} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ce=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),de(e).then(i=>{const o=i;X=(0,service_build_events_1.buildAccountOf)(o?.build),ce=0,ve(o?.watcher)}),ht();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;const i=await de(e);ve(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let i="";e.on("data",o=>{i+=o}),e.on("end",async()=>{let o=0;try{o=Number(JSON.parse(i||"{}").pods)||0}catch{}o=Math.max(1,Math.min(o,16)),await Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const i=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(i.get("tail")??"100")||0,0),Z),y=i.get("follow")!=="0",p=i.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),C=p?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(C):C),!y){t.end();return}const T={res:t,plain:p,redact:w};oe.add(T),e.on("close",()=>oe.delete(T));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(i)&&i>1024&&(I=i),I||(I=9229);const o=S.filter(p=>p.proc.exitCode===null&&p.proc.signalCode===null);for(const p of o)p.debugSlot<0&&(p.debugSlot=x()),tell(p.proc,{type:"debug-open",port:inspectorPortFor(I,p.debugSlot)});for(const p of G)try{p.proc.kill("SIGUSR1")}catch{}const y=Date.now()+2e3;for(;Date.now()<y&&o.some(p=>!p.inspectorUrl);)await new Promise(p=>setTimeout(p,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:I,fixedPorts:usesFixedInspectorPorts(),pods:o.map(p=>({id:p.id,inspectorUrl:p.inspectorUrl??null})),workers:G.map(p=>({name:p.name,port:p.debugPort||(0,inspector_secret_1.inspectorPortOf)(p.inspectorUrl),inspectorUrl:p.inspectorUrl??null}))},null,2)+`
16
16
  `);return}if(e.method==="GET"&&e.url==="/webpack/workers"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(it(),null,2)+`
17
- `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...S,...q].map(y=>({id:y.id,pid:y.proc.pid??0,podGeneration:POD_GENERATION,healthy:y.healthy,retiring:q.has(y),latest:y.memory.latest??null,history:y.memory.history,retained:[...y.memory.retained.values()]}));t.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),t.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:f,bundle:{path:i},pods:o},null,2)+`
17
+ `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...S,...U].map(y=>({id:y.id,pid:y.proc.pid??0,podGeneration:POD_GENERATION,healthy:y.healthy,retiring:U.has(y),latest:y.memory.latest??null,history:y.memory.history,retained:[...y.memory.retained.values()]}));t.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),t.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:f,bundle:{path:i},pods:o},null,2)+`
18
18
  `);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=a((L,Le)=>{t.writeHead(L,{"content-type":"application/json"}),t.end(JSON.stringify(Le,null,2)+`
19
- `)},"reply"),o=new URL(e.url,"http://localhost").searchParams,y=Number(o.get("pod")||""),p=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(p!==void 0&&!(Number.isFinite(p)&&p>0)){i(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const w=Number.isInteger(y)&&y>0?S.find(L=>L.id===y):Y()[0];if(!w||D(w)){i(404,{ok:!1,error:y?`no pod #${y} \u2014 running: ${S.map(L=>`#${L.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(Pe.size>0){i(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const A=(0,heap_snapshot_1.heapSnapshotPolicy)(),M=(0,heap_snapshot_1.heapSnapshotDir)();let T;try{(0,heap_snapshot_1.ensureHeapDir)(M);const L=(0,heap_snapshot_1.pruneHeapSnapshots)(M,A);L.length&&console.log(`[parent] removed ${L.length} older heap snapshot(s) from ${M}`),T=path.join(M,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||f,w.id,w.proc.pid??0,w.memory.latest?.gen??0,Date.now()))}catch(L){i(500,{ok:!1,error:`cannot prepare ${M}: ${L.message}`});return}const Q=++he,ke=(0,heap_snapshot_1.availableSystemMemory)();let Ge;const R=await new Promise(L=>{const Le=setTimeout(()=>L(void 0),6e5);Le.unref?.(),Pe.set(Q,mt=>{clearTimeout(Le),L(mt)}),Ge=a(()=>{clearTimeout(Le),L(void 0)},"onExit"),w.proc.once("exit",Ge);const wt={type:"heap-snapshot",id:Q,file:T,...ke?{available:ke}:{},...p!==void 0?{maxHeapBytes:Math.floor(p*1048576)}:{}};tell(w.proc,wt)||Ge()}).finally(()=>{Pe.delete(Q),Ge&&w.proc.off("exit",Ge)});if(!R){i(504,{ok:!1,pod:w.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}R.ok?console.log(`[parent] Child#${w.id} wrote a ${Math.round((R.bytes??0)/1048576)} MB heap snapshot in ${R.ms} ms \u2192 ${R.file}`):console.warn(`[parent] Child#${w.id} heap snapshot not taken: ${R.refused??R.error}`),i(R.ok?200:R.refused?409:500,{ok:R.ok,pod:w.id,pid:w.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...ke?{available:ke}:{},...R.file?{file:R.file,bytes:R.bytes,ms:R.ms}:{},...R.live!==void 0?{live:R.live}:{},...R.gen!==void 0?{gen:R.gen,closedAlive:R.closedAlive??[]}:{},...R.refused?{refused:R.refused}:{},...R.error?{error:R.error}:{}});return}const s=matchGatewayRoute(e);if(s?.prependPrefix&&!e.url?.startsWith(s.prependPrefix)&&(e.url=s.prependPrefix+(e.url??"/")),s?.target){applyGatewayMiddleware(e),g.web(e,t,{target:s.target,autoRewrite:typeof s.target=="string",changeOrigin:!0},i=>{console.error(`[parent] proxy error to ${s.target}:`,i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${s.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=pe();if(!n){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const i=S.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
19
+ `)},"reply"),o=new URL(e.url,"http://localhost").searchParams,y=Number(o.get("pod")||""),p=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(p!==void 0&&!(Number.isFinite(p)&&p>0)){i(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const w=Number.isInteger(y)&&y>0?S.find(L=>L.id===y):Y()[0];if(!w||D(w)){i(404,{ok:!1,error:y?`no pod #${y} \u2014 running: ${S.map(L=>`#${L.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(Pe.size>0){i(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const A=(0,heap_snapshot_1.heapSnapshotPolicy)(),C=(0,heap_snapshot_1.heapSnapshotDir)();let T;try{(0,heap_snapshot_1.ensureHeapDir)(C);const L=(0,heap_snapshot_1.pruneHeapSnapshots)(C,A);L.length&&console.log(`[parent] removed ${L.length} older heap snapshot(s) from ${C}`),T=path.join(C,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||f,w.id,w.proc.pid??0,w.memory.latest?.gen??0,Date.now()))}catch(L){i(500,{ok:!1,error:`cannot prepare ${C}: ${L.message}`});return}const Q=++he,ke=(0,heap_snapshot_1.availableSystemMemory)();let Ge;const R=await new Promise(L=>{const Le=setTimeout(()=>L(void 0),6e5);Le.unref?.(),Pe.set(Q,mt=>{clearTimeout(Le),L(mt)}),Ge=a(()=>{clearTimeout(Le),L(void 0)},"onExit"),w.proc.once("exit",Ge);const wt={type:"heap-snapshot",id:Q,file:T,...ke?{available:ke}:{},...p!==void 0?{maxHeapBytes:Math.floor(p*1048576)}:{}};tell(w.proc,wt)||Ge()}).finally(()=>{Pe.delete(Q),Ge&&w.proc.off("exit",Ge)});if(!R){i(504,{ok:!1,pod:w.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}R.ok?console.log(`[parent] Child#${w.id} wrote a ${Math.round((R.bytes??0)/1048576)} MB heap snapshot in ${R.ms} ms \u2192 ${R.file}`):console.warn(`[parent] Child#${w.id} heap snapshot not taken: ${R.refused??R.error}`),i(R.ok?200:R.refused?409:500,{ok:R.ok,pod:w.id,pid:w.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...ke?{available:ke}:{},...R.file?{file:R.file,bytes:R.bytes,ms:R.ms}:{},...R.live!==void 0?{live:R.live}:{},...R.gen!==void 0?{gen:R.gen,closedAlive:R.closedAlive??[]}:{},...R.refused?{refused:R.refused}:{},...R.error?{error:R.error}:{}});return}const s=matchGatewayRoute(e);if(s?.prependPrefix&&!e.url?.startsWith(s.prependPrefix)&&(e.url=s.prependPrefix+(e.url??"/")),s?.target){applyGatewayMiddleware(e),g.web(e,t,{target:s.target,autoRewrite:typeof s.target=="string",changeOrigin:!0},i=>{console.error(`[parent] proxy error to ${s.target}:`,i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${s.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=pe();if(!n){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const i=S.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
20
20
  `);t.end(`No healthy children available. POST /webpack/reload to recover.
21
21
 
22
22
  Last errors:
23
23
  ${i}`);return}g.web(e,t,{target:{socketPath:n.socketPath},headers:{"x-proxy-child-id":String(n.id)}},i=>{console.error(`[parent] proxy error to Child#${n.id}:`,i),n.healthy=!1,n.lastError=String(i?.stack||i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from Child#${n.id}. Try /webpack/reload.
24
- ${n.lastError}`)})},"requestHandler");let _e,Ie,Ze;const xe=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(n=>n.host).filter(n=>!!n),s=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ie=e.getCertificateSync(s,SERVICE_NAME||"lensmcp.dev",t),Ze=e.caCertPath(),_e=require("node:https").createServer({key:Ie,cert:Ie},Ce)}else _e=http.createServer(Ce);const ct=a((e,t,s)=>{const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){g.ws(e,t,s,{target:n.target,changeOrigin:!0},()=>t.destroy());return}const i=pe();if(!i){t.destroy();return}g.ws(e,t,s,{target:{socketPath:i.socketPath}},()=>t.destroy())},"upgradeHandler");_e.on("upgrade",ct);const lt=2e3;let dt=!1;_e.on("error",e=>{if(e.code==="EADDRINUSE"){dt||(dt=!0,console.warn(`[parent] public port ${b} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${lt/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!_e.listening&&_e.listen(b)},lt).unref?.();return}console.error("[parent] public server error:",e)}),await Se(ge);for(const e of WORKER_SPECS)qe(e,"boot");SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${b} is not bound \u2014 the gateway reaches this service through its socket pool)`):_e.listen(b,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${b}`),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(" ")}`),Ze&&(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 ${Ze}`)),console.log(`POST ${e}://localhost:${b}/webpack/reload to trigger rolling swap/respawn`)});const Ke=Number(process.env.INTERNAL_PORT||0);if(Ke>0&&!SOCKET_ONLY){const e=a((s,n)=>{const i=pe();if(!i){n.statusCode=503,n.setHeader("content-type","text/plain; charset=utf-8"),n.end("No healthy children available.");return}g.web(s,n,{target:{socketPath:i.socketPath}},o=>{i.healthy=!1,i.lastError=String(o?.stack||o),n.statusCode=502,n.end(`Upstream error from Child#${i.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(s,n,i)=>{const o=pe();if(!o){n.destroy();return}g.ws(s,n,i,{target:{socketPath:o.socketPath}},()=>n.destroy())}),t.on("error",s=>{console.warn(`[parent] internal port ${Ke} unavailable (${s.code}).`)}),t.listen(Ke,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${Ke}`)}),xe.push(t)}const ft=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of ft){if(!Number.isInteger(e)||e===Number(b))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:Ie,cert:Ie},Ce):http.createServer(Ce);t.on("upgrade",ct),t.on("error",s=>{console.warn(`[parent] extra port ${e} unavailable (${s.code}) \u2014 main port still up.`)}),t.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),xe.push(t)}const Ne=path.join(SOCK_DIR,"parent.sock");claimSock(Ne),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const De=http.createServer(Ce);De.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),De.listen(Ne),xe.push(De);function pt(){k=!0;const e=[...S,...q];console.log(`[SIGTERM] [parent] generation g${POD_GENERATION} was handed over to a newer one \u2014 ${e.length} pod(s) finish their in-flight work, then it exits`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const i of xe)if(!(i===De&&t))try{i.close()}catch{}try{_e.close()}catch{}je();for(const i of[...G])Qe(i);G.length=0;for(const i of S)if(!tell(i.proc,{type:"retire"}))try{i.proc.kill("SIGTERM")}catch{}const s=setTimeout(()=>{for(const i of e)if(!D(i)){console.error(`[parent] Child#${i.id} was still running ${l}ms after its generation was retired \u2014 killing it`);try{i.proc.kill("SIGKILL")}catch{}}},l);s.unref?.();const n=a(()=>{if(!(e.some(i=>!D(i))||[...te].some(i=>!Re(i)))){clearTimeout(s);for(const i of e)i.socketPath&&cleanupSock(i.socketPath,i.proc.pid);(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);try{fs.rmdirSync(SOCK_DIR)}catch{}console.log(`[parent] generation g${POD_GENERATION} retired`),process.exit(0)}},"finish");for(const i of e)i.proc.once("exit",n);for(const i of te)i.proc.once("exit",n);n()}u(pt,"ht"),a(pt,"retireGeneration");const ut=a(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const n of xe)if(!(n===De&&t))try{n.close()}catch{}je();for(const n of G){n.stopping=!0;try{n.proc.kill("SIGTERM")}catch{}}for(const n of WORKER_SPECS){const i=G.find(o=>o.name===n.name)?.proc.pid??0;m.publish((0,worker_supervisor_1.buildWorkerStoppedEvent)(Ae(n.name,i),{reason:`its devserver stopped (${e})`}))}for(const n of[...te])Be(n,"was still draining when its devserver shut down");for(const n of q)try{n.proc.kill("SIGTERM")}catch{}for(const n of S){try{n.proc.kill("SIGTERM")}catch{}n.socketPath&&cleanupSock(n.socketPath,n.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}const s=(0,devserver_host_1.devserverStopExitCode)(e);setTimeout(()=>process.exit(s),700).unref()},"shutdown");let et=0;const _t=2e3;["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{if(e==="SIGTERM"){if(!k&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){et=Date.now(),pt();return}if(et>0&&Date.now()-et<_t)return}ut(e)}));const Ye=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Ye)&&Ye>0){const e=setInterval(()=>{try{process.kill(Ye,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Ye}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),ut("gateway-gone")}},5e3);e.unref()}})()}
24
+ ${n.lastError}`)})},"requestHandler");let _e,Ie,Ze;const xe=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(n=>n.host).filter(n=>!!n),s=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ie=e.getCertificateSync(s,SERVICE_NAME||"lensmcp.dev",t),Ze=e.caCertPath(),_e=require("node:https").createServer({key:Ie,cert:Ie},Ce)}else _e=http.createServer(Ce);const ct=a((e,t,s)=>{const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){g.ws(e,t,s,{target:n.target,changeOrigin:!0},()=>t.destroy());return}const i=pe();if(!i){t.destroy();return}g.ws(e,t,s,{target:{socketPath:i.socketPath}},()=>t.destroy())},"upgradeHandler");_e.on("upgrade",ct);const lt=2e3;let dt=!1;_e.on("error",e=>{if(e.code==="EADDRINUSE"){dt||(dt=!0,console.warn(`[parent] public port ${b} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${lt/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!_e.listening&&_e.listen(b)},lt).unref?.();return}console.error("[parent] public server error:",e)}),await Se(ge);for(const e of WORKER_SPECS)Ue(e,"boot");SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${b} is not bound \u2014 the gateway reaches this service through its socket pool)`):_e.listen(b,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${b}`),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(" ")}`),Ze&&(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 ${Ze}`)),console.log(`POST ${e}://localhost:${b}/webpack/reload to trigger rolling swap/respawn`)});const Ke=Number(process.env.INTERNAL_PORT||0);if(Ke>0&&!SOCKET_ONLY){const e=a((s,n)=>{const i=pe();if(!i){n.statusCode=503,n.setHeader("content-type","text/plain; charset=utf-8"),n.end("No healthy children available.");return}g.web(s,n,{target:{socketPath:i.socketPath}},o=>{i.healthy=!1,i.lastError=String(o?.stack||o),n.statusCode=502,n.end(`Upstream error from Child#${i.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(s,n,i)=>{const o=pe();if(!o){n.destroy();return}g.ws(s,n,i,{target:{socketPath:o.socketPath}},()=>n.destroy())}),t.on("error",s=>{console.warn(`[parent] internal port ${Ke} unavailable (${s.code}).`)}),t.listen(Ke,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${Ke}`)}),xe.push(t)}const ft=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of ft){if(!Number.isInteger(e)||e===Number(b))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:Ie,cert:Ie},Ce):http.createServer(Ce);t.on("upgrade",ct),t.on("error",s=>{console.warn(`[parent] extra port ${e} unavailable (${s.code}) \u2014 main port still up.`)}),t.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),xe.push(t)}const Ne=path.join(SOCK_DIR,"parent.sock");claimSock(Ne),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const De=http.createServer(Ce);De.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),De.listen(Ne),xe.push(De);function pt(){k=!0;const e=[...S,...U];console.log(`[SIGTERM] [parent] generation g${POD_GENERATION} was handed over to a newer one \u2014 ${e.length} pod(s) finish their in-flight work, then it exits`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const i of xe)if(!(i===De&&t))try{i.close()}catch{}try{_e.close()}catch{}je();for(const i of[...G])Qe(i);G.length=0;for(const i of S)if(!tell(i.proc,{type:"retire"}))try{i.proc.kill("SIGTERM")}catch{}const s=setTimeout(()=>{for(const i of e)if(!D(i)){console.error(`[parent] Child#${i.id} was still running ${l}ms after its generation was retired \u2014 killing it`);try{i.proc.kill("SIGKILL")}catch{}}},l);s.unref?.();const n=a(()=>{if(!(e.some(i=>!D(i))||[...te].some(i=>!Re(i)))){clearTimeout(s);for(const i of e)i.socketPath&&cleanupSock(i.socketPath,i.proc.pid);(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);try{fs.rmdirSync(SOCK_DIR)}catch{}console.log(`[parent] generation g${POD_GENERATION} retired`),process.exit(0)}},"finish");for(const i of e)i.proc.once("exit",n);for(const i of te)i.proc.once("exit",n);n()}u(pt,"ht"),a(pt,"retireGeneration");const ut=a(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const n of xe)if(!(n===De&&t))try{n.close()}catch{}je();for(const n of G){n.stopping=!0;try{n.proc.kill("SIGTERM")}catch{}}for(const n of WORKER_SPECS){const i=G.find(o=>o.name===n.name)?.proc.pid??0;m.publish((0,worker_supervisor_1.buildWorkerStoppedEvent)(Ae(n.name,i),{reason:`its devserver stopped (${e})`}))}for(const n of[...te])Be(n,"was still draining when its devserver shut down");for(const n of U)try{n.proc.kill("SIGTERM")}catch{}for(const n of S){try{n.proc.kill("SIGTERM")}catch{}n.socketPath&&cleanupSock(n.socketPath,n.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}const s=(0,devserver_host_1.devserverStopExitCode)(e);setTimeout(()=>process.exit(s),700).unref()},"shutdown");let et=0;const _t=2e3;["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{if(e==="SIGTERM"){if(!k&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){et=Date.now(),pt();return}if(et>0&&Date.now()-et<_t)return}ut(e)}));const Ye=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Ye)&&Ye>0){const e=setInterval(()=>{try{process.kill(Ye,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Ye}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),ut("gateway-gone")}},5e3);e.unref()}})()}