@lensmcp/cluster 1.25.16 → 1.25.18

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 (131) hide show
  1. package/basic-ssl.js +1 -1
  2. package/build-host.js +1 -1
  3. package/build-scope-patterns.js +1 -1
  4. package/bundle-parent.js +1 -1
  5. package/checkout-cache.js +1 -1
  6. package/create-webpack-dev.js +1 -1
  7. package/create-webpack-prod.js +1 -1
  8. package/dev-devtool.js +1 -1
  9. package/devserver-notifier.js +1 -1
  10. package/devserver-transport.js +1 -1
  11. package/error-stack-release.js +1 -1
  12. package/executors/build/build.impl.js +1 -1
  13. package/executors/gateway/body-stall.js +1 -1
  14. package/executors/gateway/canonical-path.js +1 -1
  15. package/executors/gateway/client-ip.js +1 -1
  16. package/executors/gateway/gateway-errors.js +1 -1
  17. package/executors/gateway/gateway.impl.js +1 -1
  18. package/executors/gateway/gateway.lib.js +1 -1
  19. package/executors/gateway/health-check.js +1 -1
  20. package/executors/gateway/jwks-verify.d.ts +37 -2
  21. package/executors/gateway/jwks-verify.js +1 -1
  22. package/executors/gateway/jwt-claims.js +1 -1
  23. package/executors/gateway/main.prod-gateway.js +2 -2
  24. package/executors/gateway/main.rollout.js +4 -4
  25. package/executors/gateway/manifest.js +1 -1
  26. package/executors/gateway/metrics.js +1 -1
  27. package/executors/gateway/otel-tracing.js +1 -1
  28. package/executors/gateway/prod-config.js +1 -1
  29. package/executors/gateway/prod-gateway.lib.js +1 -1
  30. package/executors/gateway/prod-runtime/access-log.js +1 -1
  31. package/executors/gateway/prod-runtime/app.js +1 -1
  32. package/executors/gateway/prod-runtime/auth.js +1 -1
  33. package/executors/gateway/prod-runtime/body-stall.js +1 -1
  34. package/executors/gateway/prod-runtime/cors.js +1 -1
  35. package/executors/gateway/prod-runtime/edge.js +1 -1
  36. package/executors/gateway/prod-runtime/handler.js +1 -1
  37. package/executors/gateway/prod-runtime/hooks.js +1 -1
  38. package/executors/gateway/prod-runtime/observability.js +1 -1
  39. package/executors/gateway/prod-runtime/rollout.js +1 -1
  40. package/executors/gateway/prod-runtime/routing.js +1 -1
  41. package/executors/gateway/prod-runtime/server.js +1 -1
  42. package/executors/gateway/prod-runtime/trust.js +1 -1
  43. package/executors/gateway/prod-runtime/upgrade.js +7 -7
  44. package/executors/gateway/prod-runtime/upstream.js +1 -1
  45. package/executors/gateway/providers-prod.js +1 -1
  46. package/executors/gateway/rate-limit.js +2 -2
  47. package/executors/gateway/registry-source.js +1 -1
  48. package/executors/gateway/rollout-ops.js +2 -2
  49. package/executors/gateway/runtime/act.js +1 -1
  50. package/executors/gateway/runtime/auth.js +1 -1
  51. package/executors/gateway/runtime/chooser.js +12 -12
  52. package/executors/gateway/runtime/control.js +2 -2
  53. package/executors/gateway/runtime/dev-auth.js +1 -1
  54. package/executors/gateway/runtime/discovery.js +1 -1
  55. package/executors/gateway/runtime/edge.d.ts +7 -0
  56. package/executors/gateway/runtime/edge.js +1 -1
  57. package/executors/gateway/runtime/guest-graph.js +2 -2
  58. package/executors/gateway/runtime/guest-replay.js +2 -2
  59. package/executors/gateway/runtime/handler.js +1 -1
  60. package/executors/gateway/runtime/hmr-reload.js +1 -1
  61. package/executors/gateway/runtime/hooks.js +1 -1
  62. package/executors/gateway/runtime/instance.js +2 -2
  63. package/executors/gateway/runtime/lens-children.js +1 -1
  64. package/executors/gateway/runtime/lifecycle.js +3 -3
  65. package/executors/gateway/runtime/observability.js +2 -2
  66. package/executors/gateway/runtime/own-log.js +4 -4
  67. package/executors/gateway/runtime/pod-env.js +2 -2
  68. package/executors/gateway/runtime/pod-output.js +1 -1
  69. package/executors/gateway/runtime/pod-probe.js +1 -1
  70. package/executors/gateway/runtime/process-names.js +1 -1
  71. package/executors/gateway/runtime/project-graph-store.js +1 -1
  72. package/executors/gateway/runtime/proxy.js +1 -1
  73. package/executors/gateway/runtime/registration-guards.js +1 -1
  74. package/executors/gateway/runtime/route-registry.js +1 -1
  75. package/executors/gateway/runtime/scope.js +1 -1
  76. package/executors/gateway/runtime/serve-launch.js +3 -3
  77. package/executors/gateway/runtime/server.d.ts +39 -2
  78. package/executors/gateway/runtime/server.js +2 -2
  79. package/executors/gateway/runtime/service-keys.js +1 -1
  80. package/executors/gateway/runtime/shared-build.js +4 -4
  81. package/executors/gateway/runtime/source-poller.js +1 -1
  82. package/executors/gateway/runtime/types.js +1 -1
  83. package/executors/gateway/runtime/upgrade.js +1 -1
  84. package/executors/gateway/runtime/workspace-log.js +1 -1
  85. package/executors/gateway/runtime/workspace-middleware.js +1 -1
  86. package/executors/gateway/runtime/workspace-registry.js +1 -1
  87. package/executors/gateway/ssrf-guard.js +1 -1
  88. package/executors/serve/serve.impl.js +1 -1
  89. package/executors/trust/hostname.js +1 -1
  90. package/executors/trust/trust.impl.js +3 -3
  91. package/exit-reason.js +2 -2
  92. package/fork-ts-check-reporter.js +1 -1
  93. package/gateway.js +1 -1
  94. package/gc-notice.js +1 -1
  95. package/graph-snapshot.js +1 -1
  96. package/handoff-retire.js +1 -1
  97. package/heap-snapshot.js +1 -1
  98. package/hot-swap-registries.js +1 -1
  99. package/index.js +1 -1
  100. package/inspector-secret.js +1 -1
  101. package/main.devserver.js +11 -11
  102. package/notice-generation.js +1 -1
  103. package/package.json +4 -4
  104. package/perf/heavy-barrel-import.js +1 -1
  105. package/perf/perf-config.js +1 -1
  106. package/perf/perf-rule-events.js +2 -2
  107. package/perf/perf-rules-analysis.js +1 -1
  108. package/perf/perf-rules-plugin.js +1 -1
  109. package/perf/source-scan.js +5 -5
  110. package/perf/workspace-libraries.js +2 -2
  111. package/pod-memory-events.js +2 -2
  112. package/pod-memory.js +1 -1
  113. package/pod-sock.js +1 -1
  114. package/process-name.js +1 -1
  115. package/redis-disconnect-fix.js +1 -1
  116. package/schema-first-instance.js +1 -1
  117. package/serve-runner.js +1 -1
  118. package/service-build-events.js +1 -1
  119. package/shared-build/attach.js +2 -2
  120. package/shared-build/host.js +3 -3
  121. package/shared-build/protocol.js +1 -1
  122. package/shared-build/shared-compilation.js +3 -3
  123. package/shared-build/signature.js +1 -1
  124. package/stdio-guard.js +1 -1
  125. package/swap-mode.js +1 -1
  126. package/swap-recycle.js +1 -1
  127. package/tsgo-check-plugin.js +4 -4
  128. package/typecheck-bus.js +3 -3
  129. package/typecheck-queue.js +1 -1
  130. package/worker-supervisor.js +2 -2
  131. package/workspace-paths.js +1 -1
@@ -1 +1 @@
1
- "use strict";var C=Object.defineProperty;var g=(e,t)=>C(e,"name",{value:t,configurable:!0});var U=Object.defineProperty,u=g((e,t)=>U(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.sourceSame=exports.sourceFull=exports.sourceStaleAfterMs=exports.SOURCE_BACKOFF_MAX_MS=exports.SOURCE_DECLARATION_REPORT_MS=exports.SOURCE_NOT_RUNNING_REPORT_MS=exports.SOURCE_MAX_PER_SERVICE=exports.SOURCE_MAX_GROUPS=exports.SOURCE_MAX_BYTES=exports.SOURCE_ERROR_MAX=exports.LOOP_MAX_INTERVAL_SEC=exports.SOURCE_FULL_REPORT_MS=exports.TRAFFIC_DEFAULT_RATE_LIMITED=exports.TRAFFIC_DEFAULT_P95_MS=exports.TRAFFIC_DEFAULT_FAILURE_PCT=exports.STORE_DEFAULT_ORPHAN_MIN=exports.STORE_DEFAULT_ERROR_RATE_PCT=exports.STORE_DEFAULT_QUOTA_PCT=exports.LOOP_DEFAULT_IDLE_MIN=exports.QUEUE_DEFAULT_STALLED_MIN=exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN=exports.SOURCE_MIN_INTERVAL_SEC=exports.SOURCE_DEFAULT_INTERVAL_SEC=exports.TRAFFIC_DIRECTIONS=exports.LOOP_OUTCOMES=exports.SOURCE_SNAPSHOT_FIELD=exports.TRAFFIC_WIRE_SCHEMA=exports.STORE_WIRE_SCHEMA=exports.LOOP_WIRE_SCHEMA=exports.QUEUE_WIRE_SCHEMA=exports.SOURCE_KINDS_READ=exports.SOURCE_KINDS=exports.sourcesConcurrency=exports.sourcesTimeoutMs=exports.sourcesEnabled=void 0,exports.sourceBackoffMs=sourceBackoffMs,exports.parseSourceDecls=parseSourceDecls,exports.parseQueueSnapshot=parseQueueSnapshot,exports.parseLoopSnapshot=parseLoopSnapshot,exports.parseStoreSnapshot=parseStoreSnapshot,exports.parseTrafficSnapshot=parseTrafficSnapshot,exports.sourceDigest=sourceDigest,exports.keepQueueSnapshot=keepQueueSnapshot,exports.keepLoopSnapshot=keepLoopSnapshot,exports.keepStoreSnapshot=keepStoreSnapshot,exports.keepTrafficSnapshot=keepTrafficSnapshot,exports.buildSourcePollRaw=buildSourcePollRaw,exports.buildSourceDeclarationRaw=buildSourceDeclarationRaw,exports.sourcePollTitle=sourcePollTitle,exports.requestOverSocket=requestOverSocket,exports.createSourcePoller=createSourcePoller;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),http=tslib_1.__importStar(require("node:http")),discovery_1=require("./discovery"),readEnv=u(e=>process.env[e],"readEnv"),envInt=u((e,t,o)=>{const n=Number(readEnv(e));return Number.isInteger(n)&&n>=o?n:t},"envInt"),sourcesEnabled=u(()=>readEnv("LENSMCP_SOURCES")!=="0","sourcesEnabled");exports.sourcesEnabled=sourcesEnabled;const sourcesTimeoutMs=u(()=>envInt("LENSMCP_SOURCES_TIMEOUT_MS",3e3,100),"sourcesTimeoutMs");exports.sourcesTimeoutMs=sourcesTimeoutMs;const sourcesConcurrency=u(()=>envInt("LENSMCP_SOURCES_CONCURRENCY",4,1),"sourcesConcurrency");exports.sourcesConcurrency=sourcesConcurrency,exports.SOURCE_KINDS=["queue","loop","store","traffic"],exports.SOURCE_KINDS_READ=["queue","loop","store","traffic"],exports.QUEUE_WIRE_SCHEMA="lensmcp.queue/v1",exports.LOOP_WIRE_SCHEMA="lensmcp.loop/v1",exports.STORE_WIRE_SCHEMA="lensmcp.store/v1",exports.TRAFFIC_WIRE_SCHEMA="lensmcp.traffic/v1",exports.SOURCE_SNAPSHOT_FIELD={queue:"snapshot",loop:"loop",store:"store",traffic:"traffic"},exports.LOOP_OUTCOMES=["ok","failed","skipped"],exports.TRAFFIC_DIRECTIONS=["inbound","outbound"],exports.SOURCE_DEFAULT_INTERVAL_SEC=10,exports.SOURCE_MIN_INTERVAL_SEC=2,exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN=10,exports.QUEUE_DEFAULT_STALLED_MIN=15,exports.LOOP_DEFAULT_IDLE_MIN=10,exports.STORE_DEFAULT_QUOTA_PCT=90,exports.STORE_DEFAULT_ERROR_RATE_PCT=5,exports.STORE_DEFAULT_ORPHAN_MIN=60,exports.TRAFFIC_DEFAULT_FAILURE_PCT=5,exports.TRAFFIC_DEFAULT_P95_MS=2e3,exports.TRAFFIC_DEFAULT_RATE_LIMITED=1,exports.SOURCE_FULL_REPORT_MS=6e4,exports.LOOP_MAX_INTERVAL_SEC=86400,exports.SOURCE_ERROR_MAX=500,exports.SOURCE_MAX_BYTES=256*1024,exports.SOURCE_MAX_GROUPS=500,exports.SOURCE_MAX_PER_SERVICE=16,exports.SOURCE_NOT_RUNNING_REPORT_MS=6e4,exports.SOURCE_DECLARATION_REPORT_MS=5*6e4,exports.SOURCE_BACKOFF_MAX_MS=6e4;const sourceStaleAfterMs=u(e=>Math.max(3e4,3*Math.max(0,e)),"sourceStaleAfterMs");exports.sourceStaleAfterMs=sourceStaleAfterMs;function sourceBackoffMs(e,t){return t<=1?e:Math.min(e*2**Math.min(t-1,10),Math.max(e,exports.SOURCE_BACKOFF_MAX_MS))}g(sourceBackoffMs,"sourceBackoffMs"),u(sourceBackoffMs,"sourceBackoffMs");const isPolled=u(e=>e.path!==void 0,"isPolled"),ENTRY_KEYS={queue:["kind","name","path","intervalSec","thresholds"],loop:["kind","name","path","intervalSec","thresholds","feeds"],store:["kind","name","path","intervalSec","thresholds"],traffic:["kind","name","path","intervalSec","thresholds"]},finite=u(e=>typeof e=="number"&&Number.isFinite(e),"finite"),MINUTES={ok:u(e=>finite(e)&&e>0&&e<=10080,"ok"),must:"must be minutes, more than 0 and at most 10080"},PERCENT={ok:u(e=>finite(e)&&e>0&&e<=100,"ok"),must:"must be a percent, more than 0 and at most 100"},MILLISECONDS={ok:u(e=>finite(e)&&e>0&&e<=6e5,"ok"),must:"must be milliseconds, more than 0 and at most 600000"},COUNT={ok:u(e=>Number.isInteger(e)&&e>=1&&e<=1e6,"ok"),must:"must be a count, a whole number from 1 to 1000000"},THRESHOLDS={queue:{oldestWaitMin:{def:exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN,...MINUTES},stalledMin:{def:exports.QUEUE_DEFAULT_STALLED_MIN,...MINUTES}},loop:{idleMin:{def:exports.LOOP_DEFAULT_IDLE_MIN,...MINUTES}},store:{quotaPct:{def:exports.STORE_DEFAULT_QUOTA_PCT,...PERCENT},errorRatePct:{def:exports.STORE_DEFAULT_ERROR_RATE_PCT,...PERCENT},orphanMin:{def:exports.STORE_DEFAULT_ORPHAN_MIN,...MINUTES}},traffic:{failurePct:{def:exports.TRAFFIC_DEFAULT_FAILURE_PCT,...PERCENT},p95Ms:{def:exports.TRAFFIC_DEFAULT_P95_MS,...MILLISECONDS},rateLimited:{def:exports.TRAFFIC_DEFAULT_RATE_LIMITED,...COUNT}}},PATH_RE=/^\/(?!\/)[^\s#\u0000-\u001f\u007f]{0,511}$/,NAME_RE=/^[^\u0000-\u001f\u007f]{1,100}$/,isObj=u(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function parseSourceDecls(e){const t=[],o=[],n=[];if(e===void 0)return{sources:t,problems:o};if(!Array.isArray(e))return{sources:t,problems:["`sources` is not a list of { kind, name, path } entries \u2014 no source is read"]};e.forEach((i,l)=>{const E=`sources[${l}]`;if(!isObj(i)){o.push(`${E} is not an object \u2014 not read`);return}const d=typeof i.name=="string"&&i.name.trim()?`${E} "${i.name}"`:E,r=i.kind;if(typeof r!="string"||!exports.SOURCE_KINDS_READ.includes(r)){o.push(`${d}: kind ${JSON.stringify(r??null)} is not a source kind (${exports.SOURCE_KINDS.join(", ")}) \u2014 not read`);return}const a=r,p=Object.keys(i).filter(_=>!ENTRY_KEYS[a].includes(_));if(p.length){o.push(`${d}: unknown key${p.length===1?"":"s"} ${p.map(_=>JSON.stringify(_)).join(", ")} for a ${a} source (known: ${ENTRY_KEYS[a].join(", ")}) \u2014 not read`);return}const R=i.name;if(typeof R!="string"||!R.trim()||!NAME_RE.test(R)){o.push(`${E}: name ${JSON.stringify(R??null)} must be 1\u2013100 characters, not blank \u2014 not read`);return}if(t.some(_=>_.name===R)){o.push(`${d}: the name is declared twice on this service \u2014 read once`);return}const h=i.path;if(h===void 0&&a!=="traffic"&&a!=="loop"){o.push(`${d}: a ${a} source needs a path \u2014 the route on the service that answers "lensmcp.${a}/v1" (only a loop or a traffic source may go without one, as push-only) \u2014 not read`);return}if(h!==void 0&&(typeof h!="string"||!PATH_RE.test(h)||h.split("?")[0].split("/").includes(".."))){o.push(`${d}: path ${JSON.stringify(h)} must be a route on the service, starting with "/" (e.g. "/api/dev/lens/backlog") \u2014 not read`);return}const m=i.intervalSec;if(m!==void 0&&!(typeof m=="number"&&Number.isInteger(m)&&m>=exports.SOURCE_MIN_INTERVAL_SEC&&m<=3600)){o.push(`${d}: intervalSec ${JSON.stringify(m)} must be a whole number of seconds from ${exports.SOURCE_MIN_INTERVAL_SEC} to 3600 \u2014 not read`);return}const A=i.thresholds;if(A!==void 0&&!isObj(A)){o.push(`${d}: thresholds must be an object \u2014 not read`);return}const b=isObj(A)?A:{},I=THRESHOLDS[a],s=Object.keys(I),c=Object.keys(b).filter(_=>!s.includes(_));if(c.length){o.push(`${d}: unknown threshold${c.length===1?"":"s"} ${c.map(_=>JSON.stringify(_)).join(", ")} for a ${a} source (known: ${s.join(", ")}) \u2014 not read`);return}const f=s.find(_=>b[_]!==void 0&&!I[_].ok(b[_]));if(f){o.push(`${d}: thresholds.${f} ${JSON.stringify(b[f])} ${I[f].must} \u2014 not read`);return}if(t.length>=exports.SOURCE_MAX_PER_SERVICE){o.push(`${d}: more than ${exports.SOURCE_MAX_PER_SERVICE} sources on one service \u2014 not read`);return}const O={};for(const _ of s)O[_]=b[_]??I[_].def;const S={kind:a,name:R,...h!==void 0?{path:h}:{},intervalSec:m??exports.SOURCE_DEFAULT_INTERVAL_SEC,thresholds:O};t.push(S),a==="loop"&&i.feeds!==void 0&&n.push({decl:S,label:d,feeds:i.feeds})});for(const{decl:i,label:l,feeds:E}of n)typeof E!="string"||!E.trim()?o.push(`${l}: feeds ${JSON.stringify(E)} must be the name of a queue source on this service \u2014 read without it`):t.some(d=>d.kind==="queue"&&d.name===E)?i.feeds=E:o.push(`${l}: feeds ${JSON.stringify(E)} names no queue source on this service \u2014 read without it`);return{sources:t,problems:o}}g(parseSourceDecls,"parseSourceDecls"),u(parseSourceDecls,"parseSourceDecls");const ISO_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/,isIso=u(e=>typeof e=="string"&&ISO_RE.test(e)&&!Number.isNaN(Date.parse(e)),"isIso"),isCount=u(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,"isCount"),notSchema=u((e,t)=>`schema is ${e===void 0?"absent":JSON.stringify(e).slice(0,60)}, not "${t}"`,"notSchema"),keyWrong=u((e,t,o)=>{if(typeof e!="string"||e.length===0||e.length>200)return`${t}.key must be a string of 1\u2013200 characters`;if(o.has(e))return`${t}.key ${JSON.stringify(e)} appears twice`;o.add(e)},"keyWrong"),labelsWrong=u((e,t)=>{if(e===void 0)return;if(!isObj(e))return`${t}.labels must be an object of strings`;const o=Object.entries(e);if(o.length>16)return`${t}.labels has more than 16 entries`;for(const[n,i]of o)if(n.length===0||n.length>64||typeof i!="string"||i.length>200)return`${t}.labels.${n.slice(0,64)} must be a string of at most 200 characters`},"labelsWrong"),overCap=u((e,t)=>`${e} ${t} \u2014 at most ${exports.SOURCE_MAX_GROUPS}; cap them and say \`truncated: { ${t}: <dropped> }\``,"overCap");function parseQueueSnapshot(e){const t=u(d=>({ok:!1,reason:d}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.QUEUE_WIRE_SCHEMA)return t(notSchema(e.schema,exports.QUEUE_WIRE_SCHEMA));const o=e.at;if(!isIso(o))return t("`at` is not an ISO time");const n=e.truncated;if(n!==void 0&&!(isObj(n)&&isCount(n.groups)))return t("`truncated` must be { groups: <how many were dropped> }, or absent");const i=e.groups;if(!Array.isArray(i))return t("`groups` is not a list");if(i.length>exports.SOURCE_MAX_GROUPS)return t(overCap(i.length,"groups"));const l=new Set,E=[];for(let d=0;d<i.length;d++){const r=i[d],a=`groups[${d}]`;if(!isObj(r))return t(`${a} is not an object`);const p=keyWrong(r.key,a,l);if(p)return t(p);if(!isCount(r.pending))return t(`${a}.pending must be a whole number \u2265 0`);for(const A of["inFlight","failed","completedInWindow"])if(r[A]!==void 0&&!isCount(r[A]))return t(`${a}.${A} must be a whole number \u2265 0, or absent`);const R=r.oldestPendingAt;if(R!=null&&!isIso(R))return t(`${a}.oldestPendingAt must be an ISO time, null, or absent`);const h=r.labels,m=labelsWrong(h,a);if(m)return t(m);E.push({key:r.key,...h!==void 0?{labels:h}:{},pending:r.pending,...r.inFlight!==void 0?{inFlight:r.inFlight}:{},...r.failed!==void 0?{failed:r.failed}:{},...R!==void 0?{oldestPendingAt:R}:{},...r.completedInWindow!==void 0?{completedInWindow:r.completedInWindow}:{}})}return{ok:!0,at:o,groups:E,...n!==void 0?{truncated:{groups:n.groups}}:{}}}g(parseQueueSnapshot,"parseQueueSnapshot"),u(parseQueueSnapshot,"parseQueueSnapshot");const LOOP_COUNTS=["lastDurationMs","lastItems","runsInWindow","itemsInWindow","failuresInWindow","windowSec"],cutText=u((e,t)=>{if(e.length<=t)return e;const o=t-1,n=e.charCodeAt(o-1);return`${e.slice(0,n>=55296&&n<=56319?o-1:o)}\u2026`},"cutText");function parseLoopSnapshot(e){const t=u(a=>({ok:!1,reason:a}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.LOOP_WIRE_SCHEMA)return t(notSchema(e.schema,exports.LOOP_WIRE_SCHEMA));const o=e.at;if(!isIso(o))return t("`at` is not an ISO time");const n=e.intervalSec;if(!(typeof n=="number"&&Number.isFinite(n)&&n>0&&n<=exports.LOOP_MAX_INTERVAL_SEC))return t(`\`intervalSec\` must be the loop's own period in seconds, more than 0 and at most ${exports.LOOP_MAX_INTERVAL_SEC}`);const i=e.lastRunAt;if(i===void 0)return t("`lastRunAt` is absent \u2014 say null if the loop has not run since the service started");if(i!==null&&!isIso(i))return t("`lastRunAt` must be an ISO time, or null if the loop has not run since the service started");for(const a of LOOP_COUNTS)if(e[a]!==void 0&&!isCount(e[a]))return t(`\`${a}\` must be a whole number \u2265 0, or absent`);const l=e.lastOutcome;if(l!==void 0&&!exports.LOOP_OUTCOMES.includes(l))return t(`\`lastOutcome\` must be ${exports.LOOP_OUTCOMES.join(", ")}, or absent`);const E=e.nextRunAt;if(E!=null&&!isIso(E))return t("`nextRunAt` must be an ISO time, null, or absent");const d=e.lastError;if(d!==void 0&&typeof d!="string")return t("`lastError` must be a string, or absent");const r=u(a=>e[a]!==void 0?{[a]:e[a]}:{},"count");return{ok:!0,loop:{at:o,intervalSec:n,lastRunAt:i,...r("lastDurationMs"),...l!==void 0?{lastOutcome:l}:{},...r("lastItems"),...E!==void 0?{nextRunAt:E}:{},...r("runsInWindow"),...r("itemsInWindow"),...r("failuresInWindow"),...r("windowSec"),...d!==void 0?{lastError:cutText(d,exports.SOURCE_ERROR_MAX)}:{}}}}g(parseLoopSnapshot,"parseLoopSnapshot"),u(parseLoopSnapshot,"parseLoopSnapshot");const STORE_COUNTS=["opsInWindow","writesInWindow","deletesInWindow","errorsInWindow","windowSec"];function parseStoreSnapshot(e){const t=u(p=>({ok:!1,reason:p}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.STORE_WIRE_SCHEMA)return t(notSchema(e.schema,exports.STORE_WIRE_SCHEMA));const o=e.at;if(!isIso(o))return t("`at` is not an ISO time");for(const p of["objects","bytes"])if(!isCount(e[p]))return t(`\`${p}\` must be a whole number \u2265 0`);const n=e.quotaBytes;if(n!=null&&!isCount(n))return t("`quotaBytes` must be a whole number \u2265 0, null when it has no quota, or absent");for(const p of STORE_COUNTS)if(e[p]!==void 0&&!isCount(e[p]))return t(`\`${p}\` must be a whole number \u2265 0, or absent`);const i=e.lastWriteAt;if(i!=null&&!isIso(i))return t("`lastWriteAt` must be an ISO time, null, or absent");const l=e.lastError;if(l!==void 0&&typeof l!="string")return t("`lastError` must be a string, or absent");const E=e.truncated;if(E!==void 0&&!(isObj(E)&&isCount(E.groups)))return t("`truncated` must be { groups: <how many were dropped> }, or absent");const d=e.groups;let r;if(d!==void 0){if(!Array.isArray(d))return t("`groups` must be a list, or absent");if(d.length>exports.SOURCE_MAX_GROUPS)return t(overCap(d.length,"groups"));const p=new Set;r=[];for(let R=0;R<d.length;R++){const h=d[R],m=`groups[${R}]`;if(!isObj(h))return t(`${m} is not an object`);const A=keyWrong(h.key,m,p);if(A)return t(A);for(const s of["objects","bytes"])if(!isCount(h[s]))return t(`${m}.${s} must be a whole number \u2265 0`);const b=h.labels,I=labelsWrong(b,m);if(I)return t(I);r.push({key:h.key,...b!==void 0?{labels:b}:{},objects:h.objects,bytes:h.bytes})}}const a=u(p=>e[p]!==void 0?{[p]:e[p]}:{},"count");return{ok:!0,store:{at:o,objects:e.objects,bytes:e.bytes,...n!==void 0?{quotaBytes:n}:{},...a("opsInWindow"),...a("writesInWindow"),...a("deletesInWindow"),...a("errorsInWindow"),...a("windowSec"),...i!==void 0?{lastWriteAt:i}:{},...l!==void 0?{lastError:cutText(l,exports.SOURCE_ERROR_MAX)}:{},...r?{groups:r}:{},...E!==void 0?{truncated:{groups:E.groups}}:{}}}}g(parseStoreSnapshot,"parseStoreSnapshot"),u(parseStoreSnapshot,"parseStoreSnapshot");const TRAFFIC_COUNTS=["messagesInWindow","failuresInWindow","rateLimitedInWindow"];function parseTrafficSnapshot(e){const t=u(r=>({ok:!1,reason:r}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.TRAFFIC_WIRE_SCHEMA)return t(notSchema(e.schema,exports.TRAFFIC_WIRE_SCHEMA));const o=e.at;if(!isIso(o))return t("`at` is not an ISO time");const n=e.windowSec;if(n!==void 0&&!isCount(n))return t("`windowSec` must be a whole number \u2265 0, or absent");const i=e.truncated;if(i!==void 0&&!(isObj(i)&&isCount(i.channels)))return t("`truncated` must be { channels: <how many were dropped> }, or absent");const l=e.channels;if(!Array.isArray(l))return t("`channels` is not a list");if(l.length>exports.SOURCE_MAX_GROUPS)return t(overCap(l.length,"channels"));const E=new Set,d=[];for(let r=0;r<l.length;r++){const a=l[r],p=`channels[${r}]`;if(!isObj(a))return t(`${p} is not an object`);const R=keyWrong(a.key,p,E);if(R)return t(R);const h=a.direction;if(h!==void 0&&!exports.TRAFFIC_DIRECTIONS.includes(h))return t(`${p}.direction must be ${exports.TRAFFIC_DIRECTIONS.join(", ")}, or absent`);const m=a.counterpart;if(m!==void 0&&!(typeof m=="string"&&m.length>0&&m.length<=200))return t(`${p}.counterpart must be a string of 1\u2013200 characters, or absent`);for(const O of TRAFFIC_COUNTS)if(a[O]!==void 0&&!isCount(a[O]))return t(`${p}.${O} must be a whole number \u2265 0, or absent`);const A=a.p95Ms;if(A!==void 0&&!(finite(A)&&A>=0))return t(`${p}.p95Ms must be milliseconds \u2265 0, or absent`);const b=a.lastAt;if(b!=null&&!isIso(b))return t(`${p}.lastAt must be an ISO time, null, or absent`);const I=a.lastError;if(I!==void 0&&typeof I!="string")return t(`${p}.lastError must be a string, or absent`);const s=a.labels,c=labelsWrong(s,p);if(c)return t(c);const f=u(O=>a[O]!==void 0?{[O]:a[O]}:{},"count");d.push({key:a.key,...s!==void 0?{labels:s}:{},...h!==void 0?{direction:h}:{},...m!==void 0?{counterpart:m}:{},...f("messagesInWindow"),...f("failuresInWindow"),...f("rateLimitedInWindow"),...A!==void 0?{p95Ms:A}:{},...b!==void 0?{lastAt:b}:{},...I!==void 0?{lastError:cutText(I,exports.SOURCE_ERROR_MAX)}:{}})}return{ok:!0,traffic:{at:o,...n!==void 0?{windowSec:n}:{},channels:d,...i!==void 0?{truncated:{channels:i.channels}}:{}}}}g(parseTrafficSnapshot,"parseTrafficSnapshot"),u(parseTrafficSnapshot,"parseTrafficSnapshot");const sourceFull=u((e,t)=>({[exports.SOURCE_SNAPSHOT_FIELD[e]]:t}),"sourceFull");exports.sourceFull=sourceFull;const declRaw=u(e=>({sourceKind:e.kind,name:e.name,...e.path!==void 0?{path:e.path}:{},intervalSec:e.intervalSec,thresholds:{...e.thresholds},...e.feeds!==void 0?{feeds:e.feeds}:{}}),"declRaw"),canonical=u(e=>{if(Array.isArray(e))return e.map(canonical);if(!isObj(e))return e;const t={};for(const o of Object.keys(e).sort())t[o]=canonical(e[o]);return t},"canonical");function sourceDigest(e){return(0,node_crypto_1.createHash)("sha1").update(JSON.stringify(canonical(e))??"null").digest("hex").slice(0,16)}g(sourceDigest,"sourceDigest"),u(sourceDigest,"sourceDigest");const oldestOf=u(e=>e.pending>0&&e.oldestPendingAt?Date.parse(e.oldestPendingAt):Number.POSITIVE_INFINITY,"oldestOf");function keepQueueSnapshot(e,t,o,n){const i={groups:t.length,pending:0,inFlight:0,failed:0};let l;for(const r of t)i.pending+=r.pending,i.inFlight+=r.inFlight??0,i.failed+=r.failed??0,r.completedInWindow!==void 0&&(l=(l??0)+r.completedInWindow);l!==void 0&&(i.completedInWindow=l);const E=[...t].sort((r,a)=>oldestOf(r)-oldestOf(a)||a.pending-r.pending||(r.key<a.key?-1:r.key>a.key?1:0)).map(({key:r,...a})=>({group:r,...a})),d=n?{groups:n.groups}:void 0;return{at:e,receivedAt:o,totals:i,groups:E,...d?{truncated:d}:{},digest:sourceDigest({groups:E,truncated:d??null})}}g(keepQueueSnapshot,"keepQueueSnapshot"),u(keepQueueSnapshot,"keepQueueSnapshot");function keepLoopSnapshot(e,t){const{at:o,...n}=e;return{at:o,receivedAt:t,digest:sourceDigest(n),...n}}g(keepLoopSnapshot,"keepLoopSnapshot"),u(keepLoopSnapshot,"keepLoopSnapshot");const byKey=u((e,t)=>e<t?-1:e>t?1:0,"byKey");function keepStoreSnapshot(e,t){const{at:o,groups:n,truncated:i,...l}=e,E=n?[...n].sort((r,a)=>a.bytes-r.bytes||a.objects-r.objects||byKey(r.key,a.key)).map(({key:r,...a})=>({group:r,...a})):void 0,d={...l,...E?{groups:E}:{},...i?{truncated:{groups:i.groups}}:{}};return{at:o,receivedAt:t,digest:sourceDigest(d),...d}}g(keepStoreSnapshot,"keepStoreSnapshot"),u(keepStoreSnapshot,"keepStoreSnapshot");const messagesOf=u(e=>e.messagesInWindow??-1,"messagesOf");function keepTrafficSnapshot(e,t){const{at:o,channels:n,truncated:i,...l}=e,E=[...n].sort((r,a)=>messagesOf(a)-messagesOf(r)||byKey(r.key,a.key)).map(({key:r,...a})=>({channel:r,...a})),d={...l,channels:E,...i?{truncated:{channels:i.channels}}:{}};return{at:o,receivedAt:t,digest:sourceDigest(d),...d}}g(keepTrafficSnapshot,"keepTrafficSnapshot"),u(keepTrafficSnapshot,"keepTrafficSnapshot");const sourceSame=u(e=>({digest:e.digest,at:e.at,receivedAt:e.receivedAt}),"sourceSame");exports.sourceSame=sourceSame;function buildSourcePollRaw(e,t,o,n,i,l){return{kind:"source-poll",provenance:"reported",project:e,...declRaw(t),state:o.state,...o.detail!==void 0?{detail:o.detail}:{},...o.status!==void 0?{status:o.status}:{},polledAt:o.polledAt,...o.durationMs!==void 0?{durationMs:o.durationMs}:{},reportEveryMs:n,...i>0?{failures:i}:{},...l??{}}}g(buildSourcePollRaw,"buildSourcePollRaw"),u(buildSourcePollRaw,"buildSourcePollRaw");function buildSourceDeclarationRaw(e,t){return{kind:"source-declaration",project:e,sources:t.sources.map(declRaw),problems:[...t.problems]}}g(buildSourceDeclarationRaw,"buildSourceDeclarationRaw"),u(buildSourceDeclarationRaw,"buildSourceDeclarationRaw");const span=u(e=>{const t=Math.round(e/6e4);return e<6e4?`${Math.max(0,Math.round(e/1e3))}s`:t<120?`${t}m`:`${Math.floor(t/60)}h${t%60?` ${t%60}m`:""}`},"span"),loopWords=u(e=>`${e.lastRunAt===null?"has not run since the service started":`last run ${span(Math.max(0,Date.parse(e.at)-Date.parse(e.lastRunAt)))} before it was measured`}${e.lastOutcome?`, ${e.lastOutcome}`:""}${e.lastItems!==void 0?`, ${e.lastItems} item${e.lastItems===1?"":"s"}`:""}`,"loopWords"),plural=u((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),byteSize=u(e=>{const t=["B","kB","MB","GB","TB","PB"];let o=e,n=0;for(;o>=999.5&&n<t.length-1;)o/=1e3,n+=1;return n===0?`${e} B`:`${o<9.95?o.toFixed(1):Math.round(o)} ${t[n]}`},"byteSize"),storeWords=u(e=>{const t=typeof e.quotaBytes=="number"&&e.quotaBytes>0?` of ${byteSize(e.quotaBytes)} (${Math.round(e.bytes/e.quotaBytes*1e3)/10}%)`:"",o=e.errorsInWindow?`, ${plural(e.errorsInWindow,"error")}${e.windowSec?` in ${span(e.windowSec*1e3)}`:""}`:"";return`${plural(e.objects,"object")}, ${byteSize(e.bytes)}${t}${o}`},"storeWords"),trafficWords=u(e=>{let t,o=0,n=0;for(const l of e.channels)l.messagesInWindow!==void 0&&(t=(t??0)+l.messagesInWindow),o+=l.failuresInWindow??0,n+=l.rateLimitedInWindow??0;const i=t!==void 0?`, ${plural(t,"message")}${e.windowSec?` in ${span(e.windowSec*1e3)}`:""}`:"";return`${plural(e.channels.length,"channel")}${i}${o?`, ${o} failed`:""}${n?`, ${n} rate-limited`:""}`},"trafficWords");function sourcePollTitle(e,t){const o=`${e.sourceKind} ${e.project}/${e.name} (reported)`,n=t??e[exports.SOURCE_SNAPSHOT_FIELD[e.sourceKind]];if(e.state!=="current"||!n)return`${o}: ${e.state}${e.detail?` \u2014 ${e.detail}`:""}`;if(e.sourceKind==="loop")return`${o}: ${loopWords(n)}`;if(e.sourceKind==="store")return`${o}: ${storeWords(n)}`;if(e.sourceKind==="traffic")return`${o}: ${trafficWords(n)}`;const i=n,l=i.groups.find(d=>d.pending>0&&d.oldestPendingAt),E=l?.oldestPendingAt?Date.parse(i.at)-Date.parse(l.oldestPendingAt):void 0;return`${o}: ${i.totals.pending} pending in ${i.totals.groups} group${i.totals.groups===1?"":"s"}${E!==void 0?`, oldest waiting ${span(Math.max(0,E))}`:""}`}g(sourcePollTitle,"sourcePollTitle"),u(sourcePollTitle,"sourcePollTitle");function requestOverSocket(e,t,o,n,i=exports.SOURCE_MAX_BYTES){return new Promise(l=>{let E=!1,d;const r=u(p=>{E||(E=!0,clearTimeout(a),l(p))},"finish"),a=setTimeout(()=>{r({ok:!1,code:"ETIMEDOUT",message:`no answer within ${n} ms`}),d?.destroy()},n);a.unref?.();try{d=http.request({socketPath:e,path:t,method:"GET",agent:!1,headers:o},p=>{const R=[];let h=0;p.on("data",m=>{if(!E){if(h+=m.length,h>i){r({ok:!0,status:p.statusCode??0,body:"",truncated:!0}),p.destroy();return}R.push(m)}}),p.on("end",()=>r({ok:!0,status:p.statusCode??0,body:Buffer.concat(R).toString("utf8"),truncated:!1})),p.on("error",m=>r({ok:!1,code:m.code??"ERESPONSE",message:m.message}))}),d.on("error",p=>r({ok:!1,code:p.code??"EREQUEST",message:p.message})),d.end()}catch(p){r({ok:!1,code:p.code??"EREQUEST",message:p.message})}})}g(requestOverSocket,"requestOverSocket"),u(requestOverSocket,"requestOverSocket");const snippet=u(e=>e.replace(/\s+/g," ").trim().slice(0,160),"snippet");function readSnapshot(e,t,o){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`not JSON: ${snippet(t)||"(an empty body)"}`}}if(e==="loop"){const l=parseLoopSnapshot(n);return l.ok===!0?{ok:!0,kept:keepLoopSnapshot(l.loop,o)}:l}if(e==="store"){const l=parseStoreSnapshot(n);return l.ok===!0?{ok:!0,kept:keepStoreSnapshot(l.store,o)}:l}if(e==="traffic"){const l=parseTrafficSnapshot(n);return l.ok===!0?{ok:!0,kept:keepTrafficSnapshot(l.traffic,o)}:l}const i=parseQueueSnapshot(n);return i.ok===!0?{ok:!0,kept:keepQueueSnapshot(i.at,i.groups,o,i.truncated)}:i}g(readSnapshot,"readSnapshot"),u(readSnapshot,"readSnapshot");function createSourcePoller(e){const t=e.now??Date.now,o=e.timeoutMs??(0,exports.sourcesTimeoutMs)(),n=Math.max(1,e.maxConcurrent??(0,exports.sourcesConcurrency)()),i=e.socketOf??(s=>(0,discovery_1.pickSock)(s.pool,e.scanTtlMs??1500)),l=e.request??requestOverSocket,E=e.log??(s=>console.warn(s)),d=new WeakMap,r=new Map;let a=0,p;const R=u(s=>{const c=s.decl;let f=d.get(c);if(!f){f=parseSourceDecls(s.decl.sources),d.set(c,f);for(const S of f.problems)E(`[gateway] ${s.project}: cluster.sources \u2014 ${S}`)}const O=t();return(f.reportedAt===void 0||O-f.reportedAt>=exports.SOURCE_DECLARATION_REPORT_MS)&&(f.reportedAt=O,e.emit(s,f.problems.length?"warning":"info",f.problems.length?`sources ${s.project}: ${f.problems.length} cluster.sources entr${f.problems.length===1?"y":"ies"} not read \u2014 ${f.problems[0]}`:`sources ${s.project}: reads ${f.sources.map(S=>`${S.kind} "${S.name}"${isPolled(S)?"":" (push-only)"}`).join(", ")}`,`source-declaration:${s.wsKey}:${s.project}`,buildSourceDeclarationRaw(s.project,f))),f},"declarationOf"),h=u(s=>{if(s.state==="starting")return{notRunning:"it is starting \u2014 read once it is up"};const c=i(s);return c?{socket:c}:{notRunning:s.state==="up"?"it has no live pod socket \u2014 no pod runs it now":"it is scaled to zero \u2014 the lens does not start a service to read a source"}},"reach"),m=u((s,c)=>{const f=s.good;if(f)return s.full&&s.full.digest===f.digest&&c-s.full.at<exports.SOURCE_FULL_REPORT_MS?{same:(0,exports.sourceSame)(f)}:(s.full={digest:f.digest,at:c},(0,exports.sourceFull)(s.decl.kind,f))},"carried"),A=u((s,c)=>{const f=s.last;if(!f)return;const O=t();if(!c&&s.reportedAt!==void 0&&O-s.reportedAt<s.reportEveryMs)return;s.reportedAt=O;const S=buildSourcePollRaw(s.svc.project,s.decl,f,s.reportEveryMs,s.failures,m(s,O)),_=f.state==="unreachable"||f.state==="refused"||f.state==="malformed";e.emit(s.svc,_?"warning":"info",sourcePollTitle(S,s.good),`source:${s.svc.wsKey}:${s.svc.project}:${s.decl.name}`,S)},"report"),b=u(async s=>{const c=t(),f=s.decl.intervalSec*1e3;s.inFlight=!0,a+=1;const O=s.last?.state;try{const S=h(s.svc);if("notRunning"in S){s.last={state:"not-running",detail:S.notRunning,polledAt:c},s.failures=0,s.nextAt=c+f,s.reportEveryMs=exports.SOURCE_NOT_RUNNING_REPORT_MS,A(s,O!=="not-running");return}const _=e.serviceKey(s.svc),T=await l(S.socket,s.decl.path,{accept:"application/json","x-lensmcp-probe":`source:${s.decl.kind}`,..._?{"x-internal-token":_}:{}},o,exports.SOURCE_MAX_BYTES),x=Math.max(0,t()-c);if(T.ok===!1){const $=T.code==="ECONNREFUSED"||T.code==="ENOENT";s.last=$&&s.svc.state!=="up"?{state:"not-running",detail:`nothing listens on its pod socket \u2014 the service is ${s.svc.state}`,polledAt:c,durationMs:x}:{state:"unreachable",detail:T.code==="ETIMEDOUT"?T.message:`${T.code}: ${snippet(T.message)}`,polledAt:c,durationMs:x}}else if(T.status<200||T.status>299){const $=snippet(T.body);s.last={state:"refused",status:T.status,detail:`HTTP ${T.status}${$?`: ${$}`:""}`,polledAt:c,durationMs:x}}else if(T.truncated)s.last={state:"malformed",detail:`the snapshot is larger than ${exports.SOURCE_MAX_BYTES/1024} KiB`,polledAt:c,durationMs:x};else{const $=readSnapshot(s.decl.kind,T.body,t());$.ok===!0?(s.good=$.kept,s.last={state:"current",polledAt:c,durationMs:x}):s.last={state:"malformed",detail:$.reason,polledAt:c,durationMs:x}}const v=s.last.state==="unreachable"||s.last.state==="refused"||s.last.state==="malformed";s.failures=v?s.failures+1:0;const M=v?sourceBackoffMs(f,s.failures):f;s.nextAt=c+M,s.reportEveryMs=s.last.state==="not-running"?exports.SOURCE_NOT_RUNNING_REPORT_MS:M,A(s,s.last.state!=="not-running"||O!=="not-running")}catch(S){s.last={state:"unreachable",detail:`the poll failed: ${snippet(S?.message??String(S))}`,polledAt:c},s.failures+=1,s.nextAt=c+sourceBackoffMs(f,s.failures),s.reportEveryMs=s.nextAt-c,A(s,!0)}finally{s.inFlight=!1,a-=1}},"pollOne"),I=u(async()=>{if(e.stopped?.())return;const s=new Set;for(const S of e.services())if(S.decl.sources!==void 0)for(const _ of R(S).sources){if(!isPolled(_))continue;const T=`${S.wsKey} ${S.project} ${_.kind} ${_.name}`;s.add(T);const x=r.get(T);x?(x.svc!==S||x.decl!==_)&&(x.svc=S,x.decl=_):r.set(T,{svc:S,decl:_,nextAt:0,inFlight:!1,failures:0,reportEveryMs:_.intervalSec*1e3})}for(const[S,_]of[...r.entries()])!s.has(S)&&!_.inFlight&&r.delete(S);const c=t(),f=[...r.values()].filter(S=>!S.inFlight&&c>=S.nextAt).sort((S,_)=>S.nextAt-_.nextAt),O=[];for(const S of f){if(a>=n)break;O.push(b(S))}await Promise.all(O)},"tick");return{tick:I,start(s=1e3){return p&&clearInterval(p),p=setInterval(()=>{I().catch(c=>console.error("[gateway] source poll error:",c))},s),p.unref(),p},stop(){p&&clearInterval(p),p=void 0},snapshot(){const s=t();return[...r.values()].map(c=>{const f=c.last!==void 0&&s-c.last.polledAt>(0,exports.sourceStaleAfterMs)(c.reportEveryMs);return{wsKey:c.svc.wsKey,project:c.svc.project,name:c.decl.name,kind:c.decl.kind,path:c.decl.path,state:c.last?f?"stale":c.last.state:"never-polled",...c.last?.detail!==void 0?{detail:c.last.detail}:{},...c.last?.status!==void 0?{status:c.last.status}:{},...c.last?{polledAt:c.last.polledAt}:{},failures:c.failures,nextAt:c.nextAt,...c.good?{...(0,exports.sourceFull)(c.decl.kind,c.good),ageMs:Math.max(0,s-c.good.receivedAt)}:{}}})}}}g(createSourcePoller,"createSourcePoller"),u(createSourcePoller,"createSourcePoller");
1
+ "use strict";var k=Object.defineProperty;var b=(e,t)=>k(e,"name",{value:t,configurable:!0});var C=Object.defineProperty,g=b((e,t)=>C(e,"name",{value:t,configurable:!0}),"g"),U=Object.defineProperty,u=g((e,t)=>U(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.sourceSame=exports.sourceFull=exports.sourceStaleAfterMs=exports.SOURCE_BACKOFF_MAX_MS=exports.SOURCE_DECLARATION_REPORT_MS=exports.SOURCE_NOT_RUNNING_REPORT_MS=exports.SOURCE_MAX_PER_SERVICE=exports.SOURCE_MAX_GROUPS=exports.SOURCE_MAX_BYTES=exports.SOURCE_ERROR_MAX=exports.LOOP_MAX_INTERVAL_SEC=exports.SOURCE_FULL_REPORT_MS=exports.TRAFFIC_DEFAULT_RATE_LIMITED=exports.TRAFFIC_DEFAULT_P95_MS=exports.TRAFFIC_DEFAULT_FAILURE_PCT=exports.STORE_DEFAULT_ORPHAN_MIN=exports.STORE_DEFAULT_ERROR_RATE_PCT=exports.STORE_DEFAULT_QUOTA_PCT=exports.LOOP_DEFAULT_IDLE_MIN=exports.QUEUE_DEFAULT_STALLED_MIN=exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN=exports.SOURCE_MIN_INTERVAL_SEC=exports.SOURCE_DEFAULT_INTERVAL_SEC=exports.TRAFFIC_DIRECTIONS=exports.LOOP_OUTCOMES=exports.SOURCE_SNAPSHOT_FIELD=exports.TRAFFIC_WIRE_SCHEMA=exports.STORE_WIRE_SCHEMA=exports.LOOP_WIRE_SCHEMA=exports.QUEUE_WIRE_SCHEMA=exports.SOURCE_KINDS_READ=exports.SOURCE_KINDS=exports.sourcesConcurrency=exports.sourcesTimeoutMs=exports.sourcesEnabled=void 0,exports.sourceBackoffMs=sourceBackoffMs,exports.parseSourceDecls=parseSourceDecls,exports.parseQueueSnapshot=parseQueueSnapshot,exports.parseLoopSnapshot=parseLoopSnapshot,exports.parseStoreSnapshot=parseStoreSnapshot,exports.parseTrafficSnapshot=parseTrafficSnapshot,exports.sourceDigest=sourceDigest,exports.keepQueueSnapshot=keepQueueSnapshot,exports.keepLoopSnapshot=keepLoopSnapshot,exports.keepStoreSnapshot=keepStoreSnapshot,exports.keepTrafficSnapshot=keepTrafficSnapshot,exports.buildSourcePollRaw=buildSourcePollRaw,exports.buildSourceDeclarationRaw=buildSourceDeclarationRaw,exports.sourcePollTitle=sourcePollTitle,exports.requestOverSocket=requestOverSocket,exports.createSourcePoller=createSourcePoller;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),http=tslib_1.__importStar(require("node:http")),discovery_1=require("./discovery"),readEnv=u(e=>process.env[e],"readEnv"),envInt=u((e,t,s)=>{const n=Number(readEnv(e));return Number.isInteger(n)&&n>=s?n:t},"envInt"),sourcesEnabled=u(()=>readEnv("LENSMCP_SOURCES")!=="0","sourcesEnabled");exports.sourcesEnabled=sourcesEnabled;const sourcesTimeoutMs=u(()=>envInt("LENSMCP_SOURCES_TIMEOUT_MS",3e3,100),"sourcesTimeoutMs");exports.sourcesTimeoutMs=sourcesTimeoutMs;const sourcesConcurrency=u(()=>envInt("LENSMCP_SOURCES_CONCURRENCY",4,1),"sourcesConcurrency");exports.sourcesConcurrency=sourcesConcurrency,exports.SOURCE_KINDS=["queue","loop","store","traffic"],exports.SOURCE_KINDS_READ=["queue","loop","store","traffic"],exports.QUEUE_WIRE_SCHEMA="lensmcp.queue/v1",exports.LOOP_WIRE_SCHEMA="lensmcp.loop/v1",exports.STORE_WIRE_SCHEMA="lensmcp.store/v1",exports.TRAFFIC_WIRE_SCHEMA="lensmcp.traffic/v1",exports.SOURCE_SNAPSHOT_FIELD={queue:"snapshot",loop:"loop",store:"store",traffic:"traffic"},exports.LOOP_OUTCOMES=["ok","failed","skipped"],exports.TRAFFIC_DIRECTIONS=["inbound","outbound"],exports.SOURCE_DEFAULT_INTERVAL_SEC=10,exports.SOURCE_MIN_INTERVAL_SEC=2,exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN=10,exports.QUEUE_DEFAULT_STALLED_MIN=15,exports.LOOP_DEFAULT_IDLE_MIN=10,exports.STORE_DEFAULT_QUOTA_PCT=90,exports.STORE_DEFAULT_ERROR_RATE_PCT=5,exports.STORE_DEFAULT_ORPHAN_MIN=60,exports.TRAFFIC_DEFAULT_FAILURE_PCT=5,exports.TRAFFIC_DEFAULT_P95_MS=2e3,exports.TRAFFIC_DEFAULT_RATE_LIMITED=1,exports.SOURCE_FULL_REPORT_MS=6e4,exports.LOOP_MAX_INTERVAL_SEC=86400,exports.SOURCE_ERROR_MAX=500,exports.SOURCE_MAX_BYTES=256*1024,exports.SOURCE_MAX_GROUPS=500,exports.SOURCE_MAX_PER_SERVICE=16,exports.SOURCE_NOT_RUNNING_REPORT_MS=6e4,exports.SOURCE_DECLARATION_REPORT_MS=5*6e4,exports.SOURCE_BACKOFF_MAX_MS=6e4;const sourceStaleAfterMs=u(e=>Math.max(3e4,3*Math.max(0,e)),"sourceStaleAfterMs");exports.sourceStaleAfterMs=sourceStaleAfterMs;function sourceBackoffMs(e,t){return t<=1?e:Math.min(e*2**Math.min(t-1,10),Math.max(e,exports.SOURCE_BACKOFF_MAX_MS))}b(sourceBackoffMs,"sourceBackoffMs"),g(sourceBackoffMs,"sourceBackoffMs"),u(sourceBackoffMs,"sourceBackoffMs");const isPolled=u(e=>e.path!==void 0,"isPolled"),ENTRY_KEYS={queue:["kind","name","path","intervalSec","thresholds"],loop:["kind","name","path","intervalSec","thresholds","feeds"],store:["kind","name","path","intervalSec","thresholds"],traffic:["kind","name","path","intervalSec","thresholds"]},finite=u(e=>typeof e=="number"&&Number.isFinite(e),"finite"),MINUTES={ok:u(e=>finite(e)&&e>0&&e<=10080,"ok"),must:"must be minutes, more than 0 and at most 10080"},PERCENT={ok:u(e=>finite(e)&&e>0&&e<=100,"ok"),must:"must be a percent, more than 0 and at most 100"},MILLISECONDS={ok:u(e=>finite(e)&&e>0&&e<=6e5,"ok"),must:"must be milliseconds, more than 0 and at most 600000"},COUNT={ok:u(e=>Number.isInteger(e)&&e>=1&&e<=1e6,"ok"),must:"must be a count, a whole number from 1 to 1000000"},THRESHOLDS={queue:{oldestWaitMin:{def:exports.QUEUE_DEFAULT_OLDEST_WAIT_MIN,...MINUTES},stalledMin:{def:exports.QUEUE_DEFAULT_STALLED_MIN,...MINUTES}},loop:{idleMin:{def:exports.LOOP_DEFAULT_IDLE_MIN,...MINUTES}},store:{quotaPct:{def:exports.STORE_DEFAULT_QUOTA_PCT,...PERCENT},errorRatePct:{def:exports.STORE_DEFAULT_ERROR_RATE_PCT,...PERCENT},orphanMin:{def:exports.STORE_DEFAULT_ORPHAN_MIN,...MINUTES}},traffic:{failurePct:{def:exports.TRAFFIC_DEFAULT_FAILURE_PCT,...PERCENT},p95Ms:{def:exports.TRAFFIC_DEFAULT_P95_MS,...MILLISECONDS},rateLimited:{def:exports.TRAFFIC_DEFAULT_RATE_LIMITED,...COUNT}}},PATH_RE=/^\/(?!\/)[^\s#\u0000-\u001f\u007f]{0,511}$/,NAME_RE=/^[^\u0000-\u001f\u007f]{1,100}$/,isObj=u(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function parseSourceDecls(e){const t=[],s=[],n=[];if(e===void 0)return{sources:t,problems:s};if(!Array.isArray(e))return{sources:t,problems:["`sources` is not a list of { kind, name, path } entries \u2014 no source is read"]};e.forEach((i,l)=>{const S=`sources[${l}]`;if(!isObj(i)){s.push(`${S} is not an object \u2014 not read`);return}const d=typeof i.name=="string"&&i.name.trim()?`${S} "${i.name}"`:S,r=i.kind;if(typeof r!="string"||!exports.SOURCE_KINDS_READ.includes(r)){s.push(`${d}: kind ${JSON.stringify(r??null)} is not a source kind (${exports.SOURCE_KINDS.join(", ")}) \u2014 not read`);return}const a=r,p=Object.keys(i).filter(_=>!ENTRY_KEYS[a].includes(_));if(p.length){s.push(`${d}: unknown key${p.length===1?"":"s"} ${p.map(_=>JSON.stringify(_)).join(", ")} for a ${a} source (known: ${ENTRY_KEYS[a].join(", ")}) \u2014 not read`);return}const R=i.name;if(typeof R!="string"||!R.trim()||!NAME_RE.test(R)){s.push(`${S}: name ${JSON.stringify(R??null)} must be 1\u2013100 characters, not blank \u2014 not read`);return}if(t.some(_=>_.name===R)){s.push(`${d}: the name is declared twice on this service \u2014 read once`);return}const h=i.path;if(h===void 0&&a!=="traffic"&&a!=="loop"){s.push(`${d}: a ${a} source needs a path \u2014 the route on the service that answers "lensmcp.${a}/v1" (only a loop or a traffic source may go without one, as push-only) \u2014 not read`);return}if(h!==void 0&&(typeof h!="string"||!PATH_RE.test(h)||h.split("?")[0].split("/").includes(".."))){s.push(`${d}: path ${JSON.stringify(h)} must be a route on the service, starting with "/" (e.g. "/api/dev/lens/backlog") \u2014 not read`);return}const m=i.intervalSec;if(m!==void 0&&!(typeof m=="number"&&Number.isInteger(m)&&m>=exports.SOURCE_MIN_INTERVAL_SEC&&m<=3600)){s.push(`${d}: intervalSec ${JSON.stringify(m)} must be a whole number of seconds from ${exports.SOURCE_MIN_INTERVAL_SEC} to 3600 \u2014 not read`);return}const A=i.thresholds;if(A!==void 0&&!isObj(A)){s.push(`${d}: thresholds must be an object \u2014 not read`);return}const I=isObj(A)?A:{},x=THRESHOLDS[a],o=Object.keys(x),c=Object.keys(I).filter(_=>!o.includes(_));if(c.length){s.push(`${d}: unknown threshold${c.length===1?"":"s"} ${c.map(_=>JSON.stringify(_)).join(", ")} for a ${a} source (known: ${o.join(", ")}) \u2014 not read`);return}const f=o.find(_=>I[_]!==void 0&&!x[_].ok(I[_]));if(f){s.push(`${d}: thresholds.${f} ${JSON.stringify(I[f])} ${x[f].must} \u2014 not read`);return}if(t.length>=exports.SOURCE_MAX_PER_SERVICE){s.push(`${d}: more than ${exports.SOURCE_MAX_PER_SERVICE} sources on one service \u2014 not read`);return}const O={};for(const _ of o)O[_]=I[_]??x[_].def;const E={kind:a,name:R,...h!==void 0?{path:h}:{},intervalSec:m??exports.SOURCE_DEFAULT_INTERVAL_SEC,thresholds:O};t.push(E),a==="loop"&&i.feeds!==void 0&&n.push({decl:E,label:d,feeds:i.feeds})});for(const{decl:i,label:l,feeds:S}of n)typeof S!="string"||!S.trim()?s.push(`${l}: feeds ${JSON.stringify(S)} must be the name of a queue source on this service \u2014 read without it`):t.some(d=>d.kind==="queue"&&d.name===S)?i.feeds=S:s.push(`${l}: feeds ${JSON.stringify(S)} names no queue source on this service \u2014 read without it`);return{sources:t,problems:s}}b(parseSourceDecls,"parseSourceDecls"),g(parseSourceDecls,"parseSourceDecls"),u(parseSourceDecls,"parseSourceDecls");const ISO_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/,isIso=u(e=>typeof e=="string"&&ISO_RE.test(e)&&!Number.isNaN(Date.parse(e)),"isIso"),isCount=u(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,"isCount"),notSchema=u((e,t)=>`schema is ${e===void 0?"absent":JSON.stringify(e).slice(0,60)}, not "${t}"`,"notSchema"),keyWrong=u((e,t,s)=>{if(typeof e!="string"||e.length===0||e.length>200)return`${t}.key must be a string of 1\u2013200 characters`;if(s.has(e))return`${t}.key ${JSON.stringify(e)} appears twice`;s.add(e)},"keyWrong"),labelsWrong=u((e,t)=>{if(e===void 0)return;if(!isObj(e))return`${t}.labels must be an object of strings`;const s=Object.entries(e);if(s.length>16)return`${t}.labels has more than 16 entries`;for(const[n,i]of s)if(n.length===0||n.length>64||typeof i!="string"||i.length>200)return`${t}.labels.${n.slice(0,64)} must be a string of at most 200 characters`},"labelsWrong"),overCap=u((e,t)=>`${e} ${t} \u2014 at most ${exports.SOURCE_MAX_GROUPS}; cap them and say \`truncated: { ${t}: <dropped> }\``,"overCap");function parseQueueSnapshot(e){const t=u(d=>({ok:!1,reason:d}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.QUEUE_WIRE_SCHEMA)return t(notSchema(e.schema,exports.QUEUE_WIRE_SCHEMA));const s=e.at;if(!isIso(s))return t("`at` is not an ISO time");const n=e.truncated;if(n!==void 0&&!(isObj(n)&&isCount(n.groups)))return t("`truncated` must be { groups: <how many were dropped> }, or absent");const i=e.groups;if(!Array.isArray(i))return t("`groups` is not a list");if(i.length>exports.SOURCE_MAX_GROUPS)return t(overCap(i.length,"groups"));const l=new Set,S=[];for(let d=0;d<i.length;d++){const r=i[d],a=`groups[${d}]`;if(!isObj(r))return t(`${a} is not an object`);const p=keyWrong(r.key,a,l);if(p)return t(p);if(!isCount(r.pending))return t(`${a}.pending must be a whole number \u2265 0`);for(const A of["inFlight","failed","completedInWindow"])if(r[A]!==void 0&&!isCount(r[A]))return t(`${a}.${A} must be a whole number \u2265 0, or absent`);const R=r.oldestPendingAt;if(R!=null&&!isIso(R))return t(`${a}.oldestPendingAt must be an ISO time, null, or absent`);const h=r.labels,m=labelsWrong(h,a);if(m)return t(m);S.push({key:r.key,...h!==void 0?{labels:h}:{},pending:r.pending,...r.inFlight!==void 0?{inFlight:r.inFlight}:{},...r.failed!==void 0?{failed:r.failed}:{},...R!==void 0?{oldestPendingAt:R}:{},...r.completedInWindow!==void 0?{completedInWindow:r.completedInWindow}:{}})}return{ok:!0,at:s,groups:S,...n!==void 0?{truncated:{groups:n.groups}}:{}}}b(parseQueueSnapshot,"parseQueueSnapshot"),g(parseQueueSnapshot,"parseQueueSnapshot"),u(parseQueueSnapshot,"parseQueueSnapshot");const LOOP_COUNTS=["lastDurationMs","lastItems","runsInWindow","itemsInWindow","failuresInWindow","windowSec"],cutText=u((e,t)=>{if(e.length<=t)return e;const s=t-1,n=e.charCodeAt(s-1);return`${e.slice(0,n>=55296&&n<=56319?s-1:s)}\u2026`},"cutText");function parseLoopSnapshot(e){const t=u(a=>({ok:!1,reason:a}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.LOOP_WIRE_SCHEMA)return t(notSchema(e.schema,exports.LOOP_WIRE_SCHEMA));const s=e.at;if(!isIso(s))return t("`at` is not an ISO time");const n=e.intervalSec;if(!(typeof n=="number"&&Number.isFinite(n)&&n>0&&n<=exports.LOOP_MAX_INTERVAL_SEC))return t(`\`intervalSec\` must be the loop's own period in seconds, more than 0 and at most ${exports.LOOP_MAX_INTERVAL_SEC}`);const i=e.lastRunAt;if(i===void 0)return t("`lastRunAt` is absent \u2014 say null if the loop has not run since the service started");if(i!==null&&!isIso(i))return t("`lastRunAt` must be an ISO time, or null if the loop has not run since the service started");for(const a of LOOP_COUNTS)if(e[a]!==void 0&&!isCount(e[a]))return t(`\`${a}\` must be a whole number \u2265 0, or absent`);const l=e.lastOutcome;if(l!==void 0&&!exports.LOOP_OUTCOMES.includes(l))return t(`\`lastOutcome\` must be ${exports.LOOP_OUTCOMES.join(", ")}, or absent`);const S=e.nextRunAt;if(S!=null&&!isIso(S))return t("`nextRunAt` must be an ISO time, null, or absent");const d=e.lastError;if(d!==void 0&&typeof d!="string")return t("`lastError` must be a string, or absent");const r=u(a=>e[a]!==void 0?{[a]:e[a]}:{},"count");return{ok:!0,loop:{at:s,intervalSec:n,lastRunAt:i,...r("lastDurationMs"),...l!==void 0?{lastOutcome:l}:{},...r("lastItems"),...S!==void 0?{nextRunAt:S}:{},...r("runsInWindow"),...r("itemsInWindow"),...r("failuresInWindow"),...r("windowSec"),...d!==void 0?{lastError:cutText(d,exports.SOURCE_ERROR_MAX)}:{}}}}b(parseLoopSnapshot,"parseLoopSnapshot"),g(parseLoopSnapshot,"parseLoopSnapshot"),u(parseLoopSnapshot,"parseLoopSnapshot");const STORE_COUNTS=["opsInWindow","writesInWindow","deletesInWindow","errorsInWindow","windowSec"];function parseStoreSnapshot(e){const t=u(p=>({ok:!1,reason:p}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.STORE_WIRE_SCHEMA)return t(notSchema(e.schema,exports.STORE_WIRE_SCHEMA));const s=e.at;if(!isIso(s))return t("`at` is not an ISO time");for(const p of["objects","bytes"])if(!isCount(e[p]))return t(`\`${p}\` must be a whole number \u2265 0`);const n=e.quotaBytes;if(n!=null&&!isCount(n))return t("`quotaBytes` must be a whole number \u2265 0, null when it has no quota, or absent");for(const p of STORE_COUNTS)if(e[p]!==void 0&&!isCount(e[p]))return t(`\`${p}\` must be a whole number \u2265 0, or absent`);const i=e.lastWriteAt;if(i!=null&&!isIso(i))return t("`lastWriteAt` must be an ISO time, null, or absent");const l=e.lastError;if(l!==void 0&&typeof l!="string")return t("`lastError` must be a string, or absent");const S=e.truncated;if(S!==void 0&&!(isObj(S)&&isCount(S.groups)))return t("`truncated` must be { groups: <how many were dropped> }, or absent");const d=e.groups;let r;if(d!==void 0){if(!Array.isArray(d))return t("`groups` must be a list, or absent");if(d.length>exports.SOURCE_MAX_GROUPS)return t(overCap(d.length,"groups"));const p=new Set;r=[];for(let R=0;R<d.length;R++){const h=d[R],m=`groups[${R}]`;if(!isObj(h))return t(`${m} is not an object`);const A=keyWrong(h.key,m,p);if(A)return t(A);for(const o of["objects","bytes"])if(!isCount(h[o]))return t(`${m}.${o} must be a whole number \u2265 0`);const I=h.labels,x=labelsWrong(I,m);if(x)return t(x);r.push({key:h.key,...I!==void 0?{labels:I}:{},objects:h.objects,bytes:h.bytes})}}const a=u(p=>e[p]!==void 0?{[p]:e[p]}:{},"count");return{ok:!0,store:{at:s,objects:e.objects,bytes:e.bytes,...n!==void 0?{quotaBytes:n}:{},...a("opsInWindow"),...a("writesInWindow"),...a("deletesInWindow"),...a("errorsInWindow"),...a("windowSec"),...i!==void 0?{lastWriteAt:i}:{},...l!==void 0?{lastError:cutText(l,exports.SOURCE_ERROR_MAX)}:{},...r?{groups:r}:{},...S!==void 0?{truncated:{groups:S.groups}}:{}}}}b(parseStoreSnapshot,"parseStoreSnapshot"),g(parseStoreSnapshot,"parseStoreSnapshot"),u(parseStoreSnapshot,"parseStoreSnapshot");const TRAFFIC_COUNTS=["messagesInWindow","failuresInWindow","rateLimitedInWindow"];function parseTrafficSnapshot(e){const t=u(r=>({ok:!1,reason:r}),"fail");if(!isObj(e))return t("the snapshot is not a JSON object");if(e.schema!==exports.TRAFFIC_WIRE_SCHEMA)return t(notSchema(e.schema,exports.TRAFFIC_WIRE_SCHEMA));const s=e.at;if(!isIso(s))return t("`at` is not an ISO time");const n=e.windowSec;if(n!==void 0&&!isCount(n))return t("`windowSec` must be a whole number \u2265 0, or absent");const i=e.truncated;if(i!==void 0&&!(isObj(i)&&isCount(i.channels)))return t("`truncated` must be { channels: <how many were dropped> }, or absent");const l=e.channels;if(!Array.isArray(l))return t("`channels` is not a list");if(l.length>exports.SOURCE_MAX_GROUPS)return t(overCap(l.length,"channels"));const S=new Set,d=[];for(let r=0;r<l.length;r++){const a=l[r],p=`channels[${r}]`;if(!isObj(a))return t(`${p} is not an object`);const R=keyWrong(a.key,p,S);if(R)return t(R);const h=a.direction;if(h!==void 0&&!exports.TRAFFIC_DIRECTIONS.includes(h))return t(`${p}.direction must be ${exports.TRAFFIC_DIRECTIONS.join(", ")}, or absent`);const m=a.counterpart;if(m!==void 0&&!(typeof m=="string"&&m.length>0&&m.length<=200))return t(`${p}.counterpart must be a string of 1\u2013200 characters, or absent`);for(const O of TRAFFIC_COUNTS)if(a[O]!==void 0&&!isCount(a[O]))return t(`${p}.${O} must be a whole number \u2265 0, or absent`);const A=a.p95Ms;if(A!==void 0&&!(finite(A)&&A>=0))return t(`${p}.p95Ms must be milliseconds \u2265 0, or absent`);const I=a.lastAt;if(I!=null&&!isIso(I))return t(`${p}.lastAt must be an ISO time, null, or absent`);const x=a.lastError;if(x!==void 0&&typeof x!="string")return t(`${p}.lastError must be a string, or absent`);const o=a.labels,c=labelsWrong(o,p);if(c)return t(c);const f=u(O=>a[O]!==void 0?{[O]:a[O]}:{},"count");d.push({key:a.key,...o!==void 0?{labels:o}:{},...h!==void 0?{direction:h}:{},...m!==void 0?{counterpart:m}:{},...f("messagesInWindow"),...f("failuresInWindow"),...f("rateLimitedInWindow"),...A!==void 0?{p95Ms:A}:{},...I!==void 0?{lastAt:I}:{},...x!==void 0?{lastError:cutText(x,exports.SOURCE_ERROR_MAX)}:{}})}return{ok:!0,traffic:{at:s,...n!==void 0?{windowSec:n}:{},channels:d,...i!==void 0?{truncated:{channels:i.channels}}:{}}}}b(parseTrafficSnapshot,"parseTrafficSnapshot"),g(parseTrafficSnapshot,"parseTrafficSnapshot"),u(parseTrafficSnapshot,"parseTrafficSnapshot");const sourceFull=u((e,t)=>({[exports.SOURCE_SNAPSHOT_FIELD[e]]:t}),"sourceFull");exports.sourceFull=sourceFull;const declRaw=u(e=>({sourceKind:e.kind,name:e.name,...e.path!==void 0?{path:e.path}:{},intervalSec:e.intervalSec,thresholds:{...e.thresholds},...e.feeds!==void 0?{feeds:e.feeds}:{}}),"declRaw"),canonical=u(e=>{if(Array.isArray(e))return e.map(canonical);if(!isObj(e))return e;const t={};for(const s of Object.keys(e).sort())t[s]=canonical(e[s]);return t},"canonical");function sourceDigest(e){return(0,node_crypto_1.createHash)("sha1").update(JSON.stringify(canonical(e))??"null").digest("hex").slice(0,16)}b(sourceDigest,"sourceDigest"),g(sourceDigest,"sourceDigest"),u(sourceDigest,"sourceDigest");const oldestOf=u(e=>e.pending>0&&e.oldestPendingAt?Date.parse(e.oldestPendingAt):Number.POSITIVE_INFINITY,"oldestOf");function keepQueueSnapshot(e,t,s,n){const i={groups:t.length,pending:0,inFlight:0,failed:0};let l;for(const r of t)i.pending+=r.pending,i.inFlight+=r.inFlight??0,i.failed+=r.failed??0,r.completedInWindow!==void 0&&(l=(l??0)+r.completedInWindow);l!==void 0&&(i.completedInWindow=l);const S=[...t].sort((r,a)=>oldestOf(r)-oldestOf(a)||a.pending-r.pending||(r.key<a.key?-1:r.key>a.key?1:0)).map(({key:r,...a})=>({group:r,...a})),d=n?{groups:n.groups}:void 0;return{at:e,receivedAt:s,totals:i,groups:S,...d?{truncated:d}:{},digest:sourceDigest({groups:S,truncated:d??null})}}b(keepQueueSnapshot,"keepQueueSnapshot"),g(keepQueueSnapshot,"keepQueueSnapshot"),u(keepQueueSnapshot,"keepQueueSnapshot");function keepLoopSnapshot(e,t){const{at:s,...n}=e;return{at:s,receivedAt:t,digest:sourceDigest(n),...n}}b(keepLoopSnapshot,"keepLoopSnapshot"),g(keepLoopSnapshot,"keepLoopSnapshot"),u(keepLoopSnapshot,"keepLoopSnapshot");const byKey=u((e,t)=>e<t?-1:e>t?1:0,"byKey");function keepStoreSnapshot(e,t){const{at:s,groups:n,truncated:i,...l}=e,S=n?[...n].sort((r,a)=>a.bytes-r.bytes||a.objects-r.objects||byKey(r.key,a.key)).map(({key:r,...a})=>({group:r,...a})):void 0,d={...l,...S?{groups:S}:{},...i?{truncated:{groups:i.groups}}:{}};return{at:s,receivedAt:t,digest:sourceDigest(d),...d}}b(keepStoreSnapshot,"keepStoreSnapshot"),g(keepStoreSnapshot,"keepStoreSnapshot"),u(keepStoreSnapshot,"keepStoreSnapshot");const messagesOf=u(e=>e.messagesInWindow??-1,"messagesOf");function keepTrafficSnapshot(e,t){const{at:s,channels:n,truncated:i,...l}=e,S=[...n].sort((r,a)=>messagesOf(a)-messagesOf(r)||byKey(r.key,a.key)).map(({key:r,...a})=>({channel:r,...a})),d={...l,channels:S,...i?{truncated:{channels:i.channels}}:{}};return{at:s,receivedAt:t,digest:sourceDigest(d),...d}}b(keepTrafficSnapshot,"keepTrafficSnapshot"),g(keepTrafficSnapshot,"keepTrafficSnapshot"),u(keepTrafficSnapshot,"keepTrafficSnapshot");const sourceSame=u(e=>({digest:e.digest,at:e.at,receivedAt:e.receivedAt}),"sourceSame");exports.sourceSame=sourceSame;function buildSourcePollRaw(e,t,s,n,i,l){return{kind:"source-poll",provenance:"reported",project:e,...declRaw(t),state:s.state,...s.detail!==void 0?{detail:s.detail}:{},...s.status!==void 0?{status:s.status}:{},polledAt:s.polledAt,...s.durationMs!==void 0?{durationMs:s.durationMs}:{},reportEveryMs:n,...i>0?{failures:i}:{},...l??{}}}b(buildSourcePollRaw,"buildSourcePollRaw"),g(buildSourcePollRaw,"buildSourcePollRaw"),u(buildSourcePollRaw,"buildSourcePollRaw");function buildSourceDeclarationRaw(e,t){return{kind:"source-declaration",project:e,sources:t.sources.map(declRaw),problems:[...t.problems]}}b(buildSourceDeclarationRaw,"buildSourceDeclarationRaw"),g(buildSourceDeclarationRaw,"buildSourceDeclarationRaw"),u(buildSourceDeclarationRaw,"buildSourceDeclarationRaw");const span=u(e=>{const t=Math.round(e/6e4);return e<6e4?`${Math.max(0,Math.round(e/1e3))}s`:t<120?`${t}m`:`${Math.floor(t/60)}h${t%60?` ${t%60}m`:""}`},"span"),loopWords=u(e=>`${e.lastRunAt===null?"has not run since the service started":`last run ${span(Math.max(0,Date.parse(e.at)-Date.parse(e.lastRunAt)))} before it was measured`}${e.lastOutcome?`, ${e.lastOutcome}`:""}${e.lastItems!==void 0?`, ${e.lastItems} item${e.lastItems===1?"":"s"}`:""}`,"loopWords"),plural=u((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),byteSize=u(e=>{const t=["B","kB","MB","GB","TB","PB"];let s=e,n=0;for(;s>=999.5&&n<t.length-1;)s/=1e3,n+=1;return n===0?`${e} B`:`${s<9.95?s.toFixed(1):Math.round(s)} ${t[n]}`},"byteSize"),storeWords=u(e=>{const t=typeof e.quotaBytes=="number"&&e.quotaBytes>0?` of ${byteSize(e.quotaBytes)} (${Math.round(e.bytes/e.quotaBytes*1e3)/10}%)`:"",s=e.errorsInWindow?`, ${plural(e.errorsInWindow,"error")}${e.windowSec?` in ${span(e.windowSec*1e3)}`:""}`:"";return`${plural(e.objects,"object")}, ${byteSize(e.bytes)}${t}${s}`},"storeWords"),trafficWords=u(e=>{let t,s=0,n=0;for(const l of e.channels)l.messagesInWindow!==void 0&&(t=(t??0)+l.messagesInWindow),s+=l.failuresInWindow??0,n+=l.rateLimitedInWindow??0;const i=t!==void 0?`, ${plural(t,"message")}${e.windowSec?` in ${span(e.windowSec*1e3)}`:""}`:"";return`${plural(e.channels.length,"channel")}${i}${s?`, ${s} failed`:""}${n?`, ${n} rate-limited`:""}`},"trafficWords");function sourcePollTitle(e,t){const s=`${e.sourceKind} ${e.project}/${e.name} (reported)`,n=t??e[exports.SOURCE_SNAPSHOT_FIELD[e.sourceKind]];if(e.state!=="current"||!n)return`${s}: ${e.state}${e.detail?` \u2014 ${e.detail}`:""}`;if(e.sourceKind==="loop")return`${s}: ${loopWords(n)}`;if(e.sourceKind==="store")return`${s}: ${storeWords(n)}`;if(e.sourceKind==="traffic")return`${s}: ${trafficWords(n)}`;const i=n,l=i.groups.find(d=>d.pending>0&&d.oldestPendingAt),S=l?.oldestPendingAt?Date.parse(i.at)-Date.parse(l.oldestPendingAt):void 0;return`${s}: ${i.totals.pending} pending in ${i.totals.groups} group${i.totals.groups===1?"":"s"}${S!==void 0?`, oldest waiting ${span(Math.max(0,S))}`:""}`}b(sourcePollTitle,"sourcePollTitle"),g(sourcePollTitle,"sourcePollTitle"),u(sourcePollTitle,"sourcePollTitle");function requestOverSocket(e,t,s,n,i=exports.SOURCE_MAX_BYTES){return new Promise(l=>{let S=!1,d;const r=u(p=>{S||(S=!0,clearTimeout(a),l(p))},"finish"),a=setTimeout(()=>{r({ok:!1,code:"ETIMEDOUT",message:`no answer within ${n} ms`}),d?.destroy()},n);a.unref?.();try{d=http.request({socketPath:e,path:t,method:"GET",agent:!1,headers:s},p=>{const R=[];let h=0;p.on("data",m=>{if(!S){if(h+=m.length,h>i){r({ok:!0,status:p.statusCode??0,body:"",truncated:!0}),p.destroy();return}R.push(m)}}),p.on("end",()=>r({ok:!0,status:p.statusCode??0,body:Buffer.concat(R).toString("utf8"),truncated:!1})),p.on("error",m=>r({ok:!1,code:m.code??"ERESPONSE",message:m.message}))}),d.on("error",p=>r({ok:!1,code:p.code??"EREQUEST",message:p.message})),d.end()}catch(p){r({ok:!1,code:p.code??"EREQUEST",message:p.message})}})}b(requestOverSocket,"requestOverSocket"),g(requestOverSocket,"requestOverSocket"),u(requestOverSocket,"requestOverSocket");const snippet=u(e=>e.replace(/\s+/g," ").trim().slice(0,160),"snippet");function readSnapshot(e,t,s){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:`not JSON: ${snippet(t)||"(an empty body)"}`}}if(e==="loop"){const l=parseLoopSnapshot(n);return l.ok===!0?{ok:!0,kept:keepLoopSnapshot(l.loop,s)}:l}if(e==="store"){const l=parseStoreSnapshot(n);return l.ok===!0?{ok:!0,kept:keepStoreSnapshot(l.store,s)}:l}if(e==="traffic"){const l=parseTrafficSnapshot(n);return l.ok===!0?{ok:!0,kept:keepTrafficSnapshot(l.traffic,s)}:l}const i=parseQueueSnapshot(n);return i.ok===!0?{ok:!0,kept:keepQueueSnapshot(i.at,i.groups,s,i.truncated)}:i}b(readSnapshot,"readSnapshot"),g(readSnapshot,"readSnapshot"),u(readSnapshot,"readSnapshot");function createSourcePoller(e){const t=e.now??Date.now,s=e.timeoutMs??(0,exports.sourcesTimeoutMs)(),n=Math.max(1,e.maxConcurrent??(0,exports.sourcesConcurrency)()),i=e.socketOf??(o=>(0,discovery_1.pickSock)(o.pool,e.scanTtlMs??1500)),l=e.request??requestOverSocket,S=e.log??(o=>console.warn(o)),d=new WeakMap,r=new Map;let a=0,p;const R=u(o=>{const c=o.decl;let f=d.get(c);if(!f){f=parseSourceDecls(o.decl.sources),d.set(c,f);for(const E of f.problems)S(`[gateway] ${o.project}: cluster.sources \u2014 ${E}`)}const O=t();return(f.reportedAt===void 0||O-f.reportedAt>=exports.SOURCE_DECLARATION_REPORT_MS)&&(f.reportedAt=O,e.emit(o,f.problems.length?"warning":"info",f.problems.length?`sources ${o.project}: ${f.problems.length} cluster.sources entr${f.problems.length===1?"y":"ies"} not read \u2014 ${f.problems[0]}`:`sources ${o.project}: reads ${f.sources.map(E=>`${E.kind} "${E.name}"${isPolled(E)?"":" (push-only)"}`).join(", ")}`,`source-declaration:${o.wsKey}:${o.project}`,buildSourceDeclarationRaw(o.project,f))),f},"declarationOf"),h=u(o=>{if(o.state==="starting")return{notRunning:"it is starting \u2014 read once it is up"};const c=i(o);return c?{socket:c}:{notRunning:o.state==="up"?"it has no live pod socket \u2014 no pod runs it now":"it is scaled to zero \u2014 the lens does not start a service to read a source"}},"reach"),m=u((o,c)=>{const f=o.good;if(f)return o.full&&o.full.digest===f.digest&&c-o.full.at<exports.SOURCE_FULL_REPORT_MS?{same:(0,exports.sourceSame)(f)}:(o.full={digest:f.digest,at:c},(0,exports.sourceFull)(o.decl.kind,f))},"carried"),A=u((o,c)=>{const f=o.last;if(!f)return;const O=t();if(!c&&o.reportedAt!==void 0&&O-o.reportedAt<o.reportEveryMs)return;o.reportedAt=O;const E=buildSourcePollRaw(o.svc.project,o.decl,f,o.reportEveryMs,o.failures,m(o,O)),_=f.state==="unreachable"||f.state==="refused"||f.state==="malformed";e.emit(o.svc,_?"warning":"info",sourcePollTitle(E,o.good),`source:${o.svc.wsKey}:${o.svc.project}:${o.decl.name}`,E)},"report"),I=u(async o=>{const c=t(),f=o.decl.intervalSec*1e3;o.inFlight=!0,a+=1;const O=o.last?.state;try{const E=h(o.svc);if("notRunning"in E){o.last={state:"not-running",detail:E.notRunning,polledAt:c},o.failures=0,o.nextAt=c+f,o.reportEveryMs=exports.SOURCE_NOT_RUNNING_REPORT_MS,A(o,O!=="not-running");return}const _=e.serviceKey(o.svc),T=await l(E.socket,o.decl.path,{accept:"application/json","x-lensmcp-probe":`source:${o.decl.kind}`,..._?{"x-internal-token":_}:{}},s,exports.SOURCE_MAX_BYTES),$=Math.max(0,t()-c);if(T.ok===!1){const v=T.code==="ECONNREFUSED"||T.code==="ENOENT";o.last=v&&o.svc.state!=="up"?{state:"not-running",detail:`nothing listens on its pod socket \u2014 the service is ${o.svc.state}`,polledAt:c,durationMs:$}:{state:"unreachable",detail:T.code==="ETIMEDOUT"?T.message:`${T.code}: ${snippet(T.message)}`,polledAt:c,durationMs:$}}else if(T.status<200||T.status>299){const v=snippet(T.body);o.last={state:"refused",status:T.status,detail:`HTTP ${T.status}${v?`: ${v}`:""}`,polledAt:c,durationMs:$}}else if(T.truncated)o.last={state:"malformed",detail:`the snapshot is larger than ${exports.SOURCE_MAX_BYTES/1024} KiB`,polledAt:c,durationMs:$};else{const v=readSnapshot(o.decl.kind,T.body,t());v.ok===!0?(o.good=v.kept,o.last={state:"current",polledAt:c,durationMs:$}):o.last={state:"malformed",detail:v.reason,polledAt:c,durationMs:$}}const M=o.last.state==="unreachable"||o.last.state==="refused"||o.last.state==="malformed";o.failures=M?o.failures+1:0;const y=M?sourceBackoffMs(f,o.failures):f;o.nextAt=c+y,o.reportEveryMs=o.last.state==="not-running"?exports.SOURCE_NOT_RUNNING_REPORT_MS:y,A(o,o.last.state!=="not-running"||O!=="not-running")}catch(E){o.last={state:"unreachable",detail:`the poll failed: ${snippet(E?.message??String(E))}`,polledAt:c},o.failures+=1,o.nextAt=c+sourceBackoffMs(f,o.failures),o.reportEveryMs=o.nextAt-c,A(o,!0)}finally{o.inFlight=!1,a-=1}},"pollOne"),x=u(async()=>{if(e.stopped?.())return;const o=new Set;for(const E of e.services())if(E.decl.sources!==void 0)for(const _ of R(E).sources){if(!isPolled(_))continue;const T=`${E.wsKey} ${E.project} ${_.kind} ${_.name}`;o.add(T);const $=r.get(T);$?($.svc!==E||$.decl!==_)&&($.svc=E,$.decl=_):r.set(T,{svc:E,decl:_,nextAt:0,inFlight:!1,failures:0,reportEveryMs:_.intervalSec*1e3})}for(const[E,_]of[...r.entries()])!o.has(E)&&!_.inFlight&&r.delete(E);const c=t(),f=[...r.values()].filter(E=>!E.inFlight&&c>=E.nextAt).sort((E,_)=>E.nextAt-_.nextAt),O=[];for(const E of f){if(a>=n)break;O.push(I(E))}await Promise.all(O)},"tick");return{tick:x,start(o=1e3){return p&&clearInterval(p),p=setInterval(()=>{x().catch(c=>console.error("[gateway] source poll error:",c))},o),p.unref(),p},stop(){p&&clearInterval(p),p=void 0},snapshot(){const o=t();return[...r.values()].map(c=>{const f=c.last!==void 0&&o-c.last.polledAt>(0,exports.sourceStaleAfterMs)(c.reportEveryMs);return{wsKey:c.svc.wsKey,project:c.svc.project,name:c.decl.name,kind:c.decl.kind,path:c.decl.path,state:c.last?f?"stale":c.last.state:"never-polled",...c.last?.detail!==void 0?{detail:c.last.detail}:{},...c.last?.status!==void 0?{status:c.last.status}:{},...c.last?{polledAt:c.last.polledAt}:{},failures:c.failures,nextAt:c.nextAt,...c.good?{...(0,exports.sourceFull)(c.decl.kind,c.good),ageMs:Math.max(0,o-c.good.receivedAt)}:{}}})}}}b(createSourcePoller,"createSourcePoller"),g(createSourcePoller,"createSourcePoller"),u(createSourcePoller,"createSourcePoller");
@@ -1 +1 @@
1
- "use strict";var O=Object.defineProperty;var e=(_,E)=>O(_,"name",{value:E,configurable:!0});var M=Object.defineProperty,R=e((_,E)=>M(_,"name",{value:E,configurable:!0}),"R");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_RESET_RATE=exports.GATEWAY_H2_RESET_BURST=exports.BODY_STALL_MS=exports.GATEWAY_CONN_CHECK_MS=exports.GATEWAY_MAX_CONNECTIONS=exports.GATEWAY_STOP_GRACE_MS=exports.GATEWAY_HEADERS_TIMEOUT_MS=exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=exports.LENS_REQUEST_RECOVERY_WAIT_MS=exports.LENS_REPLACEMENT_DRAIN_MS=exports.LENS_REPLACEMENT_READY_MS=exports.LENS_RESTART_MODE=exports.LENS_RECYCLE_KILL_GRACE_MS=exports.LENS_PARKED_PORT_REPROBE_MS=exports.MAX_PORT_CONFLICT_RETRIES=exports.CHILD_START_FAIL_MS=exports.PORT_FREE_POLL_MS=exports.PORT_FREE_WAIT_MS=exports.LENS_PROBE_BOOT_GRACE_MS=exports.LENS_PROBE_COOLDOWN_MS=exports.LENS_PROBE_TIMEOUT_MS=exports.LENS_PROBE_FAILS=exports.LENS_PROBE_GRACE_MS=exports.MAX_COLD_STARTS=exports.POD_MAX_CONCURRENT_ROLLS=exports.POD_ROLL_READY_MS=exports.POD_RECYCLE_MODE=exports.POD_WATCHER_SILENT=exports.POD_WATCHER_UNVERIFIED=exports.LENS_WATCH_SCOPE_ENABLED=exports.LENS_WATCHER_UNVERIFIED=exports.LENS_WATCHER_PROBE_ENABLED=exports.LENS_PROBE_ENABLED=exports.POD_STALE_RECYCLE_COOLDOWN_MS=exports.POD_STALE_SCAN_MS=exports.POD_RECYCLE_SETTLE_MS=exports.POD_STALE_GRACE_MS=exports.POD_MAX_AGE_MS=exports.POD_RECYCLE_ENABLED=exports.WEDGE_RECYCLE_GRACE_MS=exports.POD_ALIVE_PATH=exports.POD_WEDGE_CONFIRM_MS=exports.POD_ALIVE_PROBE_TIMEOUT_MS=exports.POD_SLOW_FIRST_BYTE_MS=exports.POD_RESPONSE_TIMEOUT_MS=exports.UPSTREAM_HEAL_STEP_MS=exports.UPSTREAM_HEAL_WINDOW_MS=exports.SERVICE_RESTART_WINDOW_MS=exports.SERVICE_MAX_RESTARTS=exports.SERVICE_ERROR_THROTTLE_MS=void 0;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os"));function envInt(_,E,L=!1){const S=Number(process.env[_]);return!Number.isFinite(S)||S<0?E:S===0?L?0:E:S}e(envInt,"envInt"),R(envInt,"envInt"),exports.SERVICE_ERROR_THROTTLE_MS=5e3,exports.SERVICE_MAX_RESTARTS=5,exports.SERVICE_RESTART_WINDOW_MS=6e4,exports.UPSTREAM_HEAL_WINDOW_MS=8e3,exports.UPSTREAM_HEAL_STEP_MS=300,exports.POD_RESPONSE_TIMEOUT_MS=(()=>{const _=Number(process.env.LENSMCP_POD_RESPONSE_TIMEOUT_MS);return Number.isFinite(_)&&_>0?_:3e4})(),exports.POD_SLOW_FIRST_BYTE_MS=envInt("LENSMCP_POD_SLOW_FIRST_BYTE_MS",10*6e4,!0),exports.POD_ALIVE_PROBE_TIMEOUT_MS=envInt("LENSMCP_POD_ALIVE_PROBE_TIMEOUT_MS",1e3),exports.POD_WEDGE_CONFIRM_MS=envInt("LENSMCP_POD_WEDGE_CONFIRM_MS",1e4,!0),exports.POD_ALIVE_PATH="/__lensmcp/alive",exports.WEDGE_RECYCLE_GRACE_MS=(()=>{const _=Number(process.env.LENSMCP_WEDGE_RECYCLE_GRACE_MS);return Number.isFinite(_)&&_>0?_:15e3})(),exports.POD_RECYCLE_ENABLED=process.env.LENSMCP_POD_RECYCLE!=="0",exports.POD_MAX_AGE_MS=envInt("LENSMCP_POD_MAX_AGE_MS",240*6e4,!0),exports.POD_STALE_GRACE_MS=envInt("LENSMCP_POD_STALE_GRACE_MS",1e4),exports.POD_RECYCLE_SETTLE_MS=envInt("LENSMCP_POD_RECYCLE_SETTLE_MS",8e3),exports.POD_STALE_SCAN_MS=envInt("LENSMCP_POD_STALE_SCAN_MS",3e4),exports.POD_STALE_RECYCLE_COOLDOWN_MS=envInt("LENSMCP_POD_STALE_RECYCLE_COOLDOWN_MS",6e4),exports.LENS_PROBE_ENABLED=process.env.LENSMCP_LENS_PROBE!=="0",exports.LENS_WATCHER_PROBE_ENABLED=process.env.LENSMCP_LENS_WATCHER_PROBE!=="0",exports.LENS_WATCHER_UNVERIFIED=process.env.LENSMCP_LENS_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.LENS_WATCH_SCOPE_ENABLED=process.env.LENSMCP_LENS_WATCH_SCOPE!=="0",exports.POD_WATCHER_UNVERIFIED=process.env.LENSMCP_POD_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.POD_WATCHER_SILENT=process.env.LENSMCP_POD_WATCHER_SILENT==="recycle"?"recycle":"keep",exports.POD_RECYCLE_MODE=process.env.LENSMCP_POD_RECYCLE_MODE==="in-place"?"in-place":"rolling",exports.POD_ROLL_READY_MS=envInt("LENSMCP_POD_ROLL_READY_MS",18e4),exports.POD_MAX_CONCURRENT_ROLLS=envInt("LENSMCP_POD_MAX_CONCURRENT_ROLLS",2,!0),exports.MAX_COLD_STARTS=envInt("LENSMCP_MAX_COLD_STARTS",Math.max(2,Math.floor(os.availableParallelism()/2)),!0),exports.LENS_PROBE_GRACE_MS=envInt("LENSMCP_LENS_PROBE_GRACE_MS",45e3),exports.LENS_PROBE_FAILS=envInt("LENSMCP_LENS_PROBE_FAILS",2),exports.LENS_PROBE_TIMEOUT_MS=envInt("LENSMCP_LENS_PROBE_TIMEOUT_MS",1e3),exports.LENS_PROBE_COOLDOWN_MS=envInt("LENSMCP_LENS_PROBE_COOLDOWN_MS",3e4),exports.LENS_PROBE_BOOT_GRACE_MS=envInt("LENSMCP_LENS_PROBE_BOOT_GRACE_MS",24e4),exports.PORT_FREE_WAIT_MS=envInt("LENSMCP_PORT_FREE_WAIT_MS",1e4),exports.PORT_FREE_POLL_MS=envInt("LENSMCP_PORT_FREE_POLL_MS",250),exports.CHILD_START_FAIL_MS=envInt("LENSMCP_CHILD_START_FAIL_MS",1e4),exports.MAX_PORT_CONFLICT_RETRIES=envInt("LENSMCP_MAX_PORT_CONFLICT_RETRIES",5),exports.LENS_PARKED_PORT_REPROBE_MS=envInt("LENSMCP_PARKED_PORT_REPROBE_MS",3e5),exports.LENS_RECYCLE_KILL_GRACE_MS=envInt("LENSMCP_RECYCLE_KILL_GRACE_MS",5e3),exports.LENS_RESTART_MODE=process.env.LENSMCP_LENS_RESTART_MODE==="in-place"?"in-place":"rolling",exports.LENS_REPLACEMENT_READY_MS=envInt("LENSMCP_LENS_REPLACEMENT_READY_MS",3e4),exports.LENS_REPLACEMENT_DRAIN_MS=envInt("LENSMCP_LENS_REPLACEMENT_DRAIN_MS",2e3,!0),exports.LENS_REQUEST_RECOVERY_WAIT_MS=envInt("LENSMCP_LENS_REQUEST_RECOVERY_WAIT_MS",15e3),exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=envInt("LENSMCP_KEEPALIVE_TIMEOUT_MS",76e3),exports.GATEWAY_HEADERS_TIMEOUT_MS=envInt("LENSMCP_HEADERS_TIMEOUT_MS",6e4),exports.GATEWAY_STOP_GRACE_MS=envInt("LENSMCP_STOP_GRACE_MS",3e3),exports.GATEWAY_MAX_CONNECTIONS=envInt("LENSMCP_MAX_CONNECTIONS",0,!0),exports.GATEWAY_CONN_CHECK_MS=envInt("LENSMCP_CONN_CHECK_MS",0,!0),exports.BODY_STALL_MS=envInt("LENSMCP_BODY_STALL_MS",6e4,!0),exports.GATEWAY_H2_RESET_BURST=envInt("LENSMCP_H2_RESET_BURST",1e5),exports.GATEWAY_H2_RESET_RATE=envInt("LENSMCP_H2_RESET_RATE",1e4);
1
+ "use strict";var C=Object.defineProperty;var L=(_,E)=>C(_,"name",{value:E,configurable:!0});var O=Object.defineProperty,e=L((_,E)=>O(_,"name",{value:E,configurable:!0}),"e"),M=Object.defineProperty,R=e((_,E)=>M(_,"name",{value:E,configurable:!0}),"R");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_RESET_RATE=exports.GATEWAY_H2_RESET_BURST=exports.BODY_STALL_MS=exports.GATEWAY_CONN_CHECK_MS=exports.GATEWAY_MAX_CONNECTIONS=exports.GATEWAY_STOP_GRACE_MS=exports.GATEWAY_HEADERS_TIMEOUT_MS=exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=exports.LENS_REQUEST_RECOVERY_WAIT_MS=exports.LENS_REPLACEMENT_DRAIN_MS=exports.LENS_REPLACEMENT_READY_MS=exports.LENS_RESTART_MODE=exports.LENS_RECYCLE_KILL_GRACE_MS=exports.LENS_PARKED_PORT_REPROBE_MS=exports.MAX_PORT_CONFLICT_RETRIES=exports.CHILD_START_FAIL_MS=exports.PORT_FREE_POLL_MS=exports.PORT_FREE_WAIT_MS=exports.LENS_PROBE_BOOT_GRACE_MS=exports.LENS_PROBE_COOLDOWN_MS=exports.LENS_PROBE_TIMEOUT_MS=exports.LENS_PROBE_FAILS=exports.LENS_PROBE_GRACE_MS=exports.MAX_COLD_STARTS=exports.POD_MAX_CONCURRENT_ROLLS=exports.POD_ROLL_READY_MS=exports.POD_RECYCLE_MODE=exports.POD_WATCHER_SILENT=exports.POD_WATCHER_UNVERIFIED=exports.LENS_WATCH_SCOPE_ENABLED=exports.LENS_WATCHER_UNVERIFIED=exports.LENS_WATCHER_PROBE_ENABLED=exports.LENS_PROBE_ENABLED=exports.POD_STALE_RECYCLE_COOLDOWN_MS=exports.POD_STALE_SCAN_MS=exports.POD_RECYCLE_SETTLE_MS=exports.POD_STALE_GRACE_MS=exports.POD_MAX_AGE_MS=exports.POD_RECYCLE_ENABLED=exports.WEDGE_RECYCLE_GRACE_MS=exports.POD_ALIVE_PATH=exports.POD_WEDGE_CONFIRM_MS=exports.POD_ALIVE_PROBE_TIMEOUT_MS=exports.POD_SLOW_FIRST_BYTE_MS=exports.POD_RESPONSE_TIMEOUT_MS=exports.UPSTREAM_HEAL_STEP_MS=exports.UPSTREAM_HEAL_WINDOW_MS=exports.SERVICE_RESTART_WINDOW_MS=exports.SERVICE_MAX_RESTARTS=exports.SERVICE_ERROR_THROTTLE_MS=void 0;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os"));function envInt(_,E,T=!1){const S=Number(process.env[_]);return!Number.isFinite(S)||S<0?E:S===0?T?0:E:S}L(envInt,"envInt"),e(envInt,"envInt"),R(envInt,"envInt"),exports.SERVICE_ERROR_THROTTLE_MS=5e3,exports.SERVICE_MAX_RESTARTS=5,exports.SERVICE_RESTART_WINDOW_MS=6e4,exports.UPSTREAM_HEAL_WINDOW_MS=8e3,exports.UPSTREAM_HEAL_STEP_MS=300,exports.POD_RESPONSE_TIMEOUT_MS=(()=>{const _=Number(process.env.LENSMCP_POD_RESPONSE_TIMEOUT_MS);return Number.isFinite(_)&&_>0?_:3e4})(),exports.POD_SLOW_FIRST_BYTE_MS=envInt("LENSMCP_POD_SLOW_FIRST_BYTE_MS",10*6e4,!0),exports.POD_ALIVE_PROBE_TIMEOUT_MS=envInt("LENSMCP_POD_ALIVE_PROBE_TIMEOUT_MS",1e3),exports.POD_WEDGE_CONFIRM_MS=envInt("LENSMCP_POD_WEDGE_CONFIRM_MS",1e4,!0),exports.POD_ALIVE_PATH="/__lensmcp/alive",exports.WEDGE_RECYCLE_GRACE_MS=(()=>{const _=Number(process.env.LENSMCP_WEDGE_RECYCLE_GRACE_MS);return Number.isFinite(_)&&_>0?_:15e3})(),exports.POD_RECYCLE_ENABLED=process.env.LENSMCP_POD_RECYCLE!=="0",exports.POD_MAX_AGE_MS=envInt("LENSMCP_POD_MAX_AGE_MS",240*6e4,!0),exports.POD_STALE_GRACE_MS=envInt("LENSMCP_POD_STALE_GRACE_MS",1e4),exports.POD_RECYCLE_SETTLE_MS=envInt("LENSMCP_POD_RECYCLE_SETTLE_MS",8e3),exports.POD_STALE_SCAN_MS=envInt("LENSMCP_POD_STALE_SCAN_MS",3e4),exports.POD_STALE_RECYCLE_COOLDOWN_MS=envInt("LENSMCP_POD_STALE_RECYCLE_COOLDOWN_MS",6e4),exports.LENS_PROBE_ENABLED=process.env.LENSMCP_LENS_PROBE!=="0",exports.LENS_WATCHER_PROBE_ENABLED=process.env.LENSMCP_LENS_WATCHER_PROBE!=="0",exports.LENS_WATCHER_UNVERIFIED=process.env.LENSMCP_LENS_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.LENS_WATCH_SCOPE_ENABLED=process.env.LENSMCP_LENS_WATCH_SCOPE!=="0",exports.POD_WATCHER_UNVERIFIED=process.env.LENSMCP_POD_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.POD_WATCHER_SILENT=process.env.LENSMCP_POD_WATCHER_SILENT==="recycle"?"recycle":"keep",exports.POD_RECYCLE_MODE=process.env.LENSMCP_POD_RECYCLE_MODE==="in-place"?"in-place":"rolling",exports.POD_ROLL_READY_MS=envInt("LENSMCP_POD_ROLL_READY_MS",18e4),exports.POD_MAX_CONCURRENT_ROLLS=envInt("LENSMCP_POD_MAX_CONCURRENT_ROLLS",2,!0),exports.MAX_COLD_STARTS=envInt("LENSMCP_MAX_COLD_STARTS",Math.max(2,Math.floor(os.availableParallelism()/2)),!0),exports.LENS_PROBE_GRACE_MS=envInt("LENSMCP_LENS_PROBE_GRACE_MS",45e3),exports.LENS_PROBE_FAILS=envInt("LENSMCP_LENS_PROBE_FAILS",2),exports.LENS_PROBE_TIMEOUT_MS=envInt("LENSMCP_LENS_PROBE_TIMEOUT_MS",1e3),exports.LENS_PROBE_COOLDOWN_MS=envInt("LENSMCP_LENS_PROBE_COOLDOWN_MS",3e4),exports.LENS_PROBE_BOOT_GRACE_MS=envInt("LENSMCP_LENS_PROBE_BOOT_GRACE_MS",24e4),exports.PORT_FREE_WAIT_MS=envInt("LENSMCP_PORT_FREE_WAIT_MS",1e4),exports.PORT_FREE_POLL_MS=envInt("LENSMCP_PORT_FREE_POLL_MS",250),exports.CHILD_START_FAIL_MS=envInt("LENSMCP_CHILD_START_FAIL_MS",1e4),exports.MAX_PORT_CONFLICT_RETRIES=envInt("LENSMCP_MAX_PORT_CONFLICT_RETRIES",5),exports.LENS_PARKED_PORT_REPROBE_MS=envInt("LENSMCP_PARKED_PORT_REPROBE_MS",3e5),exports.LENS_RECYCLE_KILL_GRACE_MS=envInt("LENSMCP_RECYCLE_KILL_GRACE_MS",5e3),exports.LENS_RESTART_MODE=process.env.LENSMCP_LENS_RESTART_MODE==="in-place"?"in-place":"rolling",exports.LENS_REPLACEMENT_READY_MS=envInt("LENSMCP_LENS_REPLACEMENT_READY_MS",3e4),exports.LENS_REPLACEMENT_DRAIN_MS=envInt("LENSMCP_LENS_REPLACEMENT_DRAIN_MS",2e3,!0),exports.LENS_REQUEST_RECOVERY_WAIT_MS=envInt("LENSMCP_LENS_REQUEST_RECOVERY_WAIT_MS",15e3),exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=envInt("LENSMCP_KEEPALIVE_TIMEOUT_MS",76e3),exports.GATEWAY_HEADERS_TIMEOUT_MS=envInt("LENSMCP_HEADERS_TIMEOUT_MS",6e4),exports.GATEWAY_STOP_GRACE_MS=envInt("LENSMCP_STOP_GRACE_MS",3e3),exports.GATEWAY_MAX_CONNECTIONS=envInt("LENSMCP_MAX_CONNECTIONS",0,!0),exports.GATEWAY_CONN_CHECK_MS=envInt("LENSMCP_CONN_CHECK_MS",0,!0),exports.BODY_STALL_MS=envInt("LENSMCP_BODY_STALL_MS",6e4,!0),exports.GATEWAY_H2_RESET_BURST=envInt("LENSMCP_H2_RESET_BURST",1e5),exports.GATEWAY_H2_RESET_RATE=envInt("LENSMCP_H2_RESET_RATE",1e4);
@@ -1 +1 @@
1
- "use strict";var K=Object.defineProperty;var w=(c,s)=>K(c,"name",{value:s,configurable:!0});var M=Object.defineProperty,u=w((c,s)=>M(c,"name",{value:s,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_HMR_REFUSAL_REPORT_MS=void 0,exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),manifest_1=require("../manifest"),discovery_1=require("./discovery"),edge_1=require("./edge"),hmr_reload_1=require("./hmr-reload"),service_keys_1=require("./service-keys");exports.LENS_HMR_REFUSAL_REPORT_MS=1e4;function accountUpgrade(c,s){const i=c.svc;if(!i||s.destroyed)return;i.inflight+=1,i.lastUsed=Date.now();let d=!1;s.once("close",()=>{d||(d=!0,i.inflight-=1,i.lastUsed=Date.now())})}w(accountUpgrade,"accountUpgrade"),u(accountUpgrade,"accountUpgrade");function createUpgrade(c){const{rt:s,auth:i,proxy:d,hooks:p,obs:b}=c,y=new Set,_=u(e=>{e.destroyed||(y.add(e),e.once("close",()=>y.delete(e)))},"track");d.proxy.on?.("open",_);const v=new WeakMap,k=new Map,m=u((e,r)=>{const n=Date.now();n-(k.get(e.frontendKey)??0)<exports.LENS_HMR_REFUSAL_REPORT_MS||(k.set(e.frontendKey,n),console.warn(`[gateway] lens HMR socket refused: ${e.frontendKey} at ${e.target} answered ${r} for a tab on ${e.host} \u2014 that tab loads but gets no hot updates; the lens runtime reloads it once if it had a socket before.`),b?.emit("warning",`lens HMR socket refused: ${e.frontendKey} (${r})`,`cluster-lens-hmr-refused:${e.frontendKey}`,{kind:"lens-hmr-refused",frontendKey:e.frontendKey,host:e.host,target:e.target,answer:r},void 0,e.busFile))},"reportRefusal");d.proxy.on?.("proxyReqWs",(e,r)=>{const n=v.get(r);if(!n)return;const a=e;a.once("upgrade",()=>{n.answered=!0}),a.once("response",g=>{n.answered=!0,m(n,`HTTP ${g.statusCode??"?"}`)})});const S=u(async(e,r,n)=>{(0,edge_1.stripOwnedHeaders)(e);const a=(0,edge_1.canonicalize)(e.url??"/");if(a===void 0){r.destroy();return}e.url=a.path+a.query;const g=(e.headers.host||"").split(":")[0],t=(0,manifest_1.matchRoute)(s.routes,g,a.policy+a.query);if(!t){r.destroy();return}(0,edge_1.resolveClientIp)(s,e);const l=p.upgradeContext(e,r,void 0);if(l.route=t,t.internal){const o=i.internal(e,t,void 0);if(!o.ok){r.destroy();return}l.caller=o.caller}else{const o=i.public(e,t,void 0,a.policy);if(!o.ok){r.destroy();return}if(l.claims=o.claims,p.has("afterAuth")&&(await p.run("afterAuth",l),l.responded()))return}const x=t.pool?s.serviceKeys[(0,service_keys_1.serviceKeyId)(t.svc?.wsKey,t.project)]:void 0;if(x&&(e.headers["x-internal-token"]=x),t.prependPrefix&&!e.url?.startsWith(t.prependPrefix)&&(e.url=t.prependPrefix+(e.url??"/")),(0,edge_1.stampForwardingHeaders)(s,e),p.has("onUpgrade")&&(await p.run("onUpgrade",l),l.responded()))return;const h=t.pool?(()=>{const o=(0,discovery_1.pickSock)(t.pool,s.scanTtlMs);return o?{socketPath:o}:void 0})():t.target;if(!h){r.destroy();return}if(t.lens&&String(e.headers["sec-websocket-protocol"]??"").split(",").map(o=>o.trim()).includes("vite-hmr")){const o=t.lens.workspaceKey?`${t.lens.workspaceKey}:${t.lens.project}`:t.lens.project;(0,hmr_reload_1.registerHmrClient)(s,o,r);const f=!t.lens.workspaceRoot||path.resolve(t.lens.workspaceRoot)===path.resolve(s.root??"");v.set(e,{frontendKey:o,host:g,target:String(h),answered:!1,...f?{}:{busFile:path.join(t.lens.workspaceRoot,".lensmcp","events.jsonl")}})}accountUpgrade(t,r),d.proxy.ws(e,r,n,{target:h,changeOrigin:!t.pool,agent:d.agentForTarget(h)},o=>{const f=v.get(e);f&&!f.answered&&m(f,o?.code??o?.message??"an error"),r.destroy()})},"run"),R=u(((e,r,n)=>{r.on("error",()=>r.destroy()),_(r),S(e,r,n).catch(()=>r.destroy())}),"listener");return R.closeTunnels=()=>{const e=[...y];for(const r of e)r.destroy();return y.clear(),e.length},R}w(createUpgrade,"createUpgrade"),u(createUpgrade,"createUpgrade");
1
+ "use strict";var P=Object.defineProperty;var v=(a,o)=>P(a,"name",{value:o,configurable:!0});var K=Object.defineProperty,w=v((a,o)=>K(a,"name",{value:o,configurable:!0}),"w"),M=Object.defineProperty,u=w((a,o)=>M(a,"name",{value:o,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_HMR_REFUSAL_REPORT_MS=void 0,exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),manifest_1=require("../manifest"),discovery_1=require("./discovery"),edge_1=require("./edge"),hmr_reload_1=require("./hmr-reload"),service_keys_1=require("./service-keys");exports.LENS_HMR_REFUSAL_REPORT_MS=1e4;function accountUpgrade(a,o){const i=a.svc;if(!i||o.destroyed)return;i.inflight+=1,i.lastUsed=Date.now();let d=!1;o.once("close",()=>{d||(d=!0,i.inflight-=1,i.lastUsed=Date.now())})}v(accountUpgrade,"accountUpgrade"),w(accountUpgrade,"accountUpgrade"),u(accountUpgrade,"accountUpgrade");function createUpgrade(a){const{rt:o,auth:i,proxy:d,hooks:p,obs:S}=a,y=new Set,k=u(e=>{e.destroyed||(y.add(e),e.once("close",()=>y.delete(e)))},"track");d.proxy.on?.("open",k);const _=new WeakMap,m=new Map,R=u((e,r)=>{const s=Date.now();s-(m.get(e.frontendKey)??0)<exports.LENS_HMR_REFUSAL_REPORT_MS||(m.set(e.frontendKey,s),console.warn(`[gateway] lens HMR socket refused: ${e.frontendKey} at ${e.target} answered ${r} for a tab on ${e.host} \u2014 that tab loads but gets no hot updates; the lens runtime reloads it once if it had a socket before.`),S?.emit("warning",`lens HMR socket refused: ${e.frontendKey} (${r})`,`cluster-lens-hmr-refused:${e.frontendKey}`,{kind:"lens-hmr-refused",frontendKey:e.frontendKey,host:e.host,target:e.target,answer:r},void 0,e.busFile))},"reportRefusal");d.proxy.on?.("proxyReqWs",(e,r)=>{const s=_.get(r);if(!s)return;const c=e;c.once("upgrade",()=>{s.answered=!0}),c.once("response",g=>{s.answered=!0,R(s,`HTTP ${g.statusCode??"?"}`)})});const U=u(async(e,r,s)=>{(0,edge_1.stripOwnedHeaders)(e);const c=(0,edge_1.canonicalize)(e.url??"/");if(c===void 0){r.destroy();return}e.url=c.path+c.query;const g=(e.headers.host||"").split(":")[0],t=(0,manifest_1.matchRoute)(o.routes,g,c.policy+c.query);if(!t){r.destroy();return}(0,edge_1.resolveClientIp)(o,e);const l=p.upgradeContext(e,r,void 0);if(l.route=t,t.internal){const n=i.internal(e,t,void 0);if(!n.ok){r.destroy();return}l.caller=n.caller}else{const n=i.public(e,t,void 0,c.policy);if(!n.ok){r.destroy();return}if(l.claims=n.claims,p.has("afterAuth")&&(await p.run("afterAuth",l),l.responded()))return}const x=t.pool?o.serviceKeys[(0,service_keys_1.serviceKeyId)(t.svc?.wsKey,t.project)]:void 0;if(x&&(e.headers["x-internal-token"]=x),t.prependPrefix&&!e.url?.startsWith(t.prependPrefix)&&(e.url=t.prependPrefix+(e.url??"/")),(0,edge_1.stampForwardingHeaders)(o,e),p.has("onUpgrade")&&(await p.run("onUpgrade",l),l.responded()))return;const h=t.pool?(()=>{const n=(0,discovery_1.pickSock)(t.pool,o.scanTtlMs);return n?{socketPath:n}:void 0})():t.target;if(!h){r.destroy();return}if(t.lens&&String(e.headers["sec-websocket-protocol"]??"").split(",").map(n=>n.trim()).includes("vite-hmr")){const n=t.lens.workspaceKey?`${t.lens.workspaceKey}:${t.lens.project}`:t.lens.project;(0,hmr_reload_1.registerHmrClient)(o,n,r);const f=!t.lens.workspaceRoot||path.resolve(t.lens.workspaceRoot)===path.resolve(o.root??"");_.set(e,{frontendKey:n,host:g,target:String(h),answered:!1,...f?{}:{busFile:path.join(t.lens.workspaceRoot,".lensmcp","events.jsonl")}})}accountUpgrade(t,r),d.proxy.ws(e,r,s,{target:h,changeOrigin:!t.pool,agent:d.agentForTarget(h)},n=>{const f=_.get(e);f&&!f.answered&&R(f,n?.code??n?.message??"an error"),r.destroy()})},"run"),b=u(((e,r,s)=>{r.on("error",()=>r.destroy()),k(r),U(e,r,s).catch(()=>r.destroy())}),"listener");return b.closeTunnels=()=>{const e=[...y];for(const r of e)r.destroy();return y.clear(),e.length},b}v(createUpgrade,"createUpgrade"),w(createUpgrade,"createUpgrade"),u(createUpgrade,"createUpgrade");
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var r=(e,t)=>a(e,"name",{value:t,configurable:!0});var s=Object.defineProperty,n=r((e,t)=>s(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.workspaceLogWriter=workspaceLogWriter,exports.closeWorkspaceLogs=closeWorkspaceLogs;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),inspector_secret_1=require("../../../inspector-secret"),fds=new Map,written=new Map,MAX_BYTES=50*1024*1024,CHECK_EVERY=1024*1024;function ensurePrivateDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});try{const t=fs.statSync(e);(t.mode&63)!==0&&(typeof process.getuid!="function"||t.uid===process.getuid())&&fs.chmodSync(e,448)}catch{}}r(ensurePrivateDir,"ensurePrivateDir"),n(ensurePrivateDir,"ensurePrivateDir");function ownerOnly(e){try{fs.chmodSync(e,384)}catch{}}r(ownerOnly,"ownerOnly"),n(ownerOnly,"ownerOnly");function ensureFd(e){const t=fds.get(e);if(t!==void 0)return t;try{ensurePrivateDir(path.dirname(e));const o=fs.openSync(e,"a",384);return ownerOnly(e),fds.set(e,o),written.set(e,0),o}catch{return}}r(ensureFd,"ensureFd"),n(ensureFd,"ensureFd");function closeFd(e){const t=fds.get(e);if(fds.delete(e),written.delete(e),t!==void 0)try{fs.closeSync(t)}catch{}}r(closeFd,"closeFd"),n(closeFd,"closeFd");function rotateIfHuge(e){try{if(fs.statSync(e).size<=MAX_BYTES)return}catch{return}closeFd(e);try{fs.renameSync(e,`${e}.1`)}catch{}ownerOnly(`${e}.1`)}r(rotateIfHuge,"rotateIfHuge"),n(rotateIfHuge,"rotateIfHuge");function workspaceLogWriter(e){const t=path.join(e,".lensmcp","gateway.log");if(ensureFd(t)!==void 0)return o=>{const c=ensureFd(t);if(c===void 0)return;try{fs.writeSync(c,(0,inspector_secret_1.redactInspectorUrls)(o))}catch{closeFd(t);return}const i=(written.get(t)??0)+o.length;i>=CHECK_EVERY?(written.set(t,0),rotateIfHuge(t)):written.set(t,i)}}r(workspaceLogWriter,"workspaceLogWriter"),n(workspaceLogWriter,"workspaceLogWriter");function closeWorkspaceLogs(){for(const e of[...fds.keys()])closeFd(e)}r(closeWorkspaceLogs,"closeWorkspaceLogs"),n(closeWorkspaceLogs,"closeWorkspaceLogs");
1
+ "use strict";var d=Object.defineProperty;var o=(e,t)=>d(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,r=o((e,t)=>a(e,"name",{value:t,configurable:!0}),"r"),s=Object.defineProperty,n=r((e,t)=>s(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.workspaceLogWriter=workspaceLogWriter,exports.closeWorkspaceLogs=closeWorkspaceLogs;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),inspector_secret_1=require("../../../inspector-secret"),fds=new Map,written=new Map,MAX_BYTES=50*1024*1024,CHECK_EVERY=1024*1024;function ensurePrivateDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});try{const t=fs.statSync(e);(t.mode&63)!==0&&(typeof process.getuid!="function"||t.uid===process.getuid())&&fs.chmodSync(e,448)}catch{}}o(ensurePrivateDir,"ensurePrivateDir"),r(ensurePrivateDir,"ensurePrivateDir"),n(ensurePrivateDir,"ensurePrivateDir");function ownerOnly(e){try{fs.chmodSync(e,384)}catch{}}o(ownerOnly,"ownerOnly"),r(ownerOnly,"ownerOnly"),n(ownerOnly,"ownerOnly");function ensureFd(e){const t=fds.get(e);if(t!==void 0)return t;try{ensurePrivateDir(path.dirname(e));const c=fs.openSync(e,"a",384);return ownerOnly(e),fds.set(e,c),written.set(e,0),c}catch{return}}o(ensureFd,"ensureFd"),r(ensureFd,"ensureFd"),n(ensureFd,"ensureFd");function closeFd(e){const t=fds.get(e);if(fds.delete(e),written.delete(e),t!==void 0)try{fs.closeSync(t)}catch{}}o(closeFd,"closeFd"),r(closeFd,"closeFd"),n(closeFd,"closeFd");function rotateIfHuge(e){try{if(fs.statSync(e).size<=MAX_BYTES)return}catch{return}closeFd(e);try{fs.renameSync(e,`${e}.1`)}catch{}ownerOnly(`${e}.1`)}o(rotateIfHuge,"rotateIfHuge"),r(rotateIfHuge,"rotateIfHuge"),n(rotateIfHuge,"rotateIfHuge");function workspaceLogWriter(e){const t=path.join(e,".lensmcp","gateway.log");if(ensureFd(t)!==void 0)return c=>{const i=ensureFd(t);if(i===void 0)return;try{fs.writeSync(i,(0,inspector_secret_1.redactInspectorUrls)(c))}catch{closeFd(t);return}const u=(written.get(t)??0)+c.length;u>=CHECK_EVERY?(written.set(t,0),rotateIfHuge(t)):written.set(t,u)}}o(workspaceLogWriter,"workspaceLogWriter"),r(workspaceLogWriter,"workspaceLogWriter"),n(workspaceLogWriter,"workspaceLogWriter");function closeWorkspaceLogs(){for(const e of[...fds.keys()])closeFd(e)}o(closeWorkspaceLogs,"closeWorkspaceLogs"),r(closeWorkspaceLogs,"closeWorkspaceLogs"),n(closeWorkspaceLogs,"closeWorkspaceLogs");
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var a=(r,t)=>w(r,"name",{value:t,configurable:!0});var c=Object.defineProperty,i=a((r,t)=>c(r,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!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"));function guestMiddlewarePolicy(r=process.env){const t=r.LENSMCP_GUEST_MIDDLEWARE;return t==="owner"||t==="none"?t:"own"}a(guestMiddlewarePolicy,"guestMiddlewarePolicy"),i(guestMiddlewarePolicy,"guestMiddlewarePolicy");function findGatewayMiddleware(r,t){for(const n of Object.values(t)){let o;try{o=JSON.parse(fs.readFileSync(path.join(r,n.root,"project.json"),"utf8"))}catch{continue}for(const e of Object.values(o.targets??{}))if(e?.executor==="@lensmcp/cluster:gateway"&&typeof e.options?.middleware=="string"&&e.options.middleware)return e.options.middleware}}a(findGatewayMiddleware,"findGatewayMiddleware"),i(findGatewayMiddleware,"findGatewayMiddleware");function loadMiddleware(r){const t=require.resolve(r);delete require.cache[t];const n=require(t),o=n.default??n;if(typeof o!="function")throw new Error(`${r} exports no function`);return o}a(loadMiddleware,"loadMiddleware"),i(loadMiddleware,"loadMiddleware");function createWorkspaceMiddleware(r){const t=r.policy??"own",n=r.load??loadMiddleware,o=new Map;return{set(e,l,s){if(e===r.ownerKey)return;if(!s){o.set(e,void 0);return}const d=path.resolve(l,s);try{o.set(e,n(d)),t==="own"&&console.log(`[gateway] '${e}' routes run its own middleware: ${d}`)}catch(u){o.set(e,void 0),console.warn(`[gateway] could not load '${e}''s middleware ${d} (${u.message}) \u2014 its routes run with NO middleware until it registers again`)}},drop(e){o.delete(e)},for(e){if(e===void 0||e===r.ownerKey||t==="owner")return r.owner;if(t!=="none")return o.get(e)}}}a(createWorkspaceMiddleware,"createWorkspaceMiddleware"),i(createWorkspaceMiddleware,"createWorkspaceMiddleware");
1
+ "use strict";var p=Object.defineProperty;var d=(e,r)=>p(e,"name",{value:r,configurable:!0});var w=Object.defineProperty,a=d((e,r)=>w(e,"name",{value:r,configurable:!0}),"a"),c=Object.defineProperty,i=a((e,r)=>c(e,"name",{value:r,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!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"));function guestMiddlewarePolicy(e=process.env){const r=e.LENSMCP_GUEST_MIDDLEWARE;return r==="owner"||r==="none"?r:"own"}d(guestMiddlewarePolicy,"guestMiddlewarePolicy"),a(guestMiddlewarePolicy,"guestMiddlewarePolicy"),i(guestMiddlewarePolicy,"guestMiddlewarePolicy");function findGatewayMiddleware(e,r){for(const n of Object.values(r)){let o;try{o=JSON.parse(fs.readFileSync(path.join(e,n.root,"project.json"),"utf8"))}catch{continue}for(const t of Object.values(o.targets??{}))if(t?.executor==="@lensmcp/cluster:gateway"&&typeof t.options?.middleware=="string"&&t.options.middleware)return t.options.middleware}}d(findGatewayMiddleware,"findGatewayMiddleware"),a(findGatewayMiddleware,"findGatewayMiddleware"),i(findGatewayMiddleware,"findGatewayMiddleware");function loadMiddleware(e){const r=require.resolve(e);delete require.cache[r];const n=require(r),o=n.default??n;if(typeof o!="function")throw new Error(`${e} exports no function`);return o}d(loadMiddleware,"loadMiddleware"),a(loadMiddleware,"loadMiddleware"),i(loadMiddleware,"loadMiddleware");function createWorkspaceMiddleware(e){const r=e.policy??"own",n=e.load??loadMiddleware,o=new Map;return{set(t,u,l){if(t===e.ownerKey)return;if(!l){o.set(t,void 0);return}const s=path.resolve(u,l);try{o.set(t,n(s)),r==="own"&&console.log(`[gateway] '${t}' routes run its own middleware: ${s}`)}catch(f){o.set(t,void 0),console.warn(`[gateway] could not load '${t}''s middleware ${s} (${f.message}) \u2014 its routes run with NO middleware until it registers again`)}},drop(t){o.delete(t)},for(t){if(t===void 0||t===e.ownerKey||r==="owner")return e.owner;if(r!=="none")return o.get(t)}}}d(createWorkspaceMiddleware,"createWorkspaceMiddleware"),a(createWorkspaceMiddleware,"createWorkspaceMiddleware"),i(createWorkspaceMiddleware,"createWorkspaceMiddleware");
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var i=(e,r)=>p(e,"name",{value:r,configurable:!0});var c=Object.defineProperty,s=i((e,r)=>c(e,"name",{value:r,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.processStamp=processStamp,exports.registryPath=registryPath,exports.readWorkspaces=readWorkspaces,exports.registerWorkspace=registerWorkspace,exports.unregisterWorkspace=unregisterWorkspace,exports.isWorkspaceLive=isWorkspaceLive;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path"));function processStamp(e){if(!e||e<=0||process.platform==="win32")return"";try{return(0,node_child_process_1.execFileSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}i(processStamp,"processStamp"),s(processStamp,"processStamp");function registryPath(){const e=process.env.LENSMCP_HOME||os.homedir();return path.join(e,".lensmcp","workspaces.json")}i(registryPath,"registryPath"),s(registryPath,"registryPath");function readWorkspaces(e=registryPath()){try{const r=JSON.parse(fs.readFileSync(e,"utf8"));return Array.isArray(r)?r.filter(t=>!!t&&typeof t.key=="string"&&typeof t.base=="string"):[]}catch{return[]}}i(readWorkspaces,"readWorkspaces"),s(readWorkspaces,"readWorkspaces");function writeWorkspaces(e,r=registryPath()){try{fs.mkdirSync(path.dirname(r),{recursive:!0}),fs.writeFileSync(r,JSON.stringify(e,null,2))}catch{}}i(writeWorkspaces,"writeWorkspaces"),s(writeWorkspaces,"writeWorkspaces");function registerWorkspace(e,r=registryPath()){const t=readWorkspaces(r).filter(o=>o.key!==e.key);t.push(e),t.sort((o,n)=>o.key.localeCompare(n.key)),writeWorkspaces(t,r)}i(registerWorkspace,"registerWorkspace"),s(registerWorkspace,"registerWorkspace");function unregisterWorkspace(e,r=registryPath()){writeWorkspaces(readWorkspaces(r).filter(t=>t.key!==e),r)}i(unregisterWorkspace,"unregisterWorkspace"),s(unregisterWorkspace,"unregisterWorkspace");function isWorkspaceLive(e){if(!e.pid||e.pid<=0)return!1;try{process.kill(e.pid,0)}catch(t){if(t.code!=="EPERM")return!1}if(!e.procStamp)return!0;const r=processStamp(e.pid);return r===""?!0:r===e.procStamp}i(isWorkspaceLive,"isWorkspaceLive"),s(isWorkspaceLive,"isWorkspaceLive");
1
+ "use strict";var u=Object.defineProperty;var o=(r,e)=>u(r,"name",{value:e,configurable:!0});var p=Object.defineProperty,i=o((r,e)=>p(r,"name",{value:e,configurable:!0}),"i"),c=Object.defineProperty,s=i((r,e)=>c(r,"name",{value:e,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.processStamp=processStamp,exports.registryPath=registryPath,exports.readWorkspaces=readWorkspaces,exports.registerWorkspace=registerWorkspace,exports.unregisterWorkspace=unregisterWorkspace,exports.isWorkspaceLive=isWorkspaceLive;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path"));function processStamp(r){if(!r||r<=0||process.platform==="win32")return"";try{return(0,node_child_process_1.execFileSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}o(processStamp,"processStamp"),i(processStamp,"processStamp"),s(processStamp,"processStamp");function registryPath(){const r=process.env.LENSMCP_HOME||os.homedir();return path.join(r,".lensmcp","workspaces.json")}o(registryPath,"registryPath"),i(registryPath,"registryPath"),s(registryPath,"registryPath");function readWorkspaces(r=registryPath()){try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return Array.isArray(e)?e.filter(t=>!!t&&typeof t.key=="string"&&typeof t.base=="string"):[]}catch{return[]}}o(readWorkspaces,"readWorkspaces"),i(readWorkspaces,"readWorkspaces"),s(readWorkspaces,"readWorkspaces");function writeWorkspaces(r,e=registryPath()){try{fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,JSON.stringify(r,null,2))}catch{}}o(writeWorkspaces,"writeWorkspaces"),i(writeWorkspaces,"writeWorkspaces"),s(writeWorkspaces,"writeWorkspaces");function registerWorkspace(r,e=registryPath()){const t=readWorkspaces(e).filter(n=>n.key!==r.key);t.push(r),t.sort((n,a)=>n.key.localeCompare(a.key)),writeWorkspaces(t,e)}o(registerWorkspace,"registerWorkspace"),i(registerWorkspace,"registerWorkspace"),s(registerWorkspace,"registerWorkspace");function unregisterWorkspace(r,e=registryPath()){writeWorkspaces(readWorkspaces(e).filter(t=>t.key!==r),e)}o(unregisterWorkspace,"unregisterWorkspace"),i(unregisterWorkspace,"unregisterWorkspace"),s(unregisterWorkspace,"unregisterWorkspace");function isWorkspaceLive(r){if(!r.pid||r.pid<=0)return!1;try{process.kill(r.pid,0)}catch(t){if(t.code!=="EPERM")return!1}if(!r.procStamp)return!0;const e=processStamp(r.pid);return e===""?!0:e===r.procStamp}o(isWorkspaceLive,"isWorkspaceLive"),i(isWorkspaceLive,"isWorkspaceLive"),s(isWorkspaceLive,"isWorkspaceLive");
@@ -1 +1 @@
1
- "use strict";var h=Object.defineProperty;var l=(e,t)=>h(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,i=l((e,t)=>u(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SsrfBlockedError=void 0,exports.isBlockedAddress=isBlockedAddress,exports.assertFetchableUrl=assertFetchableUrl,exports.safeFetch=safeFetch,exports.pinnedLookup=pinnedLookup;const node_net_1=require("node:net"),promises_1=require("node:dns/promises");class SsrfBlockedError extends Error{static{l(this,"SsrfBlockedError")}static{i(this,"SsrfBlockedError")}constructor(t,o,s,r){super(`SSRF guard blocked ${o??"request"}: ${t}${s?` (${s})`:""}`,r!==void 0?{cause:r}:void 0),this.name="SsrfBlockedError",this.reason=t,this.url=o,this.address=s}}exports.SsrfBlockedError=SsrfBlockedError;function buildDefaultBlockList(){const e=new node_net_1.BlockList;return e.addSubnet("0.0.0.0",8,"ipv4"),e.addSubnet("10.0.0.0",8,"ipv4"),e.addSubnet("100.64.0.0",10,"ipv4"),e.addSubnet("127.0.0.0",8,"ipv4"),e.addSubnet("169.254.0.0",16,"ipv4"),e.addSubnet("172.16.0.0",12,"ipv4"),e.addSubnet("192.0.0.0",24,"ipv4"),e.addSubnet("192.168.0.0",16,"ipv4"),e.addSubnet("198.18.0.0",15,"ipv4"),e.addSubnet("240.0.0.0",4,"ipv4"),e.addAddress("::","ipv6"),e.addAddress("::1","ipv6"),e.addSubnet("fc00::",7,"ipv6"),e.addSubnet("fe80::",10,"ipv6"),e}l(buildDefaultBlockList,"buildDefaultBlockList"),i(buildDefaultBlockList,"buildDefaultBlockList");const DEFAULT_BLOCK_LIST=buildDefaultBlockList();function isBlockedAddress(e,t=DEFAULT_BLOCK_LIST){const o=(0,node_net_1.isIP)(e);return o===0?!0:t.check(e,o===6?"ipv6":"ipv4")}l(isBlockedAddress,"isBlockedAddress"),i(isBlockedAddress,"isBlockedAddress");const stripBrackets=i(e=>e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,"stripBrackets"),defaultResolve=i(async e=>(await(0,promises_1.lookup)(e,{all:!0,verbatim:!0})).map(t=>t.address),"defaultResolve");async function assertFetchableUrl(e,t={}){const o=t.allowedProtocols??["http:","https:"];let s;try{s=new URL(e)}catch{throw new SsrfBlockedError("malformed-url",String(e))}if(!o.includes(s.protocol))throw new SsrfBlockedError(`scheme-not-allowed:${s.protocol}`,s.href);if(s.username!==""||s.password!=="")throw new SsrfBlockedError("embedded-credentials",s.href);const r=stripBrackets(s.hostname);if(r==="")throw new SsrfBlockedError("missing-host",s.href);if(t.allowPrivate)return{url:s,hostname:r,addresses:(0,node_net_1.isIP)(r)?[r]:[]};const d=t.blockList??DEFAULT_BLOCK_LIST;if((0,node_net_1.isIP)(r)!==0){if(isBlockedAddress(r,d))throw new SsrfBlockedError("blocked-address",s.href,r);return{url:s,hostname:r,addresses:[r]}}const c=t.resolve??defaultResolve;let a;try{a=await c(r)}catch(n){throw new SsrfBlockedError("dns-resolution-failed",s.href,void 0,n)}if(a.length===0)throw new SsrfBlockedError("dns-no-records",s.href);for(const n of a)if(isBlockedAddress(n,d))throw new SsrfBlockedError("blocked-resolved-address",s.href,n);return{url:s,hostname:r,addresses:a}}l(assertFetchableUrl,"assertFetchableUrl"),i(assertFetchableUrl,"assertFetchableUrl");async function safeFetch(e,t={},o={}){const s=o.fetchImpl??globalThis.fetch,r=o.maxRedirects??5;let d=e;for(let c=0;;c++){const{url:a}=await assertFetchableUrl(d,o),n=await s(a,{...t,redirect:"manual"}),f=n.headers.get("location");if(n.status>=300&&n.status<400&&f){if(c>=r)throw new SsrfBlockedError("too-many-redirects",a.href);d=new URL(f,a).href;continue}return n}}l(safeFetch,"safeFetch"),i(safeFetch,"safeFetch");function pinnedLookup(e){const t=e.map(o=>({address:o,family:(0,node_net_1.isIP)(o)===6?6:4}));return(o,s,r)=>{const d=typeof s=="function"?s:r,c=typeof s=="object"&&s!==null&&s.all===!0;if(t.length===0){d(new Error(`SSRF guard: no pinned address for ${o}`));return}c?d(null,t):d(null,t[0].address,t[0].family)}}l(pinnedLookup,"pinnedLookup"),i(pinnedLookup,"pinnedLookup");
1
+ "use strict";var b=Object.defineProperty;var c=(e,t)=>b(e,"name",{value:t,configurable:!0});var h=Object.defineProperty,l=c((e,t)=>h(e,"name",{value:t,configurable:!0}),"l"),u=Object.defineProperty,i=l((e,t)=>u(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SsrfBlockedError=void 0,exports.isBlockedAddress=isBlockedAddress,exports.assertFetchableUrl=assertFetchableUrl,exports.safeFetch=safeFetch,exports.pinnedLookup=pinnedLookup;const node_net_1=require("node:net"),promises_1=require("node:dns/promises");class SsrfBlockedError extends Error{static{c(this,"SsrfBlockedError")}static{l(this,"SsrfBlockedError")}static{i(this,"SsrfBlockedError")}constructor(t,o,r,s){super(`SSRF guard blocked ${o??"request"}: ${t}${r?` (${r})`:""}`,s!==void 0?{cause:s}:void 0),this.name="SsrfBlockedError",this.reason=t,this.url=o,this.address=r}}exports.SsrfBlockedError=SsrfBlockedError;function buildDefaultBlockList(){const e=new node_net_1.BlockList;return e.addSubnet("0.0.0.0",8,"ipv4"),e.addSubnet("10.0.0.0",8,"ipv4"),e.addSubnet("100.64.0.0",10,"ipv4"),e.addSubnet("127.0.0.0",8,"ipv4"),e.addSubnet("169.254.0.0",16,"ipv4"),e.addSubnet("172.16.0.0",12,"ipv4"),e.addSubnet("192.0.0.0",24,"ipv4"),e.addSubnet("192.168.0.0",16,"ipv4"),e.addSubnet("198.18.0.0",15,"ipv4"),e.addSubnet("240.0.0.0",4,"ipv4"),e.addAddress("::","ipv6"),e.addAddress("::1","ipv6"),e.addSubnet("fc00::",7,"ipv6"),e.addSubnet("fe80::",10,"ipv6"),e}c(buildDefaultBlockList,"buildDefaultBlockList"),l(buildDefaultBlockList,"buildDefaultBlockList"),i(buildDefaultBlockList,"buildDefaultBlockList");const DEFAULT_BLOCK_LIST=buildDefaultBlockList();function isBlockedAddress(e,t=DEFAULT_BLOCK_LIST){const o=(0,node_net_1.isIP)(e);return o===0?!0:t.check(e,o===6?"ipv6":"ipv4")}c(isBlockedAddress,"isBlockedAddress"),l(isBlockedAddress,"isBlockedAddress"),i(isBlockedAddress,"isBlockedAddress");const stripBrackets=i(e=>e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,"stripBrackets"),defaultResolve=i(async e=>(await(0,promises_1.lookup)(e,{all:!0,verbatim:!0})).map(t=>t.address),"defaultResolve");async function assertFetchableUrl(e,t={}){const o=t.allowedProtocols??["http:","https:"];let r;try{r=new URL(e)}catch{throw new SsrfBlockedError("malformed-url",String(e))}if(!o.includes(r.protocol))throw new SsrfBlockedError(`scheme-not-allowed:${r.protocol}`,r.href);if(r.username!==""||r.password!=="")throw new SsrfBlockedError("embedded-credentials",r.href);const s=stripBrackets(r.hostname);if(s==="")throw new SsrfBlockedError("missing-host",r.href);if(t.allowPrivate)return{url:r,hostname:s,addresses:(0,node_net_1.isIP)(s)?[s]:[]};const d=t.blockList??DEFAULT_BLOCK_LIST;if((0,node_net_1.isIP)(s)!==0){if(isBlockedAddress(s,d))throw new SsrfBlockedError("blocked-address",r.href,s);return{url:r,hostname:s,addresses:[s]}}const f=t.resolve??defaultResolve;let a;try{a=await f(s)}catch(n){throw new SsrfBlockedError("dns-resolution-failed",r.href,void 0,n)}if(a.length===0)throw new SsrfBlockedError("dns-no-records",r.href);for(const n of a)if(isBlockedAddress(n,d))throw new SsrfBlockedError("blocked-resolved-address",r.href,n);return{url:r,hostname:s,addresses:a}}c(assertFetchableUrl,"assertFetchableUrl"),l(assertFetchableUrl,"assertFetchableUrl"),i(assertFetchableUrl,"assertFetchableUrl");async function safeFetch(e,t={},o={}){const r=o.fetchImpl??globalThis.fetch,s=o.maxRedirects??5;let d=e;for(let f=0;;f++){const{url:a}=await assertFetchableUrl(d,o),n=await r(a,{...t,redirect:"manual"}),p=n.headers.get("location");if(n.status>=300&&n.status<400&&p){if(f>=s)throw new SsrfBlockedError("too-many-redirects",a.href);d=new URL(p,a).href;continue}return n}}c(safeFetch,"safeFetch"),l(safeFetch,"safeFetch"),i(safeFetch,"safeFetch");function pinnedLookup(e){const t=e.map(o=>({address:o,family:(0,node_net_1.isIP)(o)===6?6:4}));return(o,r,s)=>{const d=typeof r=="function"?r:s,f=typeof r=="object"&&r!==null&&r.all===!0;if(t.length===0){d(new Error(`SSRF guard: no pinned address for ${o}`));return}f?d(null,t):d(null,t[0].address,t[0].family)}}c(pinnedLookup,"pinnedLookup"),l(pinnedLookup,"pinnedLookup"),i(pinnedLookup,"pinnedLookup");
@@ -1 +1 @@
1
- "use strict";var ie=Object.defineProperty;var c=(e,t)=>ie(e,"name",{value:t,configurable:!0});var se=Object.defineProperty,o=c((e,t)=>se(e,"name",{value:t,configurable:!0}),"o");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")),dev_devtool_1=require("../../dev-devtool"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach");function definedEnv(e){const t={};for(const[_,i]of Object.entries(e))typeof i=="string"&&(t[_]=i);return t}c(definedEnv,"definedEnv"),o(definedEnv,"definedEnv");const frozen=o(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,t){process.env.NODE_ENV="development";const _=t.projectsConfigurations.projects[t.projectName],i=t.root,g=path.join(i,_.root),U=e.outputPath?path.join(i,e.outputPath):path.join(i,"dist",_.root),B=e.configEnv||"development",R=path.join(i,"config",`config.${B}.yaml`),$=3050;let d=$,a=t.projectName,S={};fs.existsSync(R)?(S=yaml.load(fs.readFileSync(R,"utf8")),d=Number(S.port)||d,a=S.serviceName||a):console.warn(`[serve] ${t.projectName}: no config file at ${R} \u2014 public devserver port defaults to ${$}. If another service also lacks its config, both bind ${$} \u2192 EADDRINUSE. Add config/config.${B}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(a=e.serviceName);const T=e.servePrefix??"",h=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),z=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),p=e.logFile?path.resolve(i,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(p){fs.mkdirSync(path.dirname(p),{recursive:!0}),fs.writeFileSync(p,"",{mode:384});try{fs.chmodSync(p,384)}catch{}}let k,D;e.gateway?.middleware&&(k=path.resolve(g,e.gateway.middleware),D=JSON.stringify(S));const K=e.entryFile||"./src/deployments/service/main.ts",Q=e.tsConfigFile||"./tsconfig.app.json",Z=path.resolve(g,K),q=path.resolve(g,Q),ee=(e.workers||[]).map(r=>({entryName:r.name,entryPath:path.resolve(g,r.entryPath)})),W={appName:t.projectName,appRoot:g,outputDir:U,main:Z,tsConfig:q,assets:e.assets||[],additionalEntryPoints:ee,port:d,serviceName:a,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:i,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,O=!1,I=!1,m=!1;const V=path.join(__dirname,"../../main.devserver.js"),H=path.join(__dirname,"../../main.devserver.ts"),Y=!fs.existsSync(V)&&fs.existsSync(H),x=Y?H:V,oe=path.join(U,"main.js");function A(){l&&!l.killed&&(l.kill("SIGTERM"),l=null)}c(A,"H"),o(A,"cleanup");function N(){m=!0,A()}c(N,"O"),o(N,"stop");const re=["SIGINT","SIGTERM","SIGHUP","SIGQUIT"].map(r=>{const n=o(()=>N(),"handler");return process.on(r,n),{sig:r,handler:n}});process.on("exit",N);function E(){if(m)return;if(!fs.existsSync(x)){console.error(`[serve] devserver script not found at ${x}`);return}const r=["--enable-source-maps"];Y&&r.unshift("--require","@swc-node/register");const n=(0,node_child_process_1.fork)(x,{cwd:i,env:{...process.env,PORT:String(d),SERVICE_NAME:a,SERVE_PREFIX:T,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||t.projectName||a,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(i,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:oe,...k&&{GATEWAY_MIDDLEWARE:k},...D&&{GATEWAY_CONFIG:D},...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)},...h&&{LENSMCP_DEBUG_PORT:String(h)},...p&&{LENSMCP_LOG_FILE:p},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:I?"1":"0"},stdio:["inherit","inherit","inherit","ipc"],execArgv:r,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(i),a,"dev"))});l=n,n.on("exit",(u,f)=>{l===n&&(l=null),!(f||u===0||m)&&(console.error(`[serve] devserver exited unexpectedly (code=${u}, signal=${f}) \u2014 respawning in 1.5s`),setTimeout(()=>{!m&&!l&&O&&E()},1500).unref?.())}),console.log(`[serve] Devserver started on port ${d} (service: ${a}${T?`, prefix: /${T}`:""})`),h?(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.`),z?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${h}+slot (workers ${h}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${h}. 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`),p&&console.log(`[serve] Logs teed to ${p} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}c(E,"_"),o(E,"startDevServer");function te(){if(!l||l.killed){console.log("[serve] Devserver not running, restarting..."),E();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),A(),E()})}c(te,"ne"),o(te,"_notifyDevServerReload");let w=null;const M=[];function v(r){if(w){const n=w;w=null,n(r)}else M.push(r)}c(v,"h"),o(v,"pushResult");function J(){return M.length>0?Promise.resolve(M.shift()):new Promise(r=>{w=r})}c(J,"ee"),o(J,"waitForNext");let y=o(()=>{},"closeBuild");function F(){return!O||!l?(O=!0,E(),!0):!1}c(F,"J"),o(F,"builtOk");function b(){if(m)return;const{createDevWebpackConfig:r}=require("../../create-webpack-dev"),n=require("webpack"),u=r(W),{watch:f,...P}=u,s=n(P);I=(0,dev_devtool_1.bundleCarriesSourceMaps)(s.options.devtool);const j=o((L,C)=>{if(L){console.error("[serve] Webpack error:",L),v({success:!1});return}const ne=C.hasErrors();if(console.info(C.toString({colors:!0,chunks:!1,assets:!0})),ne){v({success:!1});return}F(),v({success:!0,baseUrl:`http://localhost:${d}`})},"onBuild");if(frozen()){console.log(`[serve] ${t.projectName}: frozen \u2014 compiling once, no file watcher`),s.run((L,C)=>{j(L,C),s.close(()=>{})});return}const G=s.watch(u.watchOptions||{},j);y=o(()=>G.close(()=>{}),"closeBuild")}c(b,"A"),o(b,"compileOnItsOwn");function X(r){const n=r.accepted.projects.filter(s=>s!==t.projectName);console.log(`[serve] ${t.projectName}: compiled by the workspace's shared compilation ${r.accepted.group.slice(0,8)}${n.length?` with ${n.join(", ")}`:""} \u2014 no webpack in this process`);const u=new devserver_notifier_1.DevserverNotifier(d,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(a)),f=(0,attach_1.createAttachedTypecheck)({appName:t.projectName,tsConfig:q,workspaceRoot:i,memoryLimit:e.memoryLimit||8192});let P;y=o(()=>{r.close(),f.dispose()},"closeBuild"),r.listen(s=>{if(!m)switch(s.type){case"watch-run":u.watchRun(s.paths);return;case"watch-closed":u.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${s.message}`),u.degrade(`compiler failed: ${s.message}`),v({success:!1});return;case"refused":console.log(`[serve] ${t.projectName}: compiling on its own from now on \u2014 ${s.reason}`),y(),b();return;case"built":{if(console.info(s.text),I=s.sourceMaps,f.built(s),!s.ok){u.failed(),v({success:!1});return}const j=s.hash!==P;P=s.hash;const G=F();u.built(j&&!G),v({success:!0,baseUrl:`http://localhost:${d}`});return}default:return}})}if(c(X,"re"),o(X,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const r=await(0,attach_1.joinSharedBuild)({project:t.projectName,target:t.targetName??"serve-hmr",...t.configurationName?{configuration:t.configurationName}:{},options:W,targetOptions:{...e},env:definedEnv(process.env)});r.kind==="attached"?X(r.session):(console.log(`[serve] ${t.projectName}: compiling on its own \u2014 ${r.reason}`),b())}else b();try{for(;;)yield await J()}finally{N(),y(),re.forEach(({sig:r,handler:n})=>process.removeListener(r,n))}}c(serveExecutor,"serveExecutor"),o(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
1
+ "use strict";var ce=Object.defineProperty;var a=(e,t)=>ce(e,"name",{value:t,configurable:!0});var ie=Object.defineProperty,c=a((e,t)=>ie(e,"name",{value:t,configurable:!0}),"c"),se=Object.defineProperty,o=c((e,t)=>se(e,"name",{value:t,configurable:!0}),"o");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")),dev_devtool_1=require("../../dev-devtool"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach");function definedEnv(e){const t={};for(const[w,i]of Object.entries(e))typeof i=="string"&&(t[w]=i);return t}a(definedEnv,"definedEnv"),c(definedEnv,"definedEnv"),o(definedEnv,"definedEnv");const frozen=o(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,t){process.env.NODE_ENV="development";const w=t.projectsConfigurations.projects[t.projectName],i=t.root,_=path.join(i,w.root),W=e.outputPath?path.join(i,e.outputPath):path.join(i,"dist",w.root),H=e.configEnv||"development",T=path.join(i,"config",`config.${H}.yaml`),k=3050;let p=k,l=t.projectName,y={};fs.existsSync(T)?(y=yaml.load(fs.readFileSync(T,"utf8")),p=Number(y.port)||p,l=y.serviceName||l):console.warn(`[serve] ${t.projectName}: no config file at ${T} \u2014 public devserver port defaults to ${k}. If another service also lacks its config, both bind ${k} \u2192 EADDRINUSE. Add config/config.${H}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(l=e.serviceName);const D=e.servePrefix??"",m=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),Q=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),v=e.logFile?path.resolve(i,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(v){fs.mkdirSync(path.dirname(v),{recursive:!0}),fs.writeFileSync(v,"",{mode:384});try{fs.chmodSync(v,384)}catch{}}let x,I;e.gateway?.middleware&&(x=path.resolve(_,e.gateway.middleware),I=JSON.stringify(y));const Z=e.entryFile||"./src/deployments/service/main.ts",ee=e.tsConfigFile||"./tsconfig.app.json",oe=path.resolve(_,Z),V=path.resolve(_,ee),re=(e.workers||[]).map(r=>({entryName:r.name,entryPath:path.resolve(_,r.entryPath)})),J={appName:t.projectName,appRoot:_,outputDir:W,main:oe,tsConfig:V,assets:e.assets||[],additionalEntryPoints:re,port:p,serviceName:l,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:i,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 u=null,A=!1,G=!1,f=!1;const Y=path.join(__dirname,"../../main.devserver.js"),X=path.join(__dirname,"../../main.devserver.ts"),z=!fs.existsSync(Y)&&fs.existsSync(X),M=z?X:Y,te=path.join(W,"main.js");function b(){u&&!u.killed&&(u.kill("SIGTERM"),u=null)}a(b,"A"),c(b,"H"),o(b,"cleanup");function S(){f=!0,b()}a(S,"N"),c(S,"O"),o(S,"stop");const ne=["SIGINT","SIGTERM","SIGHUP","SIGQUIT"].map(r=>{const n=o(()=>S(),"handler");return process.on(r,n),{sig:r,handler:n}});process.on("exit",S);function g(){if(f)return;if(!fs.existsSync(M)){console.error(`[serve] devserver script not found at ${M}`);return}const r=["--enable-source-maps"];z&&r.unshift("--require","@swc-node/register");const n=(0,node_child_process_1.fork)(M,{cwd:i,env:{...process.env,PORT:String(p),SERVICE_NAME:l,SERVE_PREFIX:D,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||t.projectName||l,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(i,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:te,...x&&{GATEWAY_MIDDLEWARE:x},...I&&{GATEWAY_CONFIG:I},...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)},...m&&{LENSMCP_DEBUG_PORT:String(m)},...v&&{LENSMCP_LOG_FILE:v},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:G?"1":"0"},stdio:["inherit","inherit","inherit","ipc"],execArgv:r,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(i),l,"dev"))});u=n,n.on("exit",(d,E)=>{u===n&&(u=null),!(E||d===0||f)&&(console.error(`[serve] devserver exited unexpectedly (code=${d}, signal=${E}) \u2014 respawning in 1.5s`),setTimeout(()=>{!f&&!u&&A&&g()},1500).unref?.())}),console.log(`[serve] Devserver started on port ${p} (service: ${l}${D?`, prefix: /${D}`:""})`),m?(console.warn(`[serve] DEBUGGER ENABLED for ${l}. 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.`),Q?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${m}+slot (workers ${m}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${m}. 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 ${l}\` (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 ${l}\` opens pod inspectors without a restart`),v&&console.log(`[serve] Logs teed to ${v} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}a(g,"E"),c(g,"_"),o(g,"startDevServer");function K(){if(!u||u.killed){console.log("[serve] Devserver not running, restarting..."),g();return}fetch(`http://localhost:${p}/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),b(),g()})}a(K,"te"),c(K,"ne"),o(K,"_notifyDevServerReload");let P=null;const F=[];function h(r){if(P){const n=P;P=null,n(r)}else F.push(r)}a(h,"v"),c(h,"h"),o(h,"pushResult");function U(){return F.length>0?Promise.resolve(F.shift()):new Promise(r=>{P=r})}a(U,"J"),c(U,"ee"),o(U,"waitForNext");let j=o(()=>{},"closeBuild");function R(){return!A||!u?(A=!0,g(),!0):!1}a(R,"F"),c(R,"J"),o(R,"builtOk");function N(){if(f)return;const{createDevWebpackConfig:r}=require("../../create-webpack-dev"),n=require("webpack"),d=r(J),{watch:E,...L}=d,s=n(L);G=(0,dev_devtool_1.bundleCarriesSourceMaps)(s.options.devtool);const O=o(($,C)=>{if($){console.error("[serve] Webpack error:",$),h({success:!1});return}const ae=C.hasErrors();if(console.info(C.toString({colors:!0,chunks:!1,assets:!0})),ae){h({success:!1});return}R(),h({success:!0,baseUrl:`http://localhost:${p}`})},"onBuild");if(frozen()){console.log(`[serve] ${t.projectName}: frozen \u2014 compiling once, no file watcher`),s.run(($,C)=>{O($,C),s.close(()=>{})});return}const q=s.watch(d.watchOptions||{},O);j=o(()=>q.close(()=>{}),"closeBuild")}a(N,"b"),c(N,"A"),o(N,"compileOnItsOwn");function B(r){const n=r.accepted.projects.filter(s=>s!==t.projectName);console.log(`[serve] ${t.projectName}: compiled by the workspace's shared compilation ${r.accepted.group.slice(0,8)}${n.length?` with ${n.join(", ")}`:""} \u2014 no webpack in this process`);const d=new devserver_notifier_1.DevserverNotifier(p,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(l)),E=(0,attach_1.createAttachedTypecheck)({appName:t.projectName,tsConfig:V,workspaceRoot:i,memoryLimit:e.memoryLimit||8192});let L;j=o(()=>{r.close(),E.dispose()},"closeBuild"),r.listen(s=>{if(!f)switch(s.type){case"watch-run":d.watchRun(s.paths);return;case"watch-closed":d.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${s.message}`),d.degrade(`compiler failed: ${s.message}`),h({success:!1});return;case"refused":console.log(`[serve] ${t.projectName}: compiling on its own from now on \u2014 ${s.reason}`),j(),N();return;case"built":{if(console.info(s.text),G=s.sourceMaps,E.built(s),!s.ok){d.failed(),h({success:!1});return}const O=s.hash!==L;L=s.hash;const q=R();d.built(O&&!q),h({success:!0,baseUrl:`http://localhost:${p}`});return}default:return}})}if(a(B,"X"),c(B,"re"),o(B,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const r=await(0,attach_1.joinSharedBuild)({project:t.projectName,target:t.targetName??"serve-hmr",...t.configurationName?{configuration:t.configurationName}:{},options:J,targetOptions:{...e},env:definedEnv(process.env)});r.kind==="attached"?B(r.session):(console.log(`[serve] ${t.projectName}: compiling on its own \u2014 ${r.reason}`),N())}else N();try{for(;;)yield await U()}finally{S(),j(),ne.forEach(({sig:r,handler:n})=>process.removeListener(r,n))}}a(serveExecutor,"serveExecutor"),c(serveExecutor,"serveExecutor"),o(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var a=(e,t)=>s(e,"name",{value:t,configurable:!0});var n=Object.defineProperty,r=a((e,t)=>n(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isValidHostname=isValidHostname;const LABEL=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/,MAX_HOSTNAME_LENGTH=253;function isValidHostname(e){return typeof e!="string"||e.length===0||e.length>MAX_HOSTNAME_LENGTH?!1:e.split(".").every(t=>LABEL.test(t))}a(isValidHostname,"isValidHostname"),r(isValidHostname,"isValidHostname");
1
+ "use strict";var o=Object.defineProperty;var i=(e,t)=>o(e,"name",{value:t,configurable:!0});var s=Object.defineProperty,a=i((e,t)=>s(e,"name",{value:t,configurable:!0}),"a"),n=Object.defineProperty,r=a((e,t)=>n(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isValidHostname=isValidHostname;const LABEL=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/,MAX_HOSTNAME_LENGTH=253;function isValidHostname(e){return typeof e!="string"||e.length===0||e.length>MAX_HOSTNAME_LENGTH?!1:e.split(".").every(t=>LABEL.test(t))}i(isValidHostname,"isValidHostname"),a(isValidHostname,"isValidHostname"),r(isValidHostname,"isValidHostname");
@@ -1,6 +1,6 @@
1
- "use strict";var v=Object.defineProperty;var h=(o,t)=>v(o,"name",{value:t,configurable:!0});var m=Object.defineProperty,d=h((o,t)=>m(o,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=trustExecutor,exports.collectHosts=collectHosts;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),basic_ssl_1=require("../../basic-ssl"),checkout_cache_1=require("../../checkout-cache"),hostname_1=require("./hostname");async function trustExecutor(o,t){const r=(0,checkout_cache_1.checkoutCacheDir)(t.root,"davnx-webpack"),c=(0,basic_ssl_1.ensureCaSync)(r),a=process.env.LENSMCP_TRUST_HOSTS_ONLY==="1",u=collectHosts(o,t);if(u.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 ${c} in your OS/browser store (Linux: update-ca-certificates / certutil)`);for(const e of u)console.log(` \u2022 /etc/hosts: "127.0.0.1 ${e}" and "::1 ${e}"`);return{success:!0}}const s=caSha256Fingerprint(c),p=a||s!==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(s)===!0;if(a)console.log("[trust] hosts-only: a shared daemon serves TLS with its own CA \u2014 skipping the keychain step.");else if(p)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): ${c}`),(0,node_child_process_1.spawnSync)("sudo",["security","add-trusted-cert","-d","-r","trustRoot","-k","/Library/Keychains/System.keychain",c],{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 i=fs.readFileSync("/etc/hosts","utf8"),n=d((e,g)=>i.split(`
2
- `).some(S=>{const f=S.trim();if(f.startsWith("#"))return!1;const y=f.split(/\s+/);return y[0]===e&&y.slice(1).includes(g)}),"hasEntry"),l=[];for(const e of u)n("127.0.0.1",e)||l.push(`127.0.0.1 ${e}`),n("::1",e)||l.push(`::1 ${e}`);if(l.length===0)console.log("[trust] /etc/hosts already complete (both families for every hostname).");else{if(console.log(`[trust] appending to /etc/hosts (sudo):
1
+ "use strict";var b=Object.defineProperty;var p=(s,t)=>b(s,"name",{value:t,configurable:!0});var v=Object.defineProperty,h=p((s,t)=>v(s,"name",{value:t,configurable:!0}),"h"),m=Object.defineProperty,d=h((s,t)=>m(s,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=trustExecutor,exports.collectHosts=collectHosts;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),basic_ssl_1=require("../../basic-ssl"),checkout_cache_1=require("../../checkout-cache"),hostname_1=require("./hostname");async function trustExecutor(s,t){const r=(0,checkout_cache_1.checkoutCacheDir)(t.root,"davnx-webpack"),c=(0,basic_ssl_1.ensureCaSync)(r),a=process.env.LENSMCP_TRUST_HOSTS_ONLY==="1",u=collectHosts(s,t);if(u.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 ${c} in your OS/browser store (Linux: update-ca-certificates / certutil)`);for(const e of u)console.log(` \u2022 /etc/hosts: "127.0.0.1 ${e}" and "::1 ${e}"`);return{success:!0}}const o=caSha256Fingerprint(c),f=a||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(a)console.log("[trust] hosts-only: a shared daemon serves TLS with its own CA \u2014 skipping the keychain step.");else if(f)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): ${c}`),(0,node_child_process_1.spawnSync)("sudo",["security","add-trusted-cert","-d","-r","trustRoot","-k","/Library/Keychains/System.keychain",c],{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 i=fs.readFileSync("/etc/hosts","utf8"),n=d((e,S)=>i.split(`
2
+ `).some(w=>{const y=w.trim();if(y.startsWith("#"))return!1;const g=y.split(/\s+/);return g[0]===e&&g.slice(1).includes(S)}),"hasEntry"),l=[];for(const e of u)n("127.0.0.1",e)||l.push(`127.0.0.1 ${e}`),n("::1",e)||l.push(`::1 ${e}`);if(l.length===0)console.log("[trust] /etc/hosts already complete (both families for every hostname).");else{if(console.log(`[trust] appending to /etc/hosts (sudo):
3
3
  ${l.join(`
4
4
  `)}`),(0,node_child_process_1.spawnSync)("sudo",["tee","-a","/etc/hosts"],{input:l.join(`
5
5
  `)+`
6
- `,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(!a){const e=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",c,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${e.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const e of u)console.log(`[trust] ${e} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}h(trustExecutor,"trustExecutor"),d(trustExecutor,"trustExecutor");function caSha256Fingerprint(o){const t=(0,node_child_process_1.spawnSync)("openssl",["x509","-in",o,"-noout","-fingerprint","-sha256"],{encoding:"utf8"});if(t.status!==0||!t.stdout)return;const r=t.stdout.split("=")[1]?.replaceAll(":","").trim().toUpperCase();return r&&/^[0-9A-F]{64}$/.test(r)?r:void 0}h(caSha256Fingerprint,"caSha256Fingerprint"),d(caSha256Fingerprint,"caSha256Fingerprint");function collectHosts(o,t){const r=[],c=t.projectName?t.projectsConfigurations?.projects[t.projectName]:void 0,a=o.serveTarget??"serve-hmr",u=c?.targets?.[a]?.options?.gateway?.routes??[];for(const s of u)s.host&&(0,hostname_1.isValidHostname)(s.host)?r.push(s.host):s.host&&console.warn(`[trust] ignoring invalid hostname in ${a} routes: ${JSON.stringify(s.host)}`);for(const s of Object.values(t.projectsConfigurations?.projects??{}))try{const p=JSON.parse(fs.readFileSync(path.join(t.root,s.root,"project.json"),"utf8")),i=p.cluster??p.davnx,n=i?.host;n&&!(0,hostname_1.isValidHostname)(n)&&console.warn(`[trust] ignoring invalid hostname in ${s.root}/project.json: ${JSON.stringify(n)}`),n&&(0,hostname_1.isValidHostname)(n)&&(r.push(n),i?.service&&i.internalHost!==!1&&r.push(typeof i.internalHost=="string"?i.internalHost:`internal.${n}`))}catch{}return[...new Set([...r,"lensmcp.local",...o.hosts??[]])]}h(collectHosts,"collectHosts"),d(collectHosts,"collectHosts");
6
+ `,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(!a){const e=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",c,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${e.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const e of u)console.log(`[trust] ${e} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}p(trustExecutor,"trustExecutor"),h(trustExecutor,"trustExecutor"),d(trustExecutor,"trustExecutor");function caSha256Fingerprint(s){const t=(0,node_child_process_1.spawnSync)("openssl",["x509","-in",s,"-noout","-fingerprint","-sha256"],{encoding:"utf8"});if(t.status!==0||!t.stdout)return;const r=t.stdout.split("=")[1]?.replaceAll(":","").trim().toUpperCase();return r&&/^[0-9A-F]{64}$/.test(r)?r:void 0}p(caSha256Fingerprint,"caSha256Fingerprint"),h(caSha256Fingerprint,"caSha256Fingerprint"),d(caSha256Fingerprint,"caSha256Fingerprint");function collectHosts(s,t){const r=[],c=t.projectName?t.projectsConfigurations?.projects[t.projectName]:void 0,a=s.serveTarget??"serve-hmr",u=c?.targets?.[a]?.options?.gateway?.routes??[];for(const o of u)o.host&&(0,hostname_1.isValidHostname)(o.host)?r.push(o.host):o.host&&console.warn(`[trust] ignoring invalid hostname in ${a} routes: ${JSON.stringify(o.host)}`);for(const o of Object.values(t.projectsConfigurations?.projects??{}))try{const f=JSON.parse(fs.readFileSync(path.join(t.root,o.root,"project.json"),"utf8")),i=f.cluster??f.davnx,n=i?.host;n&&!(0,hostname_1.isValidHostname)(n)&&console.warn(`[trust] ignoring invalid hostname in ${o.root}/project.json: ${JSON.stringify(n)}`),n&&(0,hostname_1.isValidHostname)(n)&&(r.push(n),i?.service&&i.internalHost!==!1&&r.push(typeof i.internalHost=="string"?i.internalHost:`internal.${n}`))}catch{}return[...new Set([...r,"lensmcp.local",...s.hosts??[]])]}p(collectHosts,"collectHosts"),h(collectHosts,"collectHosts"),d(collectHosts,"collectHosts");
package/exit-reason.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var l=Object.defineProperty;var s=(t,e)=>l(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,i=s((t,e)=>h(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TailBuffer=void 0,exports.describeExit=describeExit,exports.crashReport=crashReport;class TailBuffer{static{s(this,"TailBuffer")}static{i(this,"TailBuffer")}constructor(e=20,o=500){this.max=e,this.maxLineChars=o,this.lines=[]}push(e){e&&(this.lines.push(e.length>this.maxLineChars?`${e.slice(0,this.maxLineChars)}\u2026`:e),this.lines.length>this.max&&this.lines.shift())}snapshot(){return[...this.lines]}}exports.TailBuffer=TailBuffer;function describeExit(t,e){return e==="SIGKILL"||t===137?"killed with SIGKILL \u2014 the kernel OOM killer, or something outside the dev cluster (`kill -9`, a container memory limit); not a crash in the app":e==="SIGSEGV"||e==="SIGBUS"||e==="SIGABRT"?`died on ${e} \u2014 a native crash or a V8 abort (a heap out-of-memory prints "FATAL ERROR" on stderr first)`:e==="SIGPIPE"?"died on SIGPIPE \u2014 it wrote to a closed pipe":e==="SIGHUP"?"received SIGHUP \u2014 its terminal or parent session went away":e==="SIGINT"||e==="SIGTERM"||t===0?null:t===134?"aborted (exit 134, SIGABRT) \u2014 usually a V8 heap out-of-memory":t===1?"exited 1 \u2014 an uncaught exception or an explicit process.exit(1)":t!==null?`exited ${t}`:null}s(describeExit,"describeExit"),i(describeExit,"describeExit");function crashReport(t,e,o,n){const a=describeExit(e,o),r=[t+(a?` \u2014 ${a}`:"")];if(n.length){r.push(` last ${n.length} line(s) of output before it died:`);for(const u of n)r.push(` | ${u}`)}else r.push(" (it wrote nothing to stdout/stderr before it died)");return r.join(`
2
- `)}s(crashReport,"crashReport"),i(crashReport,"crashReport");
1
+ "use strict";var p=Object.defineProperty;var r=(t,e)=>p(t,"name",{value:e,configurable:!0});var l=Object.defineProperty,s=r((t,e)=>l(t,"name",{value:e,configurable:!0}),"s"),h=Object.defineProperty,i=s((t,e)=>h(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TailBuffer=void 0,exports.describeExit=describeExit,exports.crashReport=crashReport;class TailBuffer{static{r(this,"TailBuffer")}static{s(this,"TailBuffer")}static{i(this,"TailBuffer")}constructor(e=20,a=500){this.max=e,this.maxLineChars=a,this.lines=[]}push(e){e&&(this.lines.push(e.length>this.maxLineChars?`${e.slice(0,this.maxLineChars)}\u2026`:e),this.lines.length>this.max&&this.lines.shift())}snapshot(){return[...this.lines]}}exports.TailBuffer=TailBuffer;function describeExit(t,e){return e==="SIGKILL"||t===137?"killed with SIGKILL \u2014 the kernel OOM killer, or something outside the dev cluster (`kill -9`, a container memory limit); not a crash in the app":e==="SIGSEGV"||e==="SIGBUS"||e==="SIGABRT"?`died on ${e} \u2014 a native crash or a V8 abort (a heap out-of-memory prints "FATAL ERROR" on stderr first)`:e==="SIGPIPE"?"died on SIGPIPE \u2014 it wrote to a closed pipe":e==="SIGHUP"?"received SIGHUP \u2014 its terminal or parent session went away":e==="SIGINT"||e==="SIGTERM"||t===0?null:t===134?"aborted (exit 134, SIGABRT) \u2014 usually a V8 heap out-of-memory":t===1?"exited 1 \u2014 an uncaught exception or an explicit process.exit(1)":t!==null?`exited ${t}`:null}r(describeExit,"describeExit"),s(describeExit,"describeExit"),i(describeExit,"describeExit");function crashReport(t,e,a,n){const u=describeExit(e,a),o=[t+(u?` \u2014 ${u}`:"")];if(n.length){o.push(` last ${n.length} line(s) of output before it died:`);for(const c of n)o.push(` | ${c}`)}else o.push(" (it wrote nothing to stdout/stderr before it died)");return o.join(`
2
+ `)}r(crashReport,"crashReport"),s(crashReport,"crashReport"),i(crashReport,"crashReport");
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var o=(e,t)=>p(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,r=o((e,t)=>a(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForkTsCheckReporterPlugin=void 0,exports.loadForkTsChecker=loadForkTsChecker;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");function loadForkTsChecker(e){const t=[];try{t.push(path.dirname(require.resolve("@nx/webpack/package.json",{paths:[e]})))}catch{}t.push(e,__dirname);for(const s of t)try{return require(require.resolve("fork-ts-checker-webpack-plugin",{paths:[s]}))}catch{}return null}o(loadForkTsChecker,"loadForkTsChecker"),r(loadForkTsChecker,"loadForkTsChecker");function toDiagnostic(e,t){return{file:e.file?path.relative(t,e.file)||e.file:"<unknown>",line:e.location?.start?.line??0,column:e.location?.start?.column??0,severity:e.severity==="warning"?"warning":"error",code:/^TS\d+$/.test(e.code)?e.code:`TS${e.code}`,message:e.message}}o(toDiagnostic,"toDiagnostic"),r(toDiagnostic,"toDiagnostic");class ForkTsCheckReporterPlugin{static{o(this,"ForkTsCheckReporterPlugin")}static{r(this,"ForkTsCheckReporterPlugin")}constructor(t){this.startedAt=0,this.opts=t}apply(t){const s=loadForkTsChecker(this.opts.workspaceRoot)?.getCompilerHooks;if(typeof s!="function")return;let c;try{c=s(t)}catch{return}c.start?.tapPromise("LensmcpForkTsCheckReporter",async i=>(this.startedAt=Date.now(),i)),c.issues?.tap("LensmcpForkTsCheckReporter",i=>{try{(0,typecheck_bus_1.publishTypecheckDiagnostics)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"fork-ts-checker",tsConfig:this.opts.tsConfig,diagnostics:(i??[]).map(n=>toDiagnostic(n,this.opts.workspaceRoot)),durationMs:this.startedAt?Date.now()-this.startedAt:0,...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}return i})}}exports.ForkTsCheckReporterPlugin=ForkTsCheckReporterPlugin;
1
+ "use strict";var h=Object.defineProperty;var s=(e,t)=>h(e,"name",{value:t,configurable:!0});var p=Object.defineProperty,o=s((e,t)=>p(e,"name",{value:t,configurable:!0}),"o"),a=Object.defineProperty,r=o((e,t)=>a(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForkTsCheckReporterPlugin=void 0,exports.loadForkTsChecker=loadForkTsChecker;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");function loadForkTsChecker(e){const t=[];try{t.push(path.dirname(require.resolve("@nx/webpack/package.json",{paths:[e]})))}catch{}t.push(e,__dirname);for(const i of t)try{return require(require.resolve("fork-ts-checker-webpack-plugin",{paths:[i]}))}catch{}return null}s(loadForkTsChecker,"loadForkTsChecker"),o(loadForkTsChecker,"loadForkTsChecker"),r(loadForkTsChecker,"loadForkTsChecker");function toDiagnostic(e,t){return{file:e.file?path.relative(t,e.file)||e.file:"<unknown>",line:e.location?.start?.line??0,column:e.location?.start?.column??0,severity:e.severity==="warning"?"warning":"error",code:/^TS\d+$/.test(e.code)?e.code:`TS${e.code}`,message:e.message}}s(toDiagnostic,"toDiagnostic"),o(toDiagnostic,"toDiagnostic"),r(toDiagnostic,"toDiagnostic");class ForkTsCheckReporterPlugin{static{s(this,"ForkTsCheckReporterPlugin")}static{o(this,"ForkTsCheckReporterPlugin")}static{r(this,"ForkTsCheckReporterPlugin")}constructor(t){this.startedAt=0,this.opts=t}apply(t){const i=loadForkTsChecker(this.opts.workspaceRoot)?.getCompilerHooks;if(typeof i!="function")return;let n;try{n=i(t)}catch{return}n.start?.tapPromise("LensmcpForkTsCheckReporter",async c=>(this.startedAt=Date.now(),c)),n.issues?.tap("LensmcpForkTsCheckReporter",c=>{try{(0,typecheck_bus_1.publishTypecheckDiagnostics)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"fork-ts-checker",tsConfig:this.opts.tsConfig,diagnostics:(c??[]).map(l=>toDiagnostic(l,this.opts.workspaceRoot)),durationMs:this.startedAt?Date.now()-this.startedAt:0,...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}return c})}}exports.ForkTsCheckReporterPlugin=ForkTsCheckReporterPlugin;
package/gateway.js CHANGED
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var i=(r,t)=>s(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.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")});
1
+ "use strict";var n=Object.defineProperty;var a=(r,t)=>n(r,"name",{value:t,configurable:!0});var s=Object.defineProperty,i=a((r,t)=>s(r,"name",{value:t,configurable:!0}),"i"),o=Object.defineProperty,e=i((r,t)=>o(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),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")});
package/gc-notice.js CHANGED
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var c=(e,t)=>u(e,"name",{value:t,configurable:!0});var i=Object.defineProperty,r=c((e,t)=>i(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),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"));exports.GC_NOTICE_SUFFIX=".gc";function gcNoticePath(e){return`${e}${exports.GC_NOTICE_SUFFIX}`}c(gcNoticePath,"gcNoticePath"),r(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}c(gcNoticeMaxMs,"gcNoticeMaxMs"),r(gcNoticeMaxMs,"gcNoticeMaxMs");function withGcNotice(e,t,o=Date.now){if(!e)return t();try{fs.writeFileSync(gcNoticePath(e),String(o()),{mode:384})}catch{}try{return t()}finally{clearGcNotice(e)}}c(withGcNotice,"withGcNotice"),r(withGcNotice,"withGcNotice");function clearGcNotice(e){try{fs.unlinkSync(gcNoticePath(e))}catch{}}c(clearGcNotice,"clearGcNotice"),r(clearGcNotice,"clearGcNotice");function inAnnouncedGc(e,t=Date.now(),o=gcNoticeMaxMs()){try{const n=Number(fs.readFileSync(gcNoticePath(e),"utf8").trim());return Number.isFinite(n)&&n>0&&t-n>=0&&t-n<o}catch{return!1}}c(inAnnouncedGc,"inAnnouncedGc"),r(inAnnouncedGc,"inAnnouncedGc");
1
+ "use strict";var N=Object.defineProperty;var n=(e,t)=>N(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,c=n((e,t)=>u(e,"name",{value:t,configurable:!0}),"c"),i=Object.defineProperty,r=c((e,t)=>i(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),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"));exports.GC_NOTICE_SUFFIX=".gc";function gcNoticePath(e){return`${e}${exports.GC_NOTICE_SUFFIX}`}n(gcNoticePath,"gcNoticePath"),c(gcNoticePath,"gcNoticePath"),r(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}n(gcNoticeMaxMs,"gcNoticeMaxMs"),c(gcNoticeMaxMs,"gcNoticeMaxMs"),r(gcNoticeMaxMs,"gcNoticeMaxMs");function withGcNotice(e,t,a=Date.now){if(!e)return t();try{fs.writeFileSync(gcNoticePath(e),String(a()),{mode:384})}catch{}try{return t()}finally{clearGcNotice(e)}}n(withGcNotice,"withGcNotice"),c(withGcNotice,"withGcNotice"),r(withGcNotice,"withGcNotice");function clearGcNotice(e){try{fs.unlinkSync(gcNoticePath(e))}catch{}}n(clearGcNotice,"clearGcNotice"),c(clearGcNotice,"clearGcNotice"),r(clearGcNotice,"clearGcNotice");function inAnnouncedGc(e,t=Date.now(),a=gcNoticeMaxMs()){try{const o=Number(fs.readFileSync(gcNoticePath(e),"utf8").trim());return Number.isFinite(o)&&o>0&&t-o>=0&&t-o<a}catch{return!1}}n(inAnnouncedGc,"inAnnouncedGc"),c(inAnnouncedGc,"inAnnouncedGc"),r(inAnnouncedGc,"inAnnouncedGc");
package/graph-snapshot.js CHANGED
@@ -1 +1 @@
1
- "use strict";var i=Object.defineProperty;var o=(r,e)=>i(r,"name",{value:e,configurable:!0});var t=Object.defineProperty,s=o((r,e)=>t(r,"name",{value:e,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),guest_graph_1=require("./executors/gateway/runtime/guest-graph");function main(){const r=process.argv[2];r||(console.error("usage: graph-snapshot.js <output file> \u2014 run in the workspace root"),process.exit(2)),(0,guest_graph_1.snapshotWorkspaceGraph)(process.cwd()).then(e=>{fs.writeFileSync(r,JSON.stringify(e),{mode:384}),process.exit(0)},e=>{console.error(`[graph-snapshot] ${e?.message??String(e)}`),process.exit(1)})}o(main,"main"),s(main,"main"),require.main===module&&main();
1
+ "use strict";var n=Object.defineProperty;var a=(r,e)=>n(r,"name",{value:e,configurable:!0});var i=Object.defineProperty,o=a((r,e)=>i(r,"name",{value:e,configurable:!0}),"o"),t=Object.defineProperty,s=o((r,e)=>t(r,"name",{value:e,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),guest_graph_1=require("./executors/gateway/runtime/guest-graph");function main(){const r=process.argv[2];r||(console.error("usage: graph-snapshot.js <output file> \u2014 run in the workspace root"),process.exit(2)),(0,guest_graph_1.snapshotWorkspaceGraph)(process.cwd()).then(e=>{fs.writeFileSync(r,JSON.stringify(e),{mode:384}),process.exit(0)},e=>{console.error(`[graph-snapshot] ${e?.message??String(e)}`),process.exit(1)})}a(main,"main"),o(main,"main"),s(main,"main"),require.main===module&&main();
package/handoff-retire.js CHANGED
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var o=(e,r)=>a(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,n=o((e,r)=>i(e,"name",{value:r,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.HANDOFF_MARKER_FRESH_MS=void 0,exports.handoffRetireMarker=handoffRetireMarker,exports.requestHandoffRetire=requestHandoffRetire,exports.clearHandoffRetire=clearHandoffRetire,exports.handoffRetireRequested=handoffRetireRequested,exports.handoffDrainBoundMs=handoffDrainBoundMs;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path"));exports.HANDOFF_MARKER_FRESH_MS=6e4;function handoffRetireMarker(e,r){return path.join(e,`retire-g${r}`)}o(handoffRetireMarker,"handoffRetireMarker"),n(handoffRetireMarker,"handoffRetireMarker");function requestHandoffRetire(e,r,t=Date.now()){try{return fs.writeFileSync(handoffRetireMarker(e,r),String(t),{mode:384}),!0}catch{return!1}}o(requestHandoffRetire,"requestHandoffRetire"),n(requestHandoffRetire,"requestHandoffRetire");function clearHandoffRetire(e,r){try{fs.unlinkSync(handoffRetireMarker(e,r))}catch{}}o(clearHandoffRetire,"clearHandoffRetire"),n(clearHandoffRetire,"clearHandoffRetire");function handoffRetireRequested(e,r,t=Date.now()){try{const f=Number(fs.readFileSync(handoffRetireMarker(e,r),"utf8").trim());return Number.isFinite(f)&&f>0&&t-f<exports.HANDOFF_MARKER_FRESH_MS}catch{return!1}}o(handoffRetireRequested,"handoffRetireRequested"),n(handoffRetireRequested,"handoffRetireRequested");function handoffDrainBoundMs(e=process.env){const r=Number(e.LENSMCP_POD_HANDOFF_DRAIN_MS);if(e.LENSMCP_POD_HANDOFF_DRAIN_MS!==void 0&&e.LENSMCP_POD_HANDOFF_DRAIN_MS!==""&&Number.isFinite(r)&&r>=0)return Math.floor(r);const t=Number(e.LENSMCP_SWAP_DRAIN_MS);return(e.LENSMCP_SWAP_DRAIN_MS!==void 0&&e.LENSMCP_SWAP_DRAIN_MS!==""&&Number.isFinite(t)&&t>=0?t:15*6e4)+9e4}o(handoffDrainBoundMs,"handoffDrainBoundMs"),n(handoffDrainBoundMs,"handoffDrainBoundMs");
1
+ "use strict";var d=Object.defineProperty;var f=(e,r)=>d(e,"name",{value:r,configurable:!0});var a=Object.defineProperty,o=f((e,r)=>a(e,"name",{value:r,configurable:!0}),"o"),i=Object.defineProperty,n=o((e,r)=>i(e,"name",{value:r,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.HANDOFF_MARKER_FRESH_MS=void 0,exports.handoffRetireMarker=handoffRetireMarker,exports.requestHandoffRetire=requestHandoffRetire,exports.clearHandoffRetire=clearHandoffRetire,exports.handoffRetireRequested=handoffRetireRequested,exports.handoffDrainBoundMs=handoffDrainBoundMs;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path"));exports.HANDOFF_MARKER_FRESH_MS=6e4;function handoffRetireMarker(e,r){return path.join(e,`retire-g${r}`)}f(handoffRetireMarker,"handoffRetireMarker"),o(handoffRetireMarker,"handoffRetireMarker"),n(handoffRetireMarker,"handoffRetireMarker");function requestHandoffRetire(e,r,t=Date.now()){try{return fs.writeFileSync(handoffRetireMarker(e,r),String(t),{mode:384}),!0}catch{return!1}}f(requestHandoffRetire,"requestHandoffRetire"),o(requestHandoffRetire,"requestHandoffRetire"),n(requestHandoffRetire,"requestHandoffRetire");function clearHandoffRetire(e,r){try{fs.unlinkSync(handoffRetireMarker(e,r))}catch{}}f(clearHandoffRetire,"clearHandoffRetire"),o(clearHandoffRetire,"clearHandoffRetire"),n(clearHandoffRetire,"clearHandoffRetire");function handoffRetireRequested(e,r,t=Date.now()){try{const u=Number(fs.readFileSync(handoffRetireMarker(e,r),"utf8").trim());return Number.isFinite(u)&&u>0&&t-u<exports.HANDOFF_MARKER_FRESH_MS}catch{return!1}}f(handoffRetireRequested,"handoffRetireRequested"),o(handoffRetireRequested,"handoffRetireRequested"),n(handoffRetireRequested,"handoffRetireRequested");function handoffDrainBoundMs(e=process.env){const r=Number(e.LENSMCP_POD_HANDOFF_DRAIN_MS);if(e.LENSMCP_POD_HANDOFF_DRAIN_MS!==void 0&&e.LENSMCP_POD_HANDOFF_DRAIN_MS!==""&&Number.isFinite(r)&&r>=0)return Math.floor(r);const t=Number(e.LENSMCP_SWAP_DRAIN_MS);return(e.LENSMCP_SWAP_DRAIN_MS!==void 0&&e.LENSMCP_SWAP_DRAIN_MS!==""&&Number.isFinite(t)&&t>=0?t:15*6e4)+9e4}f(handoffDrainBoundMs,"handoffDrainBoundMs"),o(handoffDrainBoundMs,"handoffDrainBoundMs"),n(handoffDrainBoundMs,"handoffDrainBoundMs");
package/heap-snapshot.js CHANGED
@@ -1 +1 @@
1
- "use strict";var _=Object.defineProperty;var p=(e,t)=>_(e,"name",{value:t,configurable:!0});var m=Object.defineProperty,i=p((e,t)=>m(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.heapSnapshotPolicy=heapSnapshotPolicy,exports.availableSystemMemory=availableSystemMemory,exports.heapSnapshotRefusal=heapSnapshotRefusal,exports.heapSnapshotDir=heapSnapshotDir,exports.heapSnapshotFileName=heapSnapshotFileName,exports.ensureHeapDir=ensureHeapDir,exports.pruneHeapSnapshots=pruneHeapSnapshots,exports.writeHeapSnapshot=writeHeapSnapshot;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),inspector=tslib_1.__importStar(require("node:inspector")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),MB=1024*1024,numberFrom=i((e,t,s)=>{if(e===void 0||e.trim()==="")return t;const a=Number(e);return Number.isFinite(a)&&a>=s?a:t},"numberFrom");function heapSnapshotPolicy(e=process.env){return{maxHeapBytes:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MAX_MB,1024,1)*MB,minFreeBytes:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MIN_FREE_MB,1024,0)*MB,freeFactor:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_FREE_FACTOR,3,0),keep:Math.max(1,Math.floor(numberFrom(e.LENSMCP_HEAP_SNAPSHOT_KEEP,3,1))),maxAgeMs:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MAX_AGE_H,24,0)*36e5}}p(heapSnapshotPolicy,"heapSnapshotPolicy"),i(heapSnapshotPolicy,"heapSnapshotPolicy");function availableSystemMemory(e=process.platform){try{if(e==="darwin"){const t=(0,node_child_process_1.spawnSync)("vm_stat",[],{encoding:"utf8",timeout:2e3}).stdout??"",s=Number(/page size of (\d+) bytes/.exec(t)?.[1]??4096),a=i(r=>Number(new RegExp(`Pages ${r}:\\s+(\\d+)`).exec(t)?.[1]??0),"pages"),o=a("free")+a("inactive")+a("speculative")+a("purgeable");if(o>0)return{bytes:o*s,source:"vm_stat free+inactive+speculative+purgeable"}}else if(e==="linux"){const t=/MemAvailable:\s+(\d+) kB/.exec(fs.readFileSync("/proc/meminfo","utf8"));if(t)return{bytes:Number(t[1])*1024,source:"/proc/meminfo MemAvailable"}}return{bytes:os.freemem(),source:"os.freemem()"}}catch{return}}p(availableSystemMemory,"availableSystemMemory"),i(availableSystemMemory,"availableSystemMemory");function heapSnapshotRefusal(e,t){if(t.live>e.maxHeapBytes){const s=Math.ceil(t.live/MB/256)*256;return`the pod's live heap is ${Math.round(t.live/MB)} MB, over the ${Math.round(e.maxHeapBytes/MB)} MB bound \u2014 a snapshot this size needs several times that in memory while it is written. Raise the bound for this one snapshot with \`--max-mb ${s}\` (the free-memory check still applies); the default is LENSMCP_HEAP_SNAPSHOT_MAX_MB, read when the pod starts`}if(t.available){const s=Math.max(e.minFreeBytes,e.freeFactor*t.live);if(t.available.bytes<s)return`only ${Math.round(t.available.bytes/MB)} MB of memory is available (${t.available.source}) and a snapshot of a ${Math.round(t.live/MB)} MB heap needs about ${Math.round(s/MB)} MB \u2014 free some memory first, or lower the floor with LENSMCP_HEAP_SNAPSHOT_MIN_FREE_MB / LENSMCP_HEAP_SNAPSHOT_FREE_FACTOR`}}p(heapSnapshotRefusal,"heapSnapshotRefusal"),i(heapSnapshotRefusal,"heapSnapshotRefusal");function heapSnapshotDir(e=process.env,t=process.cwd()){return e.LENSMCP_HEAP_DIR?path.resolve(e.LENSMCP_HEAP_DIR):e.LENSMCP_EVENT_FILE?path.join(path.dirname(path.resolve(e.LENSMCP_EVENT_FILE)),"heap"):path.join(t,".lensmcp","heap")}p(heapSnapshotDir,"heapSnapshotDir"),i(heapSnapshotDir,"heapSnapshotDir");function heapSnapshotFileName(e,t,s,a,o){const r=(e||"service").replace(/[^A-Za-z0-9_.-]/g,"_"),n=new Date(o).toISOString().replace(/[:.]/g,"-");return`${r}-pod${t}-pid${s}-g${a}-${n}.heapsnapshot`}p(heapSnapshotFileName,"heapSnapshotFileName"),i(heapSnapshotFileName,"heapSnapshotFileName");function ensureHeapDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});const t=fs.lstatSync(e);if(!t.isDirectory())throw new Error(`${e} is not a directory`);(t.mode&63)!==0&&fs.chmodSync(e,448)}p(ensureHeapDir,"ensureHeapDir"),i(ensureHeapDir,"ensureHeapDir");function pruneHeapSnapshots(e,t,s=Date.now()){const a=[];let o;try{o=fs.readdirSync(e).filter(r=>r.endsWith(".heapsnapshot")).map(r=>{const n=path.join(e,r),h=fs.lstatSync(n);return h.isFile()?{file:n,mtime:h.mtimeMs}:void 0}).filter(r=>r!==void 0).sort((r,n)=>n.mtime-r.mtime)}catch{return a}return o.forEach((r,n)=>{if(n>=t.keep-1||s-r.mtime>t.maxAgeMs)try{fs.unlinkSync(r.file),a.push(r.file)}catch{}}),a}p(pruneHeapSnapshots,"pruneHeapSnapshots"),i(pruneHeapSnapshots,"pruneHeapSnapshots");function writeHeapSnapshot(e){const t=Date.now(),s=fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW??0),a=fs.openSync(e,s,384),o=new inspector.Session;let r=0,n;return new Promise((h,S)=>{const u=i(c=>{o.removeAllListeners("HeapProfiler.addHeapSnapshotChunk");try{o.disconnect()}catch{}try{fs.closeSync(a)}catch{}const l=c??n;if(l){try{fs.unlinkSync(e)}catch{}S(l);return}h({bytes:r,ms:Date.now()-t})},"finish");try{o.connect(),o.on("HeapProfiler.addHeapSnapshotChunk",c=>{if(!n)try{r+=fs.writeSync(a,c.params.chunk)}catch(l){n=l}}),o.post("HeapProfiler.takeHeapSnapshot",{reportProgress:!1},c=>u(c))}catch(c){u(c)}})}p(writeHeapSnapshot,"writeHeapSnapshot"),i(writeHeapSnapshot,"writeHeapSnapshot");
1
+ "use strict";var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});var _=Object.defineProperty,p=c((e,t)=>_(e,"name",{value:t,configurable:!0}),"p"),m=Object.defineProperty,i=p((e,t)=>m(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.heapSnapshotPolicy=heapSnapshotPolicy,exports.availableSystemMemory=availableSystemMemory,exports.heapSnapshotRefusal=heapSnapshotRefusal,exports.heapSnapshotDir=heapSnapshotDir,exports.heapSnapshotFileName=heapSnapshotFileName,exports.ensureHeapDir=ensureHeapDir,exports.pruneHeapSnapshots=pruneHeapSnapshots,exports.writeHeapSnapshot=writeHeapSnapshot;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),inspector=tslib_1.__importStar(require("node:inspector")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),MB=1024*1024,numberFrom=i((e,t,s)=>{if(e===void 0||e.trim()==="")return t;const r=Number(e);return Number.isFinite(r)&&r>=s?r:t},"numberFrom");function heapSnapshotPolicy(e=process.env){return{maxHeapBytes:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MAX_MB,1024,1)*MB,minFreeBytes:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MIN_FREE_MB,1024,0)*MB,freeFactor:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_FREE_FACTOR,3,0),keep:Math.max(1,Math.floor(numberFrom(e.LENSMCP_HEAP_SNAPSHOT_KEEP,3,1))),maxAgeMs:numberFrom(e.LENSMCP_HEAP_SNAPSHOT_MAX_AGE_H,24,0)*36e5}}c(heapSnapshotPolicy,"heapSnapshotPolicy"),p(heapSnapshotPolicy,"heapSnapshotPolicy"),i(heapSnapshotPolicy,"heapSnapshotPolicy");function availableSystemMemory(e=process.platform){try{if(e==="darwin"){const t=(0,node_child_process_1.spawnSync)("vm_stat",[],{encoding:"utf8",timeout:2e3}).stdout??"",s=Number(/page size of (\d+) bytes/.exec(t)?.[1]??4096),r=i(a=>Number(new RegExp(`Pages ${a}:\\s+(\\d+)`).exec(t)?.[1]??0),"pages"),n=r("free")+r("inactive")+r("speculative")+r("purgeable");if(n>0)return{bytes:n*s,source:"vm_stat free+inactive+speculative+purgeable"}}else if(e==="linux"){const t=/MemAvailable:\s+(\d+) kB/.exec(fs.readFileSync("/proc/meminfo","utf8"));if(t)return{bytes:Number(t[1])*1024,source:"/proc/meminfo MemAvailable"}}return{bytes:os.freemem(),source:"os.freemem()"}}catch{return}}c(availableSystemMemory,"availableSystemMemory"),p(availableSystemMemory,"availableSystemMemory"),i(availableSystemMemory,"availableSystemMemory");function heapSnapshotRefusal(e,t){if(t.live>e.maxHeapBytes){const s=Math.ceil(t.live/MB/256)*256;return`the pod's live heap is ${Math.round(t.live/MB)} MB, over the ${Math.round(e.maxHeapBytes/MB)} MB bound \u2014 a snapshot this size needs several times that in memory while it is written. Raise the bound for this one snapshot with \`--max-mb ${s}\` (the free-memory check still applies); the default is LENSMCP_HEAP_SNAPSHOT_MAX_MB, read when the pod starts`}if(t.available){const s=Math.max(e.minFreeBytes,e.freeFactor*t.live);if(t.available.bytes<s)return`only ${Math.round(t.available.bytes/MB)} MB of memory is available (${t.available.source}) and a snapshot of a ${Math.round(t.live/MB)} MB heap needs about ${Math.round(s/MB)} MB \u2014 free some memory first, or lower the floor with LENSMCP_HEAP_SNAPSHOT_MIN_FREE_MB / LENSMCP_HEAP_SNAPSHOT_FREE_FACTOR`}}c(heapSnapshotRefusal,"heapSnapshotRefusal"),p(heapSnapshotRefusal,"heapSnapshotRefusal"),i(heapSnapshotRefusal,"heapSnapshotRefusal");function heapSnapshotDir(e=process.env,t=process.cwd()){return e.LENSMCP_HEAP_DIR?path.resolve(e.LENSMCP_HEAP_DIR):e.LENSMCP_EVENT_FILE?path.join(path.dirname(path.resolve(e.LENSMCP_EVENT_FILE)),"heap"):path.join(t,".lensmcp","heap")}c(heapSnapshotDir,"heapSnapshotDir"),p(heapSnapshotDir,"heapSnapshotDir"),i(heapSnapshotDir,"heapSnapshotDir");function heapSnapshotFileName(e,t,s,r,n){const a=(e||"service").replace(/[^A-Za-z0-9_.-]/g,"_"),o=new Date(n).toISOString().replace(/[:.]/g,"-");return`${a}-pod${t}-pid${s}-g${r}-${o}.heapsnapshot`}c(heapSnapshotFileName,"heapSnapshotFileName"),p(heapSnapshotFileName,"heapSnapshotFileName"),i(heapSnapshotFileName,"heapSnapshotFileName");function ensureHeapDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});const t=fs.lstatSync(e);if(!t.isDirectory())throw new Error(`${e} is not a directory`);(t.mode&63)!==0&&fs.chmodSync(e,448)}c(ensureHeapDir,"ensureHeapDir"),p(ensureHeapDir,"ensureHeapDir"),i(ensureHeapDir,"ensureHeapDir");function pruneHeapSnapshots(e,t,s=Date.now()){const r=[];let n;try{n=fs.readdirSync(e).filter(a=>a.endsWith(".heapsnapshot")).map(a=>{const o=path.join(e,a),l=fs.lstatSync(o);return l.isFile()?{file:o,mtime:l.mtimeMs}:void 0}).filter(a=>a!==void 0).sort((a,o)=>o.mtime-a.mtime)}catch{return r}return n.forEach((a,o)=>{if(o>=t.keep-1||s-a.mtime>t.maxAgeMs)try{fs.unlinkSync(a.file),r.push(a.file)}catch{}}),r}c(pruneHeapSnapshots,"pruneHeapSnapshots"),p(pruneHeapSnapshots,"pruneHeapSnapshots"),i(pruneHeapSnapshots,"pruneHeapSnapshots");function writeHeapSnapshot(e){const t=Date.now(),s=fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW??0),r=fs.openSync(e,s,384),n=new inspector.Session;let a=0,o;return new Promise((l,f)=>{const S=i(h=>{n.removeAllListeners("HeapProfiler.addHeapSnapshotChunk");try{n.disconnect()}catch{}try{fs.closeSync(r)}catch{}const u=h??o;if(u){try{fs.unlinkSync(e)}catch{}f(u);return}l({bytes:a,ms:Date.now()-t})},"finish");try{n.connect(),n.on("HeapProfiler.addHeapSnapshotChunk",h=>{if(!o)try{a+=fs.writeSync(r,h.params.chunk)}catch(u){o=u}}),n.post("HeapProfiler.takeHeapSnapshot",{reportProgress:!1},h=>S(h))}catch(h){S(h)}})}c(writeHeapSnapshot,"writeHeapSnapshot"),p(writeHeapSnapshot,"writeHeapSnapshot"),i(writeHeapSnapshot,"writeHeapSnapshot");