@lensmcp/cluster 1.25.79 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-scope-patterns.d.ts +1 -11
- package/build-scope-patterns.js +1 -1
- package/create-webpack-prod.d.ts +1 -27
- package/create-webpack-prod.js +1 -1
- package/executors/build/build.impl.js +1 -1
- package/executors/gateway/daemon.d.ts +43 -0
- package/executors/gateway/daemon.js +1 -0
- package/executors/gateway/gateway.lib.d.ts +1 -1
- package/executors/gateway/gateway.lib.js +1 -1
- package/executors/gateway/jwks-verify.d.ts +1 -79
- package/executors/gateway/jwks-verify.js +1 -1
- package/executors/gateway/main.rollout.d.ts +2 -1
- package/executors/gateway/main.rollout.js +1 -24
- package/executors/gateway/manifest.d.ts +1 -418
- package/executors/gateway/manifest.js +1 -1
- package/executors/gateway/prod-runtime/trust.d.ts +1 -80
- package/executors/gateway/prod-runtime/trust.js +1 -1
- package/executors/gateway/rate-limit.d.ts +1 -81
- package/executors/gateway/rate-limit.js +1 -18
- package/executors/gateway/runtime/auth.d.ts +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/dev-auth.d.ts +3 -2
- package/executors/gateway/runtime/dev-auth.js +1 -1
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/edge.d.ts +2 -2
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lens-modules.d.ts +13 -0
- package/executors/gateway/runtime/lens-modules.js +1 -0
- package/executors/gateway/runtime/lifecycle.js +1 -1
- package/executors/gateway/runtime/observability.js +1 -1
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/serve-launch.d.ts +27 -0
- package/executors/gateway/runtime/serve-launch.js +3 -3
- package/executors/gateway/runtime/server.d.ts +1 -1
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/services-decl.d.ts +24 -0
- package/executors/gateway/runtime/services-decl.js +1 -0
- package/executors/gateway/runtime/shared-build.d.ts +2 -2
- package/executors/gateway/runtime/shared-build.js +3 -3
- package/executors/gateway/runtime/types.d.ts +9 -3
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
- package/executors/gateway/runtime/workspace-auth.js +1 -1
- package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
- package/executors/gateway/runtime/workspace-middleware.js +1 -1
- package/executors/serve/lens-run.d.ts +6 -0
- package/executors/serve/lens-run.js +1 -0
- package/executors/serve/schema.d.ts +2 -0
- package/executors/serve/schema.json +4 -0
- package/executors/serve/serve.impl.js +1 -1
- package/executors/trust/run.d.ts +19 -0
- package/executors/trust/run.js +1 -0
- package/executors/trust/trust.impl.js +5 -5
- package/gateway.d.ts +7 -19
- package/gateway.js +1 -1
- package/gc-notice.d.ts +3 -1
- package/gc-notice.js +1 -1
- package/main.devserver.js +7 -7
- package/package.json +6 -34
- package/pod-memory.d.ts +19 -2
- package/pod-memory.js +1 -1
- package/tsgo-check-plugin.d.ts +3 -2
- package/tsgo-check-plugin.js +3 -3
- package/typecheck-bus.d.ts +17 -0
- package/typecheck-bus.js +4 -3
- package/executors/gateway/body-stall.d.ts +0 -62
- package/executors/gateway/body-stall.js +0 -1
- package/executors/gateway/canonical-path.d.ts +0 -65
- package/executors/gateway/canonical-path.js +0 -1
- package/executors/gateway/client-ip.d.ts +0 -82
- package/executors/gateway/client-ip.js +0 -1
- package/executors/gateway/gateway-errors.d.ts +0 -43
- package/executors/gateway/gateway-errors.js +0 -1
- package/executors/gateway/health-check.d.ts +0 -52
- package/executors/gateway/health-check.js +0 -1
- package/executors/gateway/jwt-claims.d.ts +0 -51
- package/executors/gateway/jwt-claims.js +0 -1
- package/executors/gateway/main.prod-gateway.d.ts +0 -1
- package/executors/gateway/main.prod-gateway.js +0 -2
- package/executors/gateway/metrics.d.ts +0 -36
- package/executors/gateway/metrics.js +0 -1
- package/executors/gateway/otel-tracing.d.ts +0 -46
- package/executors/gateway/otel-tracing.js +0 -1
- package/executors/gateway/prod-config.d.ts +0 -130
- package/executors/gateway/prod-config.js +0 -1
- package/executors/gateway/prod-gateway.lib.d.ts +0 -19
- package/executors/gateway/prod-gateway.lib.js +0 -1
- package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
- package/executors/gateway/prod-runtime/access-log.js +0 -1
- package/executors/gateway/prod-runtime/app.d.ts +0 -30
- package/executors/gateway/prod-runtime/app.js +0 -1
- package/executors/gateway/prod-runtime/auth.d.ts +0 -29
- package/executors/gateway/prod-runtime/auth.js +0 -1
- package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
- package/executors/gateway/prod-runtime/body-stall.js +0 -1
- package/executors/gateway/prod-runtime/cors.d.ts +0 -18
- package/executors/gateway/prod-runtime/cors.js +0 -1
- package/executors/gateway/prod-runtime/edge.d.ts +0 -44
- package/executors/gateway/prod-runtime/edge.js +0 -1
- package/executors/gateway/prod-runtime/handler.d.ts +0 -33
- package/executors/gateway/prod-runtime/handler.js +0 -1
- package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
- package/executors/gateway/prod-runtime/hooks.js +0 -1
- package/executors/gateway/prod-runtime/observability.d.ts +0 -24
- package/executors/gateway/prod-runtime/observability.js +0 -1
- package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
- package/executors/gateway/prod-runtime/rollout.js +0 -1
- package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
- package/executors/gateway/prod-runtime/route-limits.js +0 -1
- package/executors/gateway/prod-runtime/routing.d.ts +0 -3
- package/executors/gateway/prod-runtime/routing.js +0 -1
- package/executors/gateway/prod-runtime/server.d.ts +0 -17
- package/executors/gateway/prod-runtime/server.js +0 -1
- package/executors/gateway/prod-runtime/types.d.ts +0 -335
- package/executors/gateway/prod-runtime/types.js +0 -1
- package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
- package/executors/gateway/prod-runtime/upgrade.js +0 -16
- package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
- package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
- package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
- package/executors/gateway/prod-runtime/upstream.js +0 -1
- package/executors/gateway/providers-prod.d.ts +0 -54
- package/executors/gateway/providers-prod.js +0 -1
- package/executors/gateway/registry-source.d.ts +0 -68
- package/executors/gateway/registry-source.js +0 -2
- package/executors/gateway/rollout-ops.d.ts +0 -53
- package/executors/gateway/rollout-ops.js +0 -2
- package/executors/gateway/ssrf-guard.d.ts +0 -96
- package/executors/gateway/ssrf-guard.js +0 -1
- package/executors/gateway/workspace-auth.d.ts +0 -100
- package/executors/gateway/workspace-auth.js +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/cluster",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.26.0",
|
|
4
4
|
"description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -29,43 +29,15 @@
|
|
|
29
29
|
"@nx/devkit": ">=20.0.0",
|
|
30
30
|
"@nx/webpack": ">=20.0.0",
|
|
31
31
|
"webpack": "^5.0.0",
|
|
32
|
-
"typescript": ">=5.0.0"
|
|
33
|
-
"ioredis": "^5.0.0",
|
|
34
|
-
"@opentelemetry/api": "^1.9.0",
|
|
35
|
-
"@opentelemetry/core": "^2.9.0",
|
|
36
|
-
"@opentelemetry/resources": "^2.9.0",
|
|
37
|
-
"@opentelemetry/sdk-trace-base": "^2.9.0",
|
|
38
|
-
"@opentelemetry/exporter-trace-otlp-http": "^0.220.0"
|
|
39
|
-
},
|
|
40
|
-
"peerDependenciesMeta": {
|
|
41
|
-
"ioredis": {
|
|
42
|
-
"optional": true
|
|
43
|
-
},
|
|
44
|
-
"@opentelemetry/api": {
|
|
45
|
-
"optional": true
|
|
46
|
-
},
|
|
47
|
-
"@opentelemetry/core": {
|
|
48
|
-
"optional": true
|
|
49
|
-
},
|
|
50
|
-
"@opentelemetry/resources": {
|
|
51
|
-
"optional": true
|
|
52
|
-
},
|
|
53
|
-
"@opentelemetry/sdk-trace-base": {
|
|
54
|
-
"optional": true
|
|
55
|
-
},
|
|
56
|
-
"@opentelemetry/exporter-trace-otlp-http": {
|
|
57
|
-
"optional": true
|
|
58
|
-
}
|
|
32
|
+
"typescript": ">=5.0.0"
|
|
59
33
|
},
|
|
60
34
|
"dependencies": {
|
|
61
|
-
"@lensmcp/core": "1.
|
|
62
|
-
"@lensmcp/node-instrumentation": "1.
|
|
63
|
-
"@lensmcp/nx-plugin": "1.
|
|
64
|
-
"
|
|
65
|
-
"@fastify/reply-from": "^12.6.2",
|
|
35
|
+
"@lensmcp/core": "1.26.0",
|
|
36
|
+
"@lensmcp/node-instrumentation": "1.26.0",
|
|
37
|
+
"@lensmcp/nx-plugin": "1.26.0",
|
|
38
|
+
"edgeward": "0.1.0",
|
|
66
39
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
|
67
40
|
"fork-ts-checker-webpack-plugin": "^9.0.0",
|
|
68
|
-
"glob": "^11.0.0",
|
|
69
41
|
"http-proxy": "^1.18.0",
|
|
70
42
|
"js-yaml": "^4.1.0",
|
|
71
43
|
"node-forge": "^1.3.1",
|
package/pod-memory.d.ts
CHANGED
|
@@ -13,7 +13,16 @@ export interface PodMemoryPolicy {
|
|
|
13
13
|
settleMs: number;
|
|
14
14
|
/** A retained verdict counts the shared classes (one heap walk each) only when live heap is at most this. */
|
|
15
15
|
countMaxBytes: number;
|
|
16
|
+
/** A request open this long is a stream: it no longer holds a collection back. */
|
|
17
|
+
streamMs: number;
|
|
18
|
+
/** The idle collection held back this long runs whatever is open — and from half of it, at the first moment no young request is. */
|
|
19
|
+
deferMaxMs: number;
|
|
20
|
+
/** A post-swap or retention collection waits for requests in flight at most this long. */
|
|
21
|
+
swapDeferMs: number;
|
|
16
22
|
}
|
|
23
|
+
export declare const IDLE_JITTER = 0.2;
|
|
24
|
+
/** One of the idle collection's two waits for one pod and one run, ±20%: it cannot fall in step with a client's poll of the same period. */
|
|
25
|
+
export declare function jittered(ms: number, random?: () => number): number;
|
|
17
26
|
/** Full GCs a closed generation must survive before it is called retained: one could have raced its last timer. */
|
|
18
27
|
export declare const RETAINED_MIN_GCS = 2;
|
|
19
28
|
/**
|
|
@@ -25,6 +34,8 @@ export declare const RETAINED_MIN_GCS = 2;
|
|
|
25
34
|
* - `LENSMCP_POD_GC_SETTLE_MS` — default `2000`.
|
|
26
35
|
* - `LENSMCP_POD_COUNT_MAX_MB` — default `64`: the live heap up to which a retained verdict counts the shared
|
|
27
36
|
* classes. Each count walks the heap, ~7 ms per MB, with the pod paused; `0` never counts.
|
|
37
|
+
* - `LENSMCP_POD_GC_STREAM_MS` — default `30000`; `LENSMCP_POD_GC_DEFER_MAX_MS` — default `600000`;
|
|
38
|
+
* `LENSMCP_POD_GC_SWAP_DEFER_MS` — default `10000`: how a collection waits for requests in flight.
|
|
28
39
|
*/
|
|
29
40
|
export declare function podMemoryPolicy(env?: NodeJS.ProcessEnv): PodMemoryPolicy;
|
|
30
41
|
/** What made the pod collect. `swap+<delay>` names a scheduled run by its delay from the swap. */
|
|
@@ -53,6 +64,8 @@ export interface PodMemoryReport {
|
|
|
53
64
|
baseline?: number;
|
|
54
65
|
/** How long the collection paused the pod. */
|
|
55
66
|
gcMs: number;
|
|
67
|
+
/** How long requests in flight held it back, when they did. */
|
|
68
|
+
deferredMs?: number;
|
|
56
69
|
/** The generation this pod's latest swap replaced. */
|
|
57
70
|
previousGen?: number;
|
|
58
71
|
/** Is it still in memory? `null` when there is none (no swap yet). */
|
|
@@ -235,8 +248,10 @@ export interface PodMemoryHost {
|
|
|
235
248
|
* How this pod runs a full GC — the devserver's announces it beside its socket and marks it for the loop tap
|
|
236
249
|
* (gc-notice.ts). `trigger`: which collection this is. Default `fullGc`.
|
|
237
250
|
*/
|
|
238
|
-
gc?(trigger: PodMemoryTrigger): boolean;
|
|
251
|
+
gc?(trigger: PodMemoryTrigger, deferredMs?: number): boolean;
|
|
239
252
|
now?: () => number;
|
|
253
|
+
/** The idle minimum's jitter source. Default `Math.random`. */
|
|
254
|
+
random?: () => number;
|
|
240
255
|
}
|
|
241
256
|
/** Drives the collections and the reports. One per pod. */
|
|
242
257
|
export interface PodMemoryMonitor {
|
|
@@ -249,8 +264,10 @@ export interface PodMemoryMonitor {
|
|
|
249
264
|
closed(gen: number, swaps: number, targets: GenerationTargets): void;
|
|
250
265
|
/** Request traffic, for the idle collection. */
|
|
251
266
|
activity(): void;
|
|
267
|
+
/** A request arrived: in flight until what this returns is called, at its response's close. */
|
|
268
|
+
request(): () => void;
|
|
252
269
|
/** Collect and report now. Serialised: concurrent callers share one queue. */
|
|
253
|
-
measure(trigger: PodMemoryTrigger): Promise<PodMemoryReport>;
|
|
270
|
+
measure(trigger: PodMemoryTrigger, deferredMs?: number): Promise<PodMemoryReport>;
|
|
254
271
|
/** For the recycle rule. */
|
|
255
272
|
oldestRetained(): ClosedGenerationView | undefined;
|
|
256
273
|
/** The pod is exiting. */
|
package/pod-memory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var O=Object.defineProperty;var d=(s,e)=>O(s,"name",{value:e,configurable:!0});var T=Object.defineProperty,i=d((s,e)=>T(s,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GenerationTracker=exports.LensmcpClosedGeneration=exports.RETAINED_MIN_GCS=void 0,exports.podMemoryPolicy=podMemoryPolicy,exports.fullGc=fullGc,exports.countLiveInstances=countLiveInstances,exports.createLiveObjectCounter=createLiveObjectCounter,exports.delayLabel=delayLabel,exports.createPodMemoryMonitor=createPodMemoryMonitor,exports.ageLabel=ageLabel,exports.describePodMemory=describePodMemory,exports.describeRetained=describeRetained,exports.describeReleased=describeReleased;const tslib_1=require("tslib"),node_async_hooks_1=require("node:async_hooks"),node_module_1=require("node:module"),v8=tslib_1.__importStar(require("node:v8")),vm=tslib_1.__importStar(require("node:vm"));exports.RETAINED_MIN_GCS=2;const numberFrom=i((s,e,t)=>{if(s===void 0||s.trim()==="")return e;const o=Number(s);return Number.isFinite(o)&&o>=t?o:e},"numberFrom");function podMemoryPolicy(s=process.env){const e=["0","false","no","off"].includes((s.LENSMCP_POD_GC??"").trim().toLowerCase()),t=(s.LENSMCP_POD_GC_SCHEDULE_MS??"").split(",").map(o=>Number(o.trim())).filter(o=>Number.isFinite(o)&&o>0).map(Math.floor).sort((o,a)=>o-a);return{enabled:!e,scheduleMs:t.length?t:[3e4,12e4,3e5],idleMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_IDLE_MS,6e4,0)),idleEveryMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_IDLE_EVERY_MS,3e5,0)),retainedAfterMs:Math.floor(numberFrom(s.LENSMCP_POD_RETAINED_AFTER_MS,3e5,0)),settleMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_SETTLE_MS,2e3,0)),countMaxBytes:Math.floor(numberFrom(s.LENSMCP_POD_COUNT_MAX_MB,64,0)*1024*1024)}}d(podMemoryPolicy,"podMemoryPolicy"),i(podMemoryPolicy,"podMemoryPolicy");let collector;function fullGc(){if(collector===void 0)try{v8.setFlagsFromString("--expose-gc");const s=vm.runInNewContext("gc");collector=typeof s=="function"?s:null}catch{collector=null}if(!collector)return!1;try{return collector(),!0}catch{return!1}}d(fullGc,"fullGc"),i(fullGc,"fullGc");function countLiveInstances(s){const e=v8.queryObjects;if(typeof e!="function"||typeof s!="function")return;const t=process.emitWarning;process.emitWarning=i(function(o,...a){const l=typeof a[0]=="string"?a[0]:a[0]?.type,n=typeof o=="string"?o:o?.message;if(!(l==="ExperimentalWarning"&&/queryObjects/.test(n??"")))return t.call(process,o,...a)},"quiet");try{const o=e(s,{format:"count"});return typeof o=="number"&&Number.isFinite(o)?o:void 0}catch{return}finally{process.emitWarning=t}}d(countLiveInstances,"countLiveInstances"),i(countLiveInstances,"countLiveInstances");const LEAK_CLASSES=[{name:"NestContainer",pkg:"@nestjs/core",pick:i(s=>s.NestContainer,"pick")},{name:"ZodObject",pkg:"zod",pick:i(s=>s.ZodObject,"pick")},{name:"DataSource",pkg:"typeorm",pick:i(s=>s.DataSource,"pick")},{name:"Redis",pkg:"ioredis",pick:i(s=>typeof s=="function"?s:s.default??s.Redis,"pick")},{name:"Worker",pkg:"bullmq",pick:i(s=>s.Worker,"pick")}];function createLiveObjectCounter(s,e=require.cache){let t;try{t=(0,node_module_1.createRequire)(s)}catch{t=void 0}const o=new Map,a=i(l=>{if(!t)return;let n=o.get(l.pkg);if(n===void 0){try{n=t.resolve(l.pkg)}catch{n=null}o.set(l.pkg,n)}if(!n)return;const p=e[n]?.exports;if(!(!p||typeof p!="object"&&typeof p!="function"))try{return l.pick(p)}catch{return}},"classOf");return{containers:i(()=>countLiveInstances(a(LEAK_CLASSES[0])),"containers"),all:i(()=>{const l={};for(const n of LEAK_CLASSES){const p=countLiveInstances(a(n));p!==void 0&&(l[n.name]=p)}return Object.keys(l).length?l:void 0},"all")}}d(createLiveObjectCounter,"createLiveObjectCounter"),i(createLiveObjectCounter,"createLiveObjectCounter");class LensmcpClosedGeneration{static{d(this,"LensmcpClosedGeneration")}static{i(this,"LensmcpClosedGeneration")}constructor(e,t){this.gen=e,this.refs={},this.label=`lensmcp closed generation ${e}`;for(const[o,a]of Object.entries(t))a&&(typeof a=="object"||typeof a=="function")&&(this.refs[o]=new WeakRef(a))}}exports.LensmcpClosedGeneration=LensmcpClosedGeneration;class GenerationTracker{static{d(this,"GenerationTracker")}static{i(this,"GenerationTracker")}constructor(e={}){this.opts=e,this.closed=new Map,this.freed=new Map,this.now=e.now??Date.now,this.registry=new FinalizationRegistry(t=>this.collected(t))}close(e,t,o){if(this.closed.has(e)||this.freed.has(e))return;const a=new LensmcpClosedGeneration(e,o),l=new Set(Object.keys(a.refs));if(l.size===0){this.markFreed(e);return}this.closed.set(e,{marker:a,closedAt:this.now(),swapsAtClose:t,gcs:0,alive:l});for(const[n,p]of Object.entries(a.refs)){const m=p.deref();m?this.registry.register(m,{gen:e,name:n}):l.delete(n)}l.size===0&&this.drop(e)}noteGc(){for(const e of this.closed.values())e.gcs+=1}isAlive(e){if(this.closed.has(e))return!0;if(this.freed.has(e))return!1}views(){return[...this.closed.entries()].map(([e,t])=>this.view(e,t))}dueForReport(e,t=this.now()){return this.views().filter(o=>o.reportedAt===void 0&&o.gcs>=exports.RETAINED_MIN_GCS&&t-o.closedAt>=e)}retainedCount(e,t=this.now()){return this.views().filter(o=>o.gcs>=exports.RETAINED_MIN_GCS&&t-o.closedAt>=e).length}markReported(e,t=this.now()){const o=this.closed.get(e);o&&(o.reportedAt=t)}oldestRetained(e,t=this.now()){return this.views().filter(o=>o.gcs>=exports.RETAINED_MIN_GCS&&t-o.closedAt>=e).sort((o,a)=>o.closedAt-a.closedAt)[0]}markers(){return[...this.closed.values()].map(e=>e.marker)}forgetAll(){const e=this.views().filter(t=>t.reportedAt!==void 0);for(const t of[...this.closed.keys()])this.drop(t);return e}collected(e){const t=this.closed.get(e.gen);if(!t||(t.alive.delete(e.name),t.alive.size>0))return;const o=this.view(e.gen,t);this.drop(e.gen);try{this.opts.onFreed?.(o,o.reportedAt!==void 0)}catch{}}drop(e){this.closed.delete(e),this.markFreed(e)}markFreed(e){this.freed.set(e,this.now()),this.freed.size>64&&this.freed.delete(this.freed.keys().next().value)}view(e,t){return{gen:e,closedAt:t.closedAt,swapsAtClose:t.swapsAtClose,gcs:t.gcs,alive:[...t.alive],...t.reportedAt!==void 0?{reportedAt:t.reportedAt}:{}}}}exports.GenerationTracker=GenerationTracker;const MB=1024*1024;function delayLabel(s){return s%6e4===0?`${s/6e4}m`:s%1e3===0?`${s/1e3}s`:`${s}ms`}d(delayLabel,"delayLabel"),i(delayLabel,"delayLabel");const turn=i(()=>new Promise(s=>setImmediate(s)),"turn");function createPodMemoryMonitor(s){const e=s.now??Date.now,t=s.policy,o=new GenerationTracker({now:e,onFreed:i((r,u)=>{u&&s.send({type:"pod-memory-released",released:{gen:r.gen,closedAt:r.closedAt,ageMs:e()-r.closedAt,reason:"collected"}})},"onFreed")});let a=Promise.resolve(),l=!1,n,p,m,w=0,A=!1,C=0;const S=new node_async_hooks_1.AsyncResource("lensmcp.pod-memory"),y=i((r,u)=>S.runInAsyncScope(()=>{const c=setTimeout(r,Math.max(0,u));return c.unref?.(),c}),"unrefTimer");function E(){return!n||n.previousGen===void 0?null:n.previousClosed()?o.isAlive(n.previousGen)!==!1:!0}d(E,"E"),i(E,"previousAlive");async function G(r){const u=process.memoryUsage().heapUsed,c=process.hrtime.bigint();s.gc?s.gc(r):fullGc();const f=Number(process.hrtime.bigint()-c)/1e6;o.noteGc(),await turn(),await turn();let h=s.containers?.();const v=process.memoryUsage(),g=v8.getHeapStatistics(),L=v8.getHeapSpaceStatistics().find(P=>P.space_name==="new_space"),$=s.state(),I=o.views(),R=e();return h!==void 0&&h<0&&(h=void 0),{trigger:r,at:R,gen:$.gen,swaps:$.swaps,live:v.heapUsed,used:u,reserved:v.heapTotal,rss:v.rss,external:v.external,youngGen:L?.space_size??0,limit:g.heap_size_limit,...$.baseline!==void 0?{baseline:$.baseline}:{},gcMs:Math.round(f),...n?.previousGen!==void 0?{previousGen:n.previousGen}:{},previousAlive:E(),closedAlive:I.length,retained:o.retainedCount(t.retainedAfterMs,R),...h!==void 0?{containers:h}:{},sourceMaps:process.sourceMapsEnabled===!0}}d(G,"G"),i(G,"collect");function N(r){for(const c of o.dueForReport(t.retainedAfterMs,r.at)){o.markReported(c.gen,r.at);const f=r.live<=t.countMaxBytes?s.counter?.all():void 0;s.send({type:"pod-memory-retained",retained:{gen:c.gen,closedAt:c.closedAt,ageMs:r.at-c.closedAt,swapsSinceClose:Math.max(0,r.swaps-c.swapsAtClose),gcs:c.gcs,alive:c.alive,...f?{counts:f}:{},live:r.live}})}const u=o.oldestRetained(t.retainedAfterMs,r.at);if(u)try{s.onRetained?.(u)}catch{}n&&!n.done&&r.previousAlive===!1&&_(),k()}d(N,"N"),i(N,"afterCollect");function M(r){const u=S.runInAsyncScope(()=>a.then(async()=>{const c=await G(r);return A=!1,l||(s.send({type:"pod-memory",report:c}),N(c)),c}));return a=u.catch(()=>{}),u}d(M,"v"),i(M,"measure");function b(r){if(!l){if(s.state().busy){y(()=>b(r),1e3);return}M(r).catch(()=>{})}}d(b,"b"),i(b,"measureWhenFree");function _(){if(n){n.done=!0;for(const r of n.timers)clearTimeout(r);n.timers=[]}}d(_,"$"),i(_,"finishSchedule");function k(){if(p&&clearTimeout(p),p=void 0,l||!t.enabled)return;const r=o.views().filter(f=>f.reportedAt===void 0);if(r.length===0)return;const u=e(),c=Math.min(...r.map(f=>Math.max(f.closedAt+t.retainedAfterMs,u+1e3)));p=y(()=>{p=void 0,b("retention-check")},c-u)}d(k,"S"),i(k,"armRetentionCheck");function x(){if(l||!t.enabled||t.idleMs<=0||m)return;const r=Math.max(t.idleMs-(e()-w),C+t.idleEveryMs-e(),250);m=y(()=>{if(m=void 0,!!A){if(e()-w<t.idleMs||e()-C<t.idleEveryMs||s.state().busy){x();return}C=e(),b("idle")}},r)}return d(x,"x"),i(x,"armIdle"),{tracker:o,booted:i(()=>M("boot"),"booted"),swapped(r,u){if(l||(_(),w=e(),A=!0,!t.enabled))return;const c={...r!==void 0?{previousGen:r}:{},previousClosed:u,timers:[],done:!1};n=c;const f=e(),h=t.scheduleMs[0]??Number.POSITIVE_INFINITY,v=i(()=>{if(c.done||n!==c)return;const g=s.state();if(!g.busy&&u()&&e()-g.lastBusyAt>=t.settleMs){M("swap-settled").catch(()=>{});return}e()-f+500<h&&c.timers.push(y(v,500))},"settledCheck");c.timers.push(y(v,Math.min(t.settleMs,500)));for(const g of t.scheduleMs)c.timers.push(y(()=>{c.done||n!==c||b(`swap+${delayLabel(g)}`)},g))},closed(r,u,c){o.close(r,u,c),k()},activity(){w=e(),A=!0,x()},measure:M,oldestRetained:i(()=>o.oldestRetained(t.retainedAfterMs),"oldestRetained"),stop(){l=!0,_(),p&&clearTimeout(p),m&&clearTimeout(m)}}}d(createPodMemoryMonitor,"createPodMemoryMonitor"),i(createPodMemoryMonitor,"createPodMemoryMonitor");const mbOf=i(s=>s===void 0?"?":`${Math.round(s/MB)} MB`,"mbOf");function ageLabel(s){return s<9e4?`${Math.max(0,Math.round(s/1e3))}s`:`${Math.round(s/6e4)} min`}d(ageLabel,"ageLabel"),i(ageLabel,"ageLabel");function describePodMemory(s,e){const t=e.trigger==="boot"?`${s} memory at boot: ${mbOf(e.live)} live after a full GC \u2014 the baseline later readings compare with`:`${s} memory (${e.trigger}): ${mbOf(e.live)} live after a full GC`+(e.used-e.live>=MB?` (${mbOf(e.used)} before it)`:"")+(e.baseline?`, ${(e.live/e.baseline).toFixed(1)}\xD7 its ${mbOf(e.baseline)} boot baseline`:""),o=[`${mbOf(e.reserved)} reserved`,`rss ${mbOf(e.rss)}`,`generation ${e.gen}, ${e.swaps} swap${e.swaps===1?"":"s"}`,`GC ${e.gcMs} ms`];return e.previousAlive===!1?o.push(`generation ${e.previousGen} freed`):e.previousAlive===!0&&o.push(`generation ${e.previousGen} still in memory`),e.containers!==void 0&&o.push(`${e.containers} Nest container${e.containers===1?"":"s"}`),e.retained>0&&o.push(`${e.retained} closed generation${e.retained===1?"":"s"} RETAINED`),`${t} \xB7 ${o.join(" \xB7 ")}`}d(describePodMemory,"describePodMemory"),i(describePodMemory,"describePodMemory");function describeRetained(s,e,t){const o=t.counts&&Object.keys(t.counts).length?` Live now: ${Object.entries(t.counts).map(([a,l])=>`${a} ${l}`).join(", ")}.`:"";return`${s} ${e}: generation ${t.gen} still in memory ${ageLabel(t.ageMs)} after its app was closed (${t.swapsSinceClose} swap${t.swapsSinceClose===1?"":"s"} since, ${t.gcs} full GCs; still alive: ${t.alive.join(", ")}) \u2014 something still points into it.${o} See what with \`lensmcp mem ${e} --snapshot --analyze\`.`}d(describeRetained,"describeRetained"),i(describeRetained,"describeRetained");function describeReleased(s,e,t){return t.reason==="pod-exited"?`${s} ${e}: generation ${t.gen} went with its pod`:`${s} ${e}: generation ${t.gen} was collected after all, ${ageLabel(t.ageMs)} after its app was closed`}d(describeReleased,"describeReleased"),i(describeReleased,"describeReleased");
|
|
1
|
+
"use strict";var K=Object.defineProperty;var u=(s,e)=>K(s,"name",{value:e,configurable:!0});var V=Object.defineProperty,o=u((s,e)=>V(s,"name",{value:e,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GenerationTracker=exports.LensmcpClosedGeneration=exports.RETAINED_MIN_GCS=exports.IDLE_JITTER=void 0,exports.jittered=jittered,exports.podMemoryPolicy=podMemoryPolicy,exports.fullGc=fullGc,exports.countLiveInstances=countLiveInstances,exports.createLiveObjectCounter=createLiveObjectCounter,exports.delayLabel=delayLabel,exports.createPodMemoryMonitor=createPodMemoryMonitor,exports.ageLabel=ageLabel,exports.describePodMemory=describePodMemory,exports.describeRetained=describeRetained,exports.describeReleased=describeReleased;const tslib_1=require("tslib"),node_async_hooks_1=require("node:async_hooks"),node_module_1=require("node:module"),v8=tslib_1.__importStar(require("node:v8")),vm=tslib_1.__importStar(require("node:vm")),ARRIVAL_GUARD_MS=1e3,RECHECK_MS=1e3;exports.IDLE_JITTER=.2;function jittered(s,e=Math.random){return Math.round(s*(1-exports.IDLE_JITTER+2*exports.IDLE_JITTER*Math.min(1,Math.max(0,e()))))}u(jittered,"jittered"),o(jittered,"jittered"),exports.RETAINED_MIN_GCS=2;const numberFrom=o((s,e,t)=>{if(s===void 0||s.trim()==="")return e;const r=Number(s);return Number.isFinite(r)&&r>=t?r:e},"numberFrom");function podMemoryPolicy(s=process.env){const e=["0","false","no","off"].includes((s.LENSMCP_POD_GC??"").trim().toLowerCase()),t=(s.LENSMCP_POD_GC_SCHEDULE_MS??"").split(",").map(r=>Number(r.trim())).filter(r=>Number.isFinite(r)&&r>0).map(Math.floor).sort((r,d)=>r-d);return{enabled:!e,scheduleMs:t.length?t:[3e4,12e4,3e5],idleMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_IDLE_MS,6e4,0)),idleEveryMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_IDLE_EVERY_MS,3e5,0)),retainedAfterMs:Math.floor(numberFrom(s.LENSMCP_POD_RETAINED_AFTER_MS,3e5,0)),settleMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_SETTLE_MS,2e3,0)),countMaxBytes:Math.floor(numberFrom(s.LENSMCP_POD_COUNT_MAX_MB,64,0)*1024*1024),streamMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_STREAM_MS,3e4,0)),deferMaxMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_DEFER_MAX_MS,6e5,0)),swapDeferMs:Math.floor(numberFrom(s.LENSMCP_POD_GC_SWAP_DEFER_MS,1e4,0))}}u(podMemoryPolicy,"podMemoryPolicy"),o(podMemoryPolicy,"podMemoryPolicy");let collector;function fullGc(){if(collector===void 0)try{v8.setFlagsFromString("--expose-gc");const s=vm.runInNewContext("gc");collector=typeof s=="function"?s:null}catch{collector=null}if(!collector)return!1;try{return collector(),!0}catch{return!1}}u(fullGc,"fullGc"),o(fullGc,"fullGc");function countLiveInstances(s){const e=v8.queryObjects;if(typeof e!="function"||typeof s!="function")return;const t=process.emitWarning;process.emitWarning=o(function(r,...d){const l=typeof d[0]=="string"?d[0]:d[0]?.type,c=typeof r=="string"?r:r?.message;if(!(l==="ExperimentalWarning"&&/queryObjects/.test(c??"")))return t.call(process,r,...d)},"quiet");try{const r=e(s,{format:"count"});return typeof r=="number"&&Number.isFinite(r)?r:void 0}catch{return}finally{process.emitWarning=t}}u(countLiveInstances,"countLiveInstances"),o(countLiveInstances,"countLiveInstances");const LEAK_CLASSES=[{name:"NestContainer",pkg:"@nestjs/core",pick:o(s=>s.NestContainer,"pick")},{name:"ZodObject",pkg:"zod",pick:o(s=>s.ZodObject,"pick")},{name:"DataSource",pkg:"typeorm",pick:o(s=>s.DataSource,"pick")},{name:"Redis",pkg:"ioredis",pick:o(s=>typeof s=="function"?s:s.default??s.Redis,"pick")},{name:"Worker",pkg:"bullmq",pick:o(s=>s.Worker,"pick")}];function createLiveObjectCounter(s,e=require.cache){let t;try{t=(0,node_module_1.createRequire)(s)}catch{t=void 0}const r=new Map,d=o(l=>{if(!t)return;let c=r.get(l.pkg);if(c===void 0){try{c=t.resolve(l.pkg)}catch{c=null}r.set(l.pkg,c)}if(!c)return;const f=e[c]?.exports;if(!(!f||typeof f!="object"&&typeof f!="function"))try{return l.pick(f)}catch{return}},"classOf");return{containers:o(()=>countLiveInstances(d(LEAK_CLASSES[0])),"containers"),all:o(()=>{const l={};for(const c of LEAK_CLASSES){const f=countLiveInstances(d(c));f!==void 0&&(l[c.name]=f)}return Object.keys(l).length?l:void 0},"all")}}u(createLiveObjectCounter,"createLiveObjectCounter"),o(createLiveObjectCounter,"createLiveObjectCounter");class LensmcpClosedGeneration{static{u(this,"LensmcpClosedGeneration")}static{o(this,"LensmcpClosedGeneration")}constructor(e,t){this.gen=e,this.refs={},this.label=`lensmcp closed generation ${e}`;for(const[r,d]of Object.entries(t))d&&(typeof d=="object"||typeof d=="function")&&(this.refs[r]=new WeakRef(d))}}exports.LensmcpClosedGeneration=LensmcpClosedGeneration;class GenerationTracker{static{u(this,"GenerationTracker")}static{o(this,"GenerationTracker")}constructor(e={}){this.opts=e,this.closed=new Map,this.freed=new Map,this.now=e.now??Date.now,this.registry=new FinalizationRegistry(t=>this.collected(t))}close(e,t,r){if(this.closed.has(e)||this.freed.has(e))return;const d=new LensmcpClosedGeneration(e,r),l=new Set(Object.keys(d.refs));if(l.size===0){this.markFreed(e);return}this.closed.set(e,{marker:d,closedAt:this.now(),swapsAtClose:t,gcs:0,alive:l});for(const[c,f]of Object.entries(d.refs)){const h=f.deref();h?this.registry.register(h,{gen:e,name:c}):l.delete(c)}l.size===0&&this.drop(e)}noteGc(){for(const e of this.closed.values())e.gcs+=1}isAlive(e){if(this.closed.has(e))return!0;if(this.freed.has(e))return!1}views(){return[...this.closed.entries()].map(([e,t])=>this.view(e,t))}dueForReport(e,t=this.now()){return this.views().filter(r=>r.reportedAt===void 0&&r.gcs>=exports.RETAINED_MIN_GCS&&t-r.closedAt>=e)}retainedCount(e,t=this.now()){return this.views().filter(r=>r.gcs>=exports.RETAINED_MIN_GCS&&t-r.closedAt>=e).length}markReported(e,t=this.now()){const r=this.closed.get(e);r&&(r.reportedAt=t)}oldestRetained(e,t=this.now()){return this.views().filter(r=>r.gcs>=exports.RETAINED_MIN_GCS&&t-r.closedAt>=e).sort((r,d)=>r.closedAt-d.closedAt)[0]}markers(){return[...this.closed.values()].map(e=>e.marker)}forgetAll(){const e=this.views().filter(t=>t.reportedAt!==void 0);for(const t of[...this.closed.keys()])this.drop(t);return e}collected(e){const t=this.closed.get(e.gen);if(!t||(t.alive.delete(e.name),t.alive.size>0))return;const r=this.view(e.gen,t);this.drop(e.gen);try{this.opts.onFreed?.(r,r.reportedAt!==void 0)}catch{}}drop(e){this.closed.delete(e),this.markFreed(e)}markFreed(e){this.freed.set(e,this.now()),this.freed.size>64&&this.freed.delete(this.freed.keys().next().value)}view(e,t){return{gen:e,closedAt:t.closedAt,swapsAtClose:t.swapsAtClose,gcs:t.gcs,alive:[...t.alive],...t.reportedAt!==void 0?{reportedAt:t.reportedAt}:{}}}}exports.GenerationTracker=GenerationTracker;const MB=1024*1024;function delayLabel(s){return s%6e4===0?`${s/6e4}m`:s%1e3===0?`${s/1e3}s`:`${s}ms`}u(delayLabel,"delayLabel"),o(delayLabel,"delayLabel");const turn=o(()=>new Promise(s=>setImmediate(s)),"turn");function createPodMemoryMonitor(s){const e=s.now??Date.now,t=s.policy,r=new GenerationTracker({now:e,onFreed:o((i,a)=>{a&&s.send({type:"pod-memory-released",released:{gen:i.gen,closedAt:i.closedAt,ageMs:e()-i.closedAt,reason:"collected"}})},"onFreed")});let d=Promise.resolve(),l=!1,c,f,h,A=0,C=!1,D=0;const E=s.random??Math.random;let O=jittered(t.idleEveryMs,E),x=jittered(t.idleMs,E);const G=new Set;let F=Number.NEGATIVE_INFINITY,I,y;const N=o(()=>{const i=e();for(const a of G)if(i-a.at<t.streamMs)return!0;return!1},"young"),$=o(()=>N()||e()-F<ARRIVAL_GUARD_MS,"inFlight"),S=o(()=>{A=e(),C||(I=A),C=!0},"touched"),j=new node_async_hooks_1.AsyncResource("lensmcp.pod-memory"),g=o((i,a)=>j.runInAsyncScope(()=>{const n=setTimeout(i,Math.max(0,a));return n.unref?.(),n}),"unrefTimer");function q(){return!c||c.previousGen===void 0?null:c.previousClosed()?r.isAlive(c.previousGen)!==!1:!0}u(q,"q"),o(q,"previousAlive");async function z(i,a){const n=process.memoryUsage().heapUsed,p=process.hrtime.bigint();s.gc?s.gc(i,a):fullGc();const v=Number(process.hrtime.bigint()-p)/1e6;r.noteGc(),await turn(),await turn();let m=s.containers?.();const M=process.memoryUsage(),U=v8.getHeapStatistics(),H=v8.getHeapSpaceStatistics().find(Y=>Y.space_name==="new_space"),R=s.state(),J=r.views(),B=e();return m!==void 0&&m<0&&(m=void 0),{trigger:i,at:B,gen:R.gen,swaps:R.swaps,live:M.heapUsed,used:n,reserved:M.heapTotal,rss:M.rss,external:M.external,youngGen:H?.space_size??0,limit:U.heap_size_limit,...R.baseline!==void 0?{baseline:R.baseline}:{},gcMs:Math.round(v),...a>0?{deferredMs:Math.round(a)}:{},...c?.previousGen!==void 0?{previousGen:c.previousGen}:{},previousAlive:q(),closedAlive:J.length,retained:r.retainedCount(t.retainedAfterMs,B),...m!==void 0?{containers:m}:{},sourceMaps:process.sourceMapsEnabled===!0}}u(z,"z"),o(z,"collect");function W(i){for(const n of r.dueForReport(t.retainedAfterMs,i.at)){r.markReported(n.gen,i.at);const p=i.live<=t.countMaxBytes?s.counter?.all():void 0;s.send({type:"pod-memory-retained",retained:{gen:n.gen,closedAt:n.closedAt,ageMs:i.at-n.closedAt,swapsSinceClose:Math.max(0,i.swaps-n.swapsAtClose),gcs:n.gcs,alive:n.alive,...p?{counts:p}:{},live:i.live}})}const a=r.oldestRetained(t.retainedAfterMs,i.at);if(a)try{s.onRetained?.(a)}catch{}c&&!c.done&&i.previousAlive===!1&&k(),L()}u(W,"W"),o(W,"afterCollect");function _(i,a=0){const n=j.runInAsyncScope(()=>d.then(async()=>{const p=await z(i,a);return C=!1,I=void 0,y=void 0,l||(s.send({type:"pod-memory",report:p}),W(p)),p}));return d=n.catch(()=>{}),n}u(_,"x"),o(_,"measure");function b(i,a=()=>!0,n){if(l||!a())return;const p=e(),v=n===void 0?0:p-n,m=!s.state().busy&&v<t.swapDeferMs&&$();if(s.state().busy||m){g(()=>b(i,a,m?n??p:n),RECHECK_MS);return}_(i,v).catch(()=>{})}u(b,"C"),o(b,"measureWhenFree");function k(){if(c){c.done=!0;for(const i of c.timers)clearTimeout(i);c.timers=[]}}u(k,"R"),o(k,"finishSchedule");function L(){if(f&&clearTimeout(f),f=void 0,l||!t.enabled)return;const i=r.views().filter(p=>p.reportedAt===void 0);if(i.length===0)return;const a=e(),n=Math.min(...i.map(p=>Math.max(p.closedAt+t.retainedAfterMs,a+1e3)));f=g(()=>{f=void 0,b("retention-check")},n-a)}u(L,"O"),o(L,"armRetentionCheck");const T=o(()=>Math.max((I??e())+x,D+O),"idleFrom");function w(){if(l||!t.enabled||t.idleMs<=0||h)return;const i=e(),a=i-T(),n=a<0?-a:a>=t.deferMaxMs/2?Math.min(RECHECK_MS,t.deferMaxMs-a):Math.min(Math.max(x-(i-A),$()?RECHECK_MS:0),t.deferMaxMs/2-a);h=g(P,Math.max(n,250))}u(w,"S"),o(w,"armIdle");function P(){if(h=void 0,l||!C)return;const i=e(),a=i-T(),n=i-A>=x,p=a>=t.deferMaxMs||(a>=t.deferMaxMs/2?!N():n&&!$());if(a<0||s.state().busy||!p){a>=0&&y===void 0&&$()&&(y=i),w();return}const v=a>=t.deferMaxMs/2?a:y===void 0?0:i-y;D=i,O=jittered(t.idleEveryMs,E),x=jittered(t.idleMs,E),_("idle",v).catch(()=>{})}return u(P,"F"),o(P,"idleCheck"),{tracker:r,booted:o(()=>_("boot"),"booted"),swapped(i,a){if(l||(k(),S(),!t.enabled))return;const n={...i!==void 0?{previousGen:i}:{},previousClosed:a,timers:[],done:!1};c=n;const p=e(),v=t.scheduleMs[0]??Number.POSITIVE_INFINITY,m=o(()=>{if(n.done||c!==n)return;const M=s.state();if(!M.busy&&a()&&e()-M.lastBusyAt>=t.settleMs){b("swap-settled",()=>!n.done&&c===n);return}e()-p+500<v&&n.timers.push(g(m,500))},"settledCheck");n.timers.push(g(m,Math.min(t.settleMs,500)));for(const M of t.scheduleMs)n.timers.push(g(()=>{b(`swap+${delayLabel(M)}`,()=>!n.done&&c===n)},M))},closed(i,a,n){r.close(i,a,n),L()},activity(){S(),w()},request(){const i={at:e()};return G.add(i),F=i.at,S(),w(),()=>{G.delete(i)&&(S(),h&&!l&&e()-T()>=t.deferMaxMs/2&&!N()?(clearTimeout(h),P()):w())}},measure:_,oldestRetained:o(()=>r.oldestRetained(t.retainedAfterMs),"oldestRetained"),stop(){l=!0,k(),f&&clearTimeout(f),h&&clearTimeout(h)}}}u(createPodMemoryMonitor,"createPodMemoryMonitor"),o(createPodMemoryMonitor,"createPodMemoryMonitor");const mbOf=o(s=>s===void 0?"?":`${Math.round(s/MB)} MB`,"mbOf");function ageLabel(s){return s<9e4?`${Math.max(0,Math.round(s/1e3))}s`:`${Math.round(s/6e4)} min`}u(ageLabel,"ageLabel"),o(ageLabel,"ageLabel");function describePodMemory(s,e){const t=e.trigger==="boot"?`${s} memory at boot: ${mbOf(e.live)} live after a full GC \u2014 the baseline later readings compare with`:`${s} memory (${e.trigger}): ${mbOf(e.live)} live after a full GC`+(e.used-e.live>=MB?` (${mbOf(e.used)} before it)`:"")+(e.baseline?`, ${(e.live/e.baseline).toFixed(1)}\xD7 its ${mbOf(e.baseline)} boot baseline`:""),r=[`${mbOf(e.reserved)} reserved`,`rss ${mbOf(e.rss)}`,`generation ${e.gen}, ${e.swaps} swap${e.swaps===1?"":"s"}`,`GC ${e.gcMs} ms`];return e.previousAlive===!1?r.push(`generation ${e.previousGen} freed`):e.previousAlive===!0&&r.push(`generation ${e.previousGen} still in memory`),e.containers!==void 0&&r.push(`${e.containers} Nest container${e.containers===1?"":"s"}`),e.retained>0&&r.push(`${e.retained} closed generation${e.retained===1?"":"s"} RETAINED`),e.deferredMs&&r.push(`held back ${ageLabel(e.deferredMs)} by requests in flight`),`${t} \xB7 ${r.join(" \xB7 ")}`}u(describePodMemory,"describePodMemory"),o(describePodMemory,"describePodMemory");function describeRetained(s,e,t){const r=t.counts&&Object.keys(t.counts).length?` Live now: ${Object.entries(t.counts).map(([d,l])=>`${d} ${l}`).join(", ")}.`:"";return`${s} ${e}: generation ${t.gen} still in memory ${ageLabel(t.ageMs)} after its app was closed (${t.swapsSinceClose} swap${t.swapsSinceClose===1?"":"s"} since, ${t.gcs} full GCs; still alive: ${t.alive.join(", ")}) \u2014 something still points into it.${r} See what with \`lensmcp mem ${e} --snapshot --analyze\`.`}u(describeRetained,"describeRetained"),o(describeRetained,"describeRetained");function describeReleased(s,e,t){return t.reason==="pod-exited"?`${s} ${e}: generation ${t.gen} went with its pod`:`${s} ${e}: generation ${t.gen} was collected after all, ${ageLabel(t.ageMs)} after its app was closed`}u(describeReleased,"describeReleased"),o(describeReleased,"describeReleased");
|
package/tsgo-check-plugin.d.ts
CHANGED
|
@@ -24,8 +24,9 @@
|
|
|
24
24
|
* re-checked all of it once per service: 1,054 checks in 12 hours, up to 5.9GB each. So a check keeps what it learnt
|
|
25
25
|
* in a build-info file beside its shim (`tmp/lensmcp-tsgo/<app>.tsbuildinfo`, `--incremental --tsBuildInfoFile`): the
|
|
26
26
|
* next one re-checks only the files a change can affect, and reports the errors of the rest from that file. Still
|
|
27
|
-
* nothing is resident between saves — the knowledge is on disk. A run that gave no verdict (killed at its timeout
|
|
28
|
-
* checker failing) deletes the file, so a bad one is never
|
|
27
|
+
* nothing is resident between saves — the knowledge is on disk. A run that gave no verdict (killed at its timeout or from
|
|
28
|
+
* outside, a position-less program error such as TS18003, the checker failing) deletes the file, so a bad one is never
|
|
29
|
+
* read twice. `LENSMCP_TSGO_INCREMENTAL=0` checks cold.
|
|
29
30
|
* And a check's turn waits for memory: the queue holds it while the machine has little free, and it says so
|
|
30
31
|
* (`[tsgo] <app>: check held …`, and a `phase: 'held'` event the lens shows in `service_state`).
|
|
31
32
|
*
|
package/tsgo-check-plugin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`&&(
|
|
1
|
+
"use strict";var v=Object.defineProperty;var l=(e,t)=>v(e,"name",{value:t,configurable:!0});var y=Object.defineProperty,c=l((e,t)=>y(e,"name",{value:t,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=void 0,exports.checkerMaxProcs=checkerMaxProcs,exports.tsgoIncremental=tsgoIncremental,exports.tsgoBuildInfoPath=tsgoBuildInfoPath,exports.tsgoCheckArgs=tsgoCheckArgs,exports.typecheckMode=typecheckMode,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable,exports.effectivePaths=effectivePaths,exports.tsconfigChain=tsconfigChain,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus"),typecheck_queue_1=require("./typecheck-queue"),DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_PROCS=4;function checkerMaxProcs(e=process.env){const t=Number(e.LENSMCP_TYPECHECK_GOMAXPROCS);return Number.isInteger(t)&&t>=1?t:DEFAULT_MAX_PROCS}l(checkerMaxProcs,"checkerMaxProcs"),c(checkerMaxProcs,"checkerMaxProcs");function tsgoIncremental(e=process.env){const t=(e.LENSMCP_TSGO_INCREMENTAL??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off"||t==="no")}l(tsgoIncremental,"tsgoIncremental"),c(tsgoIncremental,"tsgoIncremental");function tsgoBuildInfoPath(e,t){return path.join(t,"tmp","lensmcp-tsgo",`${e}.tsbuildinfo`)}l(tsgoBuildInfoPath,"tsgoBuildInfoPath"),c(tsgoBuildInfoPath,"tsgoBuildInfoPath");function tsgoCheckArgs(e,t){return["--noEmit","--pretty","false",...t?["--incremental","--tsBuildInfoFile",t]:[],"-p",e]}l(tsgoCheckArgs,"tsgoCheckArgs"),c(tsgoCheckArgs,"tsgoCheckArgs");const livePlugins=new Set;let exitHooked=!1;function stopWithTheProcess(e){livePlugins.add(e),!exitHooked&&(exitHooked=!0,process.once("exit",()=>{for(const t of livePlugins)t.dispose()}))}l(stopWithTheProcess,"stopWithTheProcess"),c(stopWithTheProcess,"stopWithTheProcess");function typecheckMode(e=process.env){const t=e.LENSMCP_TYPECHECK;return t===void 0||t===""||t==="tsgo"?"tsgo":t==="off"?"off":"tsc"}l(typecheckMode,"typecheckMode"),c(typecheckMode,"typecheckMode"),exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(e){return e==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}l(shimNames,"shimNames"),c(shimNames,"shimNames");function isExecutableFile(e,t){try{if(!fs.statSync(e).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(e,fs.constants.X_OK),!0}catch{return!1}}l(isExecutableFile,"isExecutableFile"),c(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let e=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const o=path.join(e,"package.json");if(fs.existsSync(o))try{const{name:s}=JSON.parse(fs.readFileSync(o,"utf8"));if(s===exports.TSGO_PACKAGE)return e}catch{}const r=path.dirname(e);if(r===e)break;e=r}}catch{}return null}l(resolveTsgoPackageDir,"resolveTsgoPackageDir"),c(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(e){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(e,"package.json"),"utf8")),o=typeof t=="string"?t:t?.tsgo;return o?path.join(e,o):null}catch{return null}}l(packageDeclaredBin,"packageDeclaredBin"),c(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(e,t){const o=path.resolve(e,"..","..",".bin"),r=shimNames(t).map(i=>path.join(o,i)),s=t==="win32"?null:packageDeclaredBin(e);return s?[s,...r]:r}l(ownBinCandidates,"ownBinCandidates"),c(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(e,t,o={}){const r=o.platform??process.platform,s=o.isExecutable??(n=>isExecutableFile(n,r));if(t)return s(t)?t:null;for(const n of shimNames(r)){const a=path.join(e,"node_modules",".bin",n);if(s(a))return a}const i=(o.ownPackageDir??resolveTsgoPackageDir)();return i?ownBinCandidates(i,r).find(s)??null:null}l(resolveTsgoBin,"resolveTsgoBin"),c(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(e){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:e.workspaceRoot,project:e.appName,tool:"tsgo",tsConfig:e.tsConfig,output:"",durationMs:0,toolError:e.detail,...e.eventFile?{eventFile:e.eventFile}:{}})}catch{}}l(reportTsgoUnavailable,"reportTsgoUnavailable"),c(reportTsgoUnavailable,"reportTsgoUnavailable");function parseJsonc(e){let t="",o=!1,r=!1,s=!1;for(let i=0;i<e.length;i++){const n=e[i],a=e[i+1];if(r){n===`
|
|
2
|
+
`&&(r=!1,t+=n);continue}if(s){n==="*"&&a==="/"&&(s=!1,i++);continue}if(o){t+=n,n==="\\"?(t+=a??"",i++):n==='"'&&(o=!1);continue}if(n==='"'){o=!0,t+=n;continue}if(n==="/"&&a==="/"){r=!0,i++;continue}if(n==="/"&&a==="*"){s=!0,i++;continue}t+=n}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}l(parseJsonc,"parseJsonc"),c(parseJsonc,"parseJsonc");function resolveExtends(e,t){if(!e.startsWith(".")&&!path.isAbsolute(e))return null;const o=path.isAbsolute(e)?e:path.resolve(t,e);for(const r of[o,`${o}.json`,path.join(o,"tsconfig.json")])try{if(fs.statSync(r).isFile())return r}catch{}return null}l(resolveExtends,"resolveExtends"),c(resolveExtends,"resolveExtends");function effectivePaths(e,t=new Set){if(t.has(e))return null;t.add(e);let o;try{o=fs.readFileSync(e,"utf8")}catch{return null}const r=parseJsonc(o);if(!r)return null;const s=path.dirname(e),i=r.compilerOptions??{},n=Array.isArray(r.extends)?r.extends.filter(p=>typeof p=="string"):typeof r.extends=="string"?[r.extends]:[],a=c(()=>{for(const p of[...n].reverse()){const d=resolveExtends(p,s);if(!d)continue;const g=effectivePaths(d,t);if(g)return g}return null},"inherited"),u=i.paths,h=typeof i.baseUrl=="string"?path.resolve(s,i.baseUrl):void 0;if(!u){const p=a();return p?{paths:p.paths,anchorDir:h??p.anchorDir}:null}return{paths:u,anchorDir:h??a()?.anchorDir??s}}l(effectivePaths,"effectivePaths"),c(effectivePaths,"effectivePaths");function tsconfigChain(e){const t=[],o=c(r=>{if(t.includes(r))return;t.push(r);let s;try{s=parseJsonc(fs.readFileSync(r,"utf8"))}catch{return}const i=s?.extends,n=Array.isArray(i)?i.filter(a=>typeof a=="string"):typeof i=="string"?[i]:[];for(const a of n){const u=resolveExtends(a,path.dirname(r));u&&!u.split(path.sep).includes("node_modules")&&o(u)}},"visit");return o(path.resolve(e)),t}l(tsconfigChain,"tsconfigChain"),c(tsconfigChain,"tsconfigChain");function writeShimTsconfig(e,t,o){const r=path.join(o,"tmp","lensmcp-tsgo");fs.mkdirSync(r,{recursive:!0});const s=path.join(r,`${e}.tsconfig.json`),i=effectivePaths(t),n=i?Object.fromEntries(Object.entries(i.paths).map(([h,p])=>[h,(Array.isArray(p)?p:[]).map(d=>path.isAbsolute(d)?d:path.resolve(i.anchorDir,d))])):void 0,a=JSON.stringify({extends:t,compilerOptions:{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null,...n&&Object.keys(n).length?{paths:n}:{}}},null,2);let u;try{u=fs.readFileSync(s,"utf8")}catch{}return u!==a&&fs.writeFileSync(s,a),s}l(writeShimTsconfig,"writeShimTsconfig"),c(writeShimTsconfig,"writeShimTsconfig");class TsgoCheckPlugin{static{l(this,"TsgoCheckPlugin")}static{c(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.phase="idle",this.dirty=!1,this.ticket=null,this.inflight=null,this.askedAt=0,this.shimPath=null,this.disabled=!1,this.disposed=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn,this.queue=t.queue??(0,typecheck_queue_1.machineTypecheckQueue)(),this.buildInfo=t.incremental??tsgoIncremental()?tsgoBuildInfoPath(t.appName,t.workspaceRoot):void 0}apply(t){t.hooks.done.tap("TsgoCheckPlugin",o=>{o.hasErrors()||this.schedule()}),t.hooks.shutdown?.tap?.("TsgoCheckPlugin",()=>this.dispose()),t.hooks.watchClose?.tap?.("TsgoCheckPlugin",()=>this.dispose()),stopWithTheProcess(this)}schedule(){this.disabled||this.disposed||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.request(),this.opts.debounceMs??500),this.timer.unref?.())}request(){if(this.disabled||this.disposed)return;if(this.phase==="running"){this.dirty=!0;return}if(this.phase==="waiting")return;this.phase="waiting",this.askedAt=Date.now();const t=this.queue(this.opts.appName,()=>this.run(),{onHold:c(o=>this.held(o),"onHold")});this.isIdle()?t.release():this.ticket=t}held(t){if(!this.disposed&&(console.log(`[tsgo] ${this.opts.appName}: check held \u2014 ${t.availableMb} MB free, it waits for ${t.minFreeMb} MB (LENSMCP_TYPECHECK_MIN_FREE_MB)`),this.opts.publishEvents!==!1))try{(0,typecheck_bus_1.publishTypecheckHeld)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,availableMb:t.availableMb,minFreeMb:t.minFreeMb,...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}forgetBuildInfo(){if(this.buildInfo)try{fs.rmSync(this.buildInfo,{force:!0})}catch{}}isIdle(){return this.phase==="idle"}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){if(this.disposed)return this.leave();let t;try{t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath),t&&(this.shimPath=writeShimTsconfig(this.opts.appName,this.opts.tsConfig,this.opts.workspaceRoot))}catch(h){return console.warn(`[tsgo] ${this.opts.appName}: could not prepare the check \u2014 ${h.message}`),this.publish({output:"",durationMs:0,toolError:`could not prepare the check: ${h.message}`}),this.leave()}if(!t){this.disabled=!0;const h=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;return console.warn(`[tsgo] ${this.opts.appName}: ${h}.`),this.publish({output:"",durationMs:0,toolError:h}),this.leave()}this.phase="running",this.dirty=!1;const o=Date.now(),r=o-this.askedAt,s=this.spawnImpl(t,tsgoCheckArgs(this.shimPath,this.buildInfo),{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"],env:{...process.env,GOMAXPROCS:process.env.GOMAXPROCS??String(this.opts.maxProcs??checkerMaxProcs())}});this.inflight=s;let i="",n=!1;const a=this.opts.timeoutMs??DEFAULT_TIMEOUT_MS,u=setTimeout(()=>{n=!0,s.kill("SIGKILL")},a);u.unref?.(),s.stdout?.on("data",h=>{i+=h.toString()}),s.stderr?.on("data",h=>{i+=h.toString()}),s.on("error",()=>{clearTimeout(u),this.inflight===s&&(console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.forgetBuildInfo(),this.publish({output:"",durationMs:Date.now()-o,toolError:`failed to spawn ${t}`}),this.finish(s))}),s.on("close",(h,p)=>{if(clearTimeout(u),this.inflight!==s)return;const d=Date.now()-o,g=(d/1e3).toFixed(1),b=r>=1e3?`${g}s, waited ${(r/1e3).toFixed(1)}s`:`${g}s`;if(this.disposed)return this.finish(s);if(n){const f=`the check was killed after ${Math.round(a/1e3)}s without finishing`;return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:"",durationMs:d,toolError:f}),this.finish(s)}if(p){const f=`the check was ended by ${p} from outside before it finished`;return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:"",durationMs:d,toolError:f}),this.finish(s)}if(h===0)return console.log(`[tsgo] ${this.opts.appName}: types clean (${b})`),this.publish({output:"",durationMs:d}),this.finish(s);i.trim()&&process.stdout.write(i.endsWith(`
|
|
3
3
|
`)?i:`${i}
|
|
4
|
-
`);const
|
|
4
|
+
`);const k=(0,typecheck_bus_1.parseTscProgramErrors)(i);if(k.length){const f=(0,typecheck_bus_1.programErrorDetail)("tsgo",k,h);return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:i,durationMs:d,toolError:f}),this.finish(s)}const m=(0,typecheck_bus_1.parseTscOutput)(i).filter(f=>f.severity==="error").length;console.log(`[tsgo] ${this.opts.appName}: ${m} type error${m===1?"":"s"} (${b})`),m===0&&this.forgetBuildInfo(),this.publish({output:i,durationMs:d,...m===0?{toolError:`tsgo exited ${h} with no diagnostics: ${firstLine(i)}`}:{}}),this.finish(s)})}finish(t){this.inflight===t&&(this.inflight=null),this.leave(),this.dirty&&!this.disposed&&(this.dirty=!1,this.request())}leave(){this.phase="idle",this.ticket?.release(),this.ticket=null}dispose(){this.disposed||(this.disposed=!0,livePlugins.delete(this),this.timer&&clearTimeout(this.timer),this.inflight&&(this.inflight.kill("SIGKILL"),this.forgetBuildInfo()),this.ticket?.release(),this.ticket=null)}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(e){return e.trim().split(`
|
|
5
5
|
`)[0]?.slice(0,300)??""}l(firstLine,"firstLine"),c(firstLine,"firstLine");
|
package/typecheck-bus.d.ts
CHANGED
|
@@ -12,6 +12,21 @@ export declare function stripAnsi(s: string): string;
|
|
|
12
12
|
export declare function parseTscDiagnosticLine(raw: string): TscDiagnostic | null;
|
|
13
13
|
/** MIRROR of session's `parseTscOutput`. */
|
|
14
14
|
export declare function parseTscOutput(output: string): TscDiagnostic[];
|
|
15
|
+
/**
|
|
16
|
+
* A compiler error printed with no file position — `error TS18003: No inputs were found in config file …`, the TS5xxx
|
|
17
|
+
* option errors, TS6053/TS5083 (an extended file not found), TS6310. The program was not checked, so a run holding one
|
|
18
|
+
* has no verdict (planning/checks/00-plan.md, finding 1). Producer-only: session's mirror does not read it yet.
|
|
19
|
+
*/
|
|
20
|
+
export interface TscProgramError {
|
|
21
|
+
code: string;
|
|
22
|
+
message: string;
|
|
23
|
+
/** Whatever the line named before `error`, when it named something without a position. */
|
|
24
|
+
source?: string;
|
|
25
|
+
}
|
|
26
|
+
/** Every `error TS…` line that {@link parseTscDiagnosticLine} cannot place, in order. */
|
|
27
|
+
export declare function parseTscProgramErrors(output: string): TscProgramError[];
|
|
28
|
+
/** The no-verdict reason for a run whose program could not be checked: the first program error, and how many more. */
|
|
29
|
+
export declare function programErrorDetail(tool: string, errors: readonly TscProgramError[], exitCode?: number | null): string;
|
|
15
30
|
/** MIRROR of session's cap — a broken tsconfig can cascade into thousands. */
|
|
16
31
|
export declare const MAX_DIAGNOSTICS_PER_RUN = 200;
|
|
17
32
|
/** Loose BaseEvent shape — cluster does not depend on `@lensmcp/protocol-types`. */
|
|
@@ -49,6 +64,8 @@ export declare function buildTypecheckRunEvents(args: {
|
|
|
49
64
|
diagnostics: readonly TscDiagnostic[];
|
|
50
65
|
durationMs: number;
|
|
51
66
|
toolError?: string;
|
|
67
|
+
/** Kept on the END event of a no-verdict run, so the reason is there with its codes. */
|
|
68
|
+
programErrors?: readonly TscProgramError[];
|
|
52
69
|
now?: () => number;
|
|
53
70
|
idImpl?: () => string;
|
|
54
71
|
}): TypecheckBusEvent[];
|
package/typecheck-bus.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)){const
|
|
1
|
+
"use strict";var d=Object.defineProperty;var s=(t,e)=>d(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,r=s((t,e)=>f(t,"name",{value:e,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_DIAGNOSTICS_PER_RUN=void 0,exports.stripAnsi=stripAnsi,exports.parseTscDiagnosticLine=parseTscDiagnosticLine,exports.parseTscOutput=parseTscOutput,exports.parseTscProgramErrors=parseTscProgramErrors,exports.programErrorDetail=programErrorDetail,exports.buildTypecheckRunEvents=buildTypecheckRunEvents,exports.resolveEventFile=resolveEventFile,exports.appendTypecheckEvents=appendTypecheckEvents,exports.publishTypecheckDiagnostics=publishTypecheckDiagnostics,exports.publishTypecheckRun=publishTypecheckRun,exports.buildTypecheckHeldEvent=buildTypecheckHeldEvent,exports.publishTypecheckHeld=publishTypecheckHeld;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})(),DIAG_LINE_REGEX=/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/,ANSI_CSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function stripAnsi(t){return t.replace(ANSI_CSI,"")}s(stripAnsi,"stripAnsi"),r(stripAnsi,"stripAnsi");function parseTscDiagnosticLine(t){const e=stripAnsi(t).trim();if(!e)return null;const n=DIAG_LINE_REGEX.exec(e);if(!n)return null;const[,o,c,p,l,a,u]=n;return!o||!c||!p||!l||!a||!u?null:{file:o,line:Number(c),column:Number(p),severity:l==="warning"?"warning":"error",code:a,message:u}}s(parseTscDiagnosticLine,"parseTscDiagnosticLine"),r(parseTscDiagnosticLine,"parseTscDiagnosticLine");function parseTscOutput(t){const e=[];for(const n of t.split(`
|
|
2
|
+
`)){const o=parseTscDiagnosticLine(n);o&&e.push(o)}return e}s(parseTscOutput,"parseTscOutput"),r(parseTscOutput,"parseTscOutput");const PROGRAM_ERROR_REGEX=/\berror\s+(TS\d+):?\s*(.*)$/;function parseTscProgramErrors(t){const e=[];for(const n of t.split(`
|
|
3
|
+
`)){const o=stripAnsi(n).trim();if(!o||parseTscDiagnosticLine(o))continue;const c=PROGRAM_ERROR_REGEX.exec(o);if(!c)continue;const[,p="",l=""]=c,a=o.slice(0,c.index).replace(/[\s:]+$/,"");e.push({code:p,message:l,...a?{source:a}:{}})}return e}s(parseTscProgramErrors,"parseTscProgramErrors"),r(parseTscProgramErrors,"parseTscProgramErrors");function programErrorDetail(t,e,n){const o=e[0],c=e.length>1?` (+${e.length-1} more)`:"",p=n==null?"":` (exit ${n})`;return`${t} could not check the program${p}: ${o?`${o.code}: ${o.message}`.slice(0,300):"no message"}${c}`}s(programErrorDetail,"programErrorDetail"),r(programErrorDetail,"programErrorDetail"),exports.MAX_DIAGNOSTICS_PER_RUN=200;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}s(makeId,"makeId"),r(makeId,"makeId");function buildTypecheckRunEvents(t){const e=(t.now??Date.now)(),n=t.idImpl??makeId,o="pending",c={sessionId:o,source:"typescript",category:"typecheck",context:{sessionId:o,projectName:t.project}},p={project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{}},l=t.diagnostics.filter(i=>i.severity==="error"),a=t.diagnostics.slice(0,exports.MAX_DIAGNOSTICS_PER_RUN),u=[];if(!t.toolError){u.push({...c,id:n(),timestamp:e,severity:"info",title:`tsc clear: ${t.project}`,message:`typecheck run starting for ${t.project}`,fingerprint:`tsc:${t.project}:run-start`,raw:{...p,kind:"typecheck-run",phase:"start"}});for(const i of a)u.push({...c,id:n(),timestamp:e,severity:i.severity,title:`${i.code}: ${i.message}`,message:i.message,location:{file:i.file,line:i.line,column:i.column},fingerprint:`tsc:${t.project}:${i.file}:${i.line}:${i.column}:${i.code}`,raw:{...p,kind:"typecheck-diagnostic",code:i.code}})}const g=t.toolError?"error":l.length>0?"failing":"clean";return u.push({...c,id:n(),timestamp:e,severity:"info",title:`typecheck run: ${t.project} \u2014 ${t.toolError?"tool error":`${l.length} error${l.length===1?"":"s"}`} (${t.durationMs}ms)`,...t.toolError?{message:t.toolError}:{},fingerprint:`tsc:${t.project}:run-end`,raw:{...p,kind:"typecheck-run",phase:"end",status:g,durationMs:t.durationMs,errorCount:l.length,warningCount:t.diagnostics.length-l.length,...t.diagnostics.length>a.length?{truncatedDiagnostics:t.diagnostics.length-a.length}:{},...t.toolError?{error:t.toolError}:{},...t.programErrors?.length?{programErrors:t.programErrors.slice(0,exports.MAX_DIAGNOSTICS_PER_RUN)}:{}}}),u}s(buildTypecheckRunEvents,"buildTypecheckRunEvents"),r(buildTypecheckRunEvents,"buildTypecheckRunEvents");function resolveEventFile(t){return process.env.LENSMCP_EVENT_FILE||path.join(t,".lensmcp","events.jsonl")}s(resolveEventFile,"resolveEventFile"),r(resolveEventFile,"resolveEventFile");let ensuredDir=null;function ensureDir(t){const e=path.dirname(t);ensuredDir!==e&&(fs.mkdirSync(e,{recursive:!0}),ensuredDir=e)}s(ensureDir,"ensureDir"),r(ensureDir,"ensureDir");function appendTypecheckEvents(t,e){if(e.length===0)return;const n=e.map(o=>JSON.stringify(o)).join(`
|
|
3
4
|
`)+`
|
|
4
|
-
`;try{ensureDir(t),busHygiene?.maybeRotateEventFile(t,
|
|
5
|
+
`;try{ensureDir(t),busHygiene?.maybeRotateEventFile(t,n.length),fs.appendFileSync(t,n)}catch(o){if(o?.code==="ENOENT"){try{ensuredDir=null,ensureDir(t),fs.appendFileSync(t,n)}catch{}return}}}s(appendTypecheckEvents,"appendTypecheckEvents"),r(appendTypecheckEvents,"appendTypecheckEvents");function publishTypecheckDiagnostics(t){const e=buildTypecheckRunEvents({project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{},diagnostics:t.diagnostics,durationMs:t.durationMs});return appendTypecheckEvents(t.eventFile??resolveEventFile(t.workspaceRoot),e),e}s(publishTypecheckDiagnostics,"publishTypecheckDiagnostics"),r(publishTypecheckDiagnostics,"publishTypecheckDiagnostics");function publishTypecheckRun(t){const e=parseTscProgramErrors(t.output),n=t.toolError??(e.length?programErrorDetail(t.tool,e):void 0),o=buildTypecheckRunEvents({project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{},diagnostics:n?[]:parseTscOutput(t.output),durationMs:t.durationMs,...n?{toolError:n}:{},...e.length?{programErrors:e}:{}});return appendTypecheckEvents(t.eventFile??resolveEventFile(t.workspaceRoot),o),o}s(publishTypecheckRun,"publishTypecheckRun"),r(publishTypecheckRun,"publishTypecheckRun");function buildTypecheckHeldEvent(t){const e="pending";return{id:(t.idImpl??makeId)(),sessionId:e,timestamp:(t.now??Date.now)(),source:"typescript",category:"typecheck",severity:"info",context:{sessionId:e,projectName:t.project},title:`typecheck held: ${t.project} \u2014 ${t.availableMb} MB free, a check waits for ${t.minFreeMb} MB`,message:`the type check of ${t.project} waits until ${t.minFreeMb} MB is free (LENSMCP_TYPECHECK_MIN_FREE_MB)`,fingerprint:`tsc:${t.project}:run-held`,raw:{project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{},kind:"typecheck-run",phase:"held",availableMb:t.availableMb,minFreeMb:t.minFreeMb}}}s(buildTypecheckHeldEvent,"buildTypecheckHeldEvent"),r(buildTypecheckHeldEvent,"buildTypecheckHeldEvent");function publishTypecheckHeld(t){const e=buildTypecheckHeldEvent(t);return appendTypecheckEvents(t.eventFile??resolveEventFile(t.workspaceRoot),[e]),e}s(publishTypecheckHeld,"publishTypecheckHeld"),r(publishTypecheckHeld,"publishTypecheckHeld");
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The bidirectional progress bound — SHARED by both gateways (lifted from `prod-runtime/body-stall.ts`;
|
|
3
|
-
* the dev proxy arms the same guard on its h1 and h2 paths, issues/closed/dev-gateway-12).
|
|
4
|
-
*
|
|
5
|
-
* `requestTimeout` is deliberately 0 on this proxy — a hard request deadline would cut the
|
|
6
|
-
* long-lived streaming (SSE, streamable-HTTP MCP) it exists to carry. But `headersTimeout`
|
|
7
|
-
* only ever bounded HEADERS, and undici's `bodyTimeout` is 0 too, so nothing bounded a
|
|
8
|
-
* request BODY: a client could send headers, have the gateway dispatch upstream, and then
|
|
9
|
-
* dribble one byte a minute — holding one of the 256 per-origin pool connections for as long
|
|
10
|
-
* as it liked. 256 of those and a service is unreachable, from one unauthenticated client.
|
|
11
|
-
*
|
|
12
|
-
* The bound here is on STALL, not duration: a request is killed only when it has transferred
|
|
13
|
-
* NOTHING for the whole window. A slow-but-progressing upload is untouched, and a request
|
|
14
|
-
* whose body has already been fully received is never watched at all — so an indefinitely
|
|
15
|
-
* open SSE *response* is unaffected.
|
|
16
|
-
*
|
|
17
|
-
* Progress is read from `socket.bytesRead` rather than a `data` listener, because attaching
|
|
18
|
-
* one would put the request stream into flowing mode and steal the body from reply-from.
|
|
19
|
-
*
|
|
20
|
-
* The RESPONSE direction needs the same bound for the same reason. A client that requests a
|
|
21
|
-
* large body and then stops reading applies backpressure all the way up the pipe, and the
|
|
22
|
-
* undici pool connection serving it stays busy for as long as the client cares to wait — 256
|
|
23
|
-
* of those (the default per-origin pool) make a service unreachable for everyone else, from
|
|
24
|
-
* one unauthenticated client. `armResponse` watches for that, and it is a STALL bound too:
|
|
25
|
-
* a response is killed only while bytes are queued in the socket AND none have moved for the
|
|
26
|
-
* whole window, so a client that is draining slowly is untouched and an idle SSE stream (with
|
|
27
|
-
* nothing queued) is never even a candidate.
|
|
28
|
-
*/
|
|
29
|
-
import type * as http from 'node:http';
|
|
30
|
-
export interface BodyStallGuard {
|
|
31
|
-
/** Watch a request that is still receiving a body. No-op for a body-less request. */
|
|
32
|
-
arm(req: http.IncomingMessage): void;
|
|
33
|
-
/** Watch a response for a client that has stopped draining it. */
|
|
34
|
-
armResponse(res: http.ServerResponse): void;
|
|
35
|
-
stop(): void;
|
|
36
|
-
}
|
|
37
|
-
/** Does this request carry a body at all? Only one that does can stall mid-body — or still be arriving. */
|
|
38
|
-
export declare function requestCarriesBody(req: http.IncomingMessage): boolean;
|
|
39
|
-
/**
|
|
40
|
-
* Is the client still SENDING this request's body? The inbound half of what the stall bound watches: a
|
|
41
|
-
* request that carries a body and has not completed.
|
|
42
|
-
*
|
|
43
|
-
* The dev proxy's first-byte guard reads it too (issues/closed/codex-security-27). An upstream body parser
|
|
44
|
-
* produces no headers until the last byte is in, so a pod "silent" while the body is still arriving is
|
|
45
|
-
* waiting on the CLIENT — that time is not the pod's, and must never count toward evicting it. Read from
|
|
46
|
-
* the request's own state rather than this guard's sampler, so it holds when the stall bound is disabled.
|
|
47
|
-
*/
|
|
48
|
-
export declare function requestBodyArriving(req: http.IncomingMessage): boolean;
|
|
49
|
-
/**
|
|
50
|
-
* The body RATE bound (issues/closed/prod-gateway-4-04) — `mod_reqtimeout`'s shape. A stall bound alone calls any
|
|
51
|
-
* byte progress: one byte a minute held an upstream pool connection for as long as the client liked, and 256 such
|
|
52
|
-
* sockets (the default pool) took a whole origin away for the price of nothing. With a rate bound a request body gets
|
|
53
|
-
* `graceMs` up front and one more second for every `minBytesPerSec` bytes received; a body that falls behind that
|
|
54
|
-
* line is cut. A real upload on the slowest link in use (2G is ~6 KB/s) stays far ahead of 500 B/s.
|
|
55
|
-
*/
|
|
56
|
-
export interface BodyRateOptions {
|
|
57
|
-
/** Bytes per second a request body must average once the grace is spent. 0 / unset = no rate bound. */
|
|
58
|
-
minBytesPerSec?: number;
|
|
59
|
-
/** The allowance before the rate applies (ms). Default 30 000. */
|
|
60
|
-
graceMs?: number;
|
|
61
|
-
}
|
|
62
|
-
export declare function createBodyStallGuard(stallMs: number, rate?: BodyRateOptions): BodyStallGuard;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var u=(r,o)=>p(r,"name",{value:o,configurable:!0});var l=Object.defineProperty,i=u((r,o)=>l(r,"name",{value:o,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestCarriesBody=requestCarriesBody,exports.requestBodyArriving=requestBodyArriving,exports.createBodyStallGuard=createBodyStallGuard;const OFF={arm:i(()=>{},"arm"),armResponse:i(()=>{},"armResponse"),stop:i(()=>{},"stop")};function requestCarriesBody(r){const o=r.headers["content-length"];return String(r.headers["transfer-encoding"]??"").toLowerCase().includes("chunked")||typeof o=="string"&&Number(o)>0}u(requestCarriesBody,"requestCarriesBody"),i(requestCarriesBody,"requestCarriesBody");function requestBodyArriving(r){return requestCarriesBody(r)&&!r.complete&&!r.destroyed}u(requestBodyArriving,"requestBodyArriving"),i(requestBodyArriving,"requestBodyArriving");function createBodyStallGuard(r,o={}){const y=Number.isFinite(o.minBytesPerSec)&&o.minBytesPerSec>0?o.minBytesPerSec:0,b=Number.isFinite(o.graceMs)&&o.graceMs>=0?o.graceMs:3e4,a=Number.isFinite(r)&&r>0;if(!a&&!y)return OFF;const c=new Map,d=new Map,m=Math.max(500,Math.min(a?r:5e3,y?1e3:5e3,5e3)),f=setInterval(i(()=>{if(c.size===0&&d.size===0)return;const e=Date.now();for(const[t,s]of c){if(t.complete||t.destroyed||!t.socket||t.socket.destroyed){c.delete(t);continue}const n=t.socket.bytesRead;if(y&&e-s.started>b+(n-s.from)/y*1e3){c.delete(t),t.socket.destroy();continue}if(n!==s.bytes){s.bytes=n,s.since=e;continue}a&&e-s.since>=r&&(c.delete(t),t.socket.destroy())}if(a)for(const[t,s]of d){const n=t.socket;if(t.writableEnded||t.destroyed||!n||n.destroyed){d.delete(t);continue}if(n.writableLength===0){s.bytes=n.bytesWritten,s.since=e;continue}if(n.bytesWritten!==s.bytes){s.bytes=n.bytesWritten,s.since=e;continue}e-s.since>=r&&(d.delete(t),n.destroy())}},"tick"),m);return f.unref?.(),{arm(e){if(!requestCarriesBody(e)||e.complete||!e.socket)return;const t=Date.now(),s=e.socket.bytesRead;c.set(e,{bytes:s,since:t,from:s,started:t});const n=i(()=>{c.delete(e)},"done");e.on("end",n),e.on("close",n),e.on("aborted",n)},armResponse(e){const t=e.socket;if(!a||!t||e.writableEnded||e.destroyed)return;d.set(e,{bytes:t.bytesWritten,since:Date.now()});const s=i(()=>{d.delete(e)},"done");e.on("finish",s),e.on("close",s)},stop(){clearInterval(f),c.clear(),d.clear()}}}u(createBodyStallGuard,"createBodyStallGuard"),i(createBodyStallGuard,"createBodyStallGuard");
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The ONE request-path canonicalizer — shared by BOTH gateways.
|
|
3
|
-
*
|
|
4
|
-
* Lifted out of `prod-runtime/edge.ts` (prod-gateway-2 #01/#03/#04/#12) so the dev gateway can stop
|
|
5
|
-
* routing, authorising and forwarding the RAW `req.url` (issues/closed/dev-gateway-11: `/./admin`, an
|
|
6
|
-
* absolute-form target and `/..;/admin` all skipped dev's path policy while prod had been fixed).
|
|
7
|
-
* `prod-runtime/edge.ts` and `runtime/edge.ts` re-export everything here, so each pipeline keeps its
|
|
8
|
-
* import surface and neither can drift from the other.
|
|
9
|
-
*/
|
|
10
|
-
import type * as http from 'node:http';
|
|
11
|
-
export declare const ENCODED_STRUCTURE: RegExp;
|
|
12
|
-
/**
|
|
13
|
-
* The ONE canonical form of a request target. Everything downstream — mount matching, the auth
|
|
14
|
-
* override, the ABAC `path` attribute, the forwarded URL and the WebSocket request line — is
|
|
15
|
-
* derived from this, so the gateway can no longer authorise one string and forward another.
|
|
16
|
-
*
|
|
17
|
-
* Two representations, because they answer different questions:
|
|
18
|
-
* - `path` keeps the ORIGINAL percent-encoding, so what reaches the upstream is byte-equivalent
|
|
19
|
-
* to what the client asked for (decoding and re-encoding would turn `%3F` into a real `?`).
|
|
20
|
-
* - `policy` is the same path DECODED, so `/%61dmin` is judged as `/admin`.
|
|
21
|
-
*/
|
|
22
|
-
export interface CanonicalTarget {
|
|
23
|
-
/** Canonical path, original encoding preserved — routed and forwarded. */
|
|
24
|
-
path: string;
|
|
25
|
-
/** Canonical path, decoded — matched against auth overrides and ABAC rules. */
|
|
26
|
-
policy: string;
|
|
27
|
-
/** The query string including `?`, exactly as received (never re-encoded), or ''. */
|
|
28
|
-
query: string;
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Canonicalize a request target, or `undefined` if it is unsafe (→ 400 / drop).
|
|
32
|
-
*
|
|
33
|
-
* Three rejections and two collapses, each one a fixed bug:
|
|
34
|
-
* - an ABSOLUTE-form target (`GET http://host/admin`) is refused. Node leaves the scheme and
|
|
35
|
-
* authority in `req.url`, `find-my-way` strips them only for its own lookup, and
|
|
36
|
-
* `@fastify/reply-from` accepts an absolute source whose origin matches the route — so the
|
|
37
|
-
* segments the override was matched against were `['http:', 'host', 'admin']` and the
|
|
38
|
-
* upstream still got `/admin`.
|
|
39
|
-
* - matrix parameters and the fragment are stripped BEFORE any segment is judged, so
|
|
40
|
-
* `/..;/admin` cannot hide a traversal behind a parameter (it used to survive the `..`
|
|
41
|
-
* test and then have the `;x` trimmed off, yielding `/../admin`).
|
|
42
|
-
* - a `..` segment is rejected, never resolved.
|
|
43
|
-
* - empty (`//`) and single-dot (`/./`) segments collapse, because the upstream's own URL
|
|
44
|
-
* parsing collapses them and the policy matcher already ignored them — the gateway used to
|
|
45
|
-
* authorise `/./admin` and forward `/admin`.
|
|
46
|
-
* - a trailing slash is PRESERVED (RFC 3986 §5.2.4: `/a/.` resolves to `/a/`), since
|
|
47
|
-
* `/a` and `/a/` are different resources to many backends.
|
|
48
|
-
*/
|
|
49
|
-
export declare const canonicalize: (rawUrl: string) => CanonicalTarget | undefined;
|
|
50
|
-
/**
|
|
51
|
-
* Where the request target AS RECEIVED is kept, when canonicalization changed it.
|
|
52
|
-
*
|
|
53
|
-
* The handler replaces `req.url` with the canonical form so routing, policy and the wire cannot
|
|
54
|
-
* diverge — but that form is also what the access log reads, and an operator investigating a
|
|
55
|
-
* probe needs to see what the client actually sent: `/./admin` and `/admin` are the same line in
|
|
56
|
-
* the log otherwise, and the attempt disappears. Set ONLY when the two differ, so ordinary
|
|
57
|
-
* traffic carries no extra work and no extra field.
|
|
58
|
-
*/
|
|
59
|
-
export declare const RAW_TARGET: unique symbol;
|
|
60
|
-
/** The target as received, if canonicalization rewrote it. */
|
|
61
|
-
export declare const rawTargetOf: (req: http.IncomingMessage) => string | undefined;
|
|
62
|
-
/** Remember the target as received, for the access log. */
|
|
63
|
-
export declare const rememberRawTarget: (req: http.IncomingMessage, raw: string) => void;
|
|
64
|
-
/** The decoded canonical path for auth matching, or undefined if the path is unsafe. */
|
|
65
|
-
export declare const canonicalPath: (rawUrl: string) => string | undefined;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var x=Object.defineProperty;var f=(e,t)=>x(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,r=f((e,t)=>u(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.canonicalPath=exports.rememberRawTarget=exports.rawTargetOf=exports.RAW_TARGET=exports.canonicalize=exports.ENCODED_STRUCTURE=void 0,exports.ENCODED_STRUCTURE=/%2e|%2f|%5c|%00|\\/i;const NEEDS_NORMALIZE=/[%;#\\]|\/\/|(?:^|\/)\.{1,2}(?:\/|$)/,canonicalize=r(e=>{if(e.charCodeAt(0)!==47)return;const t=e.indexOf("?"),a=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(a.indexOf("\0")!==-1)return;if(!NEEDS_NORMALIZE.test(a))return{path:a,policy:a,query:s};if(exports.ENCODED_STRUCTURE.test(a))return;const c=a.split("#")[0].split("/").map(n=>n.split(";")[0]),i=[],p=[];for(const n of c){let o;try{o=decodeURIComponent(n)}catch{return}if(o.indexOf("\0")!==-1)return;if(!(o===""||o===".")){if(o==="..")return;i.push(n),p.push(o)}}const l=c[c.length-1],T=i.length>0&&(l===""||l===".")?"/":"";return{path:"/"+i.join("/")+T,policy:"/"+p.join("/")+T,query:s}},"canonicalize");exports.canonicalize=canonicalize,exports.RAW_TARGET=Symbol.for("lensmcp.gateway.rawTarget");const rawTargetOf=r(e=>e[exports.RAW_TARGET],"rawTargetOf");exports.rawTargetOf=rawTargetOf;const rememberRawTarget=r((e,t)=>{e[exports.RAW_TARGET]=t},"rememberRawTarget");exports.rememberRawTarget=rememberRawTarget;const canonicalPath=r(e=>(0,exports.canonicalize)(e)?.policy,"canonicalPath");exports.canonicalPath=canonicalPath;
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import type * as http from 'node:http';
|
|
2
|
-
export interface ClientIpOptions {
|
|
3
|
-
/** A front proxy's client-address header (e.g. `cf-connecting-ip`), trusted only from a trusted peer. */
|
|
4
|
-
clientIpHeader?: string;
|
|
5
|
-
/** CIDRs of peers allowed to assert `clientIpHeader`. Empty ⇒ loopback only (a co-located sidecar). */
|
|
6
|
-
clientIpTrustedProxies?: readonly string[];
|
|
7
|
-
/** How many proxy hops in front of us are trusted to have appended to `X-Forwarded-For`. 0 = none. */
|
|
8
|
-
trustProxyHops?: number;
|
|
9
|
-
/**
|
|
10
|
-
* A secret the front proxy adds to every request (issues/closed/prod-gateway-4-17). With it, a peer is the trusted
|
|
11
|
-
* proxy only when its ADDRESS is trusted AND the request carries `header: value` — an address alone cannot tell the
|
|
12
|
-
* tunnel from any other process on loopback (a sidecar, a host-network container). The header is the gateway's:
|
|
13
|
-
* {@link ClientIpResolver.dropProxySecret} removes it before anything is forwarded. `header` defaults to
|
|
14
|
-
* `x-lensmcp-proxy-secret`.
|
|
15
|
-
*/
|
|
16
|
-
proxySecret?: {
|
|
17
|
-
header?: string;
|
|
18
|
-
value: string;
|
|
19
|
-
};
|
|
20
|
-
/** Told ONCE when the configured client-address header arrives from a peer that is not a trusted proxy — the
|
|
21
|
-
* header is then ignored, which silently makes that peer «the client» for every request it carries. */
|
|
22
|
-
onIgnoredProxyHeader?: (peer: string, header: string) => void;
|
|
23
|
-
}
|
|
24
|
-
/** What the peer of a request is to the gateway — which decides whose forwarding headers are kept. */
|
|
25
|
-
export type ProxyKind =
|
|
26
|
-
/** Not a trusted proxy: every forwarding / client-address header it sent is a claim the caller made about itself. */
|
|
27
|
-
'none'
|
|
28
|
-
/** A trusted peer with no client-address header configured: the headers a rule may read from it are evidence
|
|
29
|
-
* (`attributeHeaders`), but it states no chain — the gateway's own hop is the whole `X-Forwarded-For`. */
|
|
30
|
-
| 'peer'
|
|
31
|
-
/** A proxy trusted for its client-address header (`clientIpHeader`): its own header family is evidence. */
|
|
32
|
-
| 'header'
|
|
33
|
-
/** A counted `X-Forwarded-For` chain (`trustProxyHops`): a generic proxy — its forwarding headers are kept. */
|
|
34
|
-
| 'chain';
|
|
35
|
-
export interface ClientIpResolver {
|
|
36
|
-
/** The authoritative client address for `req`, or `fallback` (normally the socket peer). */
|
|
37
|
-
clientIpOf(req: http.IncomingMessage, fallback: string): string;
|
|
38
|
-
/** The `X-Forwarded-For` to send upstream: trusted chain + peer, or just the peer. */
|
|
39
|
-
forwardedFor(req: http.IncomingMessage, peer: string): string;
|
|
40
|
-
/** Is this peer address a trusted front proxy? */
|
|
41
|
-
peerTrusted(peer?: string): boolean;
|
|
42
|
-
/**
|
|
43
|
-
* Is a forwarding header from this peer evidence (PG3-05)? True behind a counted trusted hop chain, or when the
|
|
44
|
-
* peer itself is trusted (`clientIpTrustedProxies`, default loopback). Used for request headers a rule may read.
|
|
45
|
-
*/
|
|
46
|
-
peerAsserts(peer?: string, req?: http.IncomingMessage): boolean;
|
|
47
|
-
/** What this request's peer is ({@link ProxyKind}) — address trust AND, when one is configured, the proxy secret. */
|
|
48
|
-
proxyKind(req: http.IncomingMessage, peer?: string): ProxyKind;
|
|
49
|
-
/** Remove the proxy secret from the request (after {@link proxyKind} judged it — the verdict is remembered). */
|
|
50
|
-
dropProxySecret(req: http.IncomingMessage): void;
|
|
51
|
-
/** Lower-cased request headers that are the configured proxy's to assert (`clientIpHeader`). */
|
|
52
|
-
readonly proxyHeaders: readonly string[];
|
|
53
|
-
/**
|
|
54
|
-
* The `X-Forwarded-Proto` to send upstream (PG3-04). A trusted front proxy terminated the user's TLS, so ITS
|
|
55
|
-
* statement of the scheme is kept (`X-Forwarded-Proto`, else Cloudflare's `CF-Visitor` when the client address
|
|
56
|
-
* comes from `cf-connecting-ip`); anyone else gets the gateway's own listener scheme. Trust is the forwarding
|
|
57
|
-
* chain's: the same condition {@link forwardedFor} appends to a chain under.
|
|
58
|
-
*/
|
|
59
|
-
forwardedProto(req: http.IncomingMessage, peer: string, ownScheme: 'http' | 'https'): 'http' | 'https';
|
|
60
|
-
readonly trustProxyHops: number;
|
|
61
|
-
}
|
|
62
|
-
/** An IPv4-mapped IPv6 peer (`::ffff:127.0.0.1`, what a dual-stack listener reports) → its IPv4 form. */
|
|
63
|
-
export declare const normalizePeer: (addr: string) => string;
|
|
64
|
-
/** Is `addr` in `list` — IPv4 CIDRs (`10.0.0.0/8`) or exact addresses (`::1`, `10.1.2.3`)? Mapped IPv6 folds first. */
|
|
65
|
-
export declare const addressIn: (addr: string, list: readonly string[]) => boolean;
|
|
66
|
-
/** `1.2.3.4:51234` (an X-Forwarded-For port suffix) → `1.2.3.4`. IPv6 keeps its colons unless bracketed. */
|
|
67
|
-
export declare const stripPort: (v: string) => string;
|
|
68
|
-
/**
|
|
69
|
-
* The bucket a client address is limited under (issues/closed/prod-gateway-4-10). An IPv4 address is its own bucket.
|
|
70
|
-
* An IPv6 address is bucketed by its /64: every IPv6 subscriber is handed at least a /64, so per-address buckets
|
|
71
|
-
* gave one client 2^64 of them — 40 addresses of one /64 took 40 full budgets. Every textual spelling of one
|
|
72
|
-
* address yields one key, and an IPv4-mapped address (`::ffff:1.2.3.4`, in either notation) is its IPv4 self.
|
|
73
|
-
*/
|
|
74
|
-
export declare const limiterKey: (addr: string, v6PrefixBits?: number) => string;
|
|
75
|
-
export declare function createClientIpResolver(opts?: ClientIpOptions): ClientIpResolver;
|
|
76
|
-
/**
|
|
77
|
-
* The dev gateway's knobs (the prod gateway reads its `LENSMCP_GW_*` twins in `prod-config.ts`):
|
|
78
|
-
* - `LENSMCP_TRUST_PROXY` — trusted `X-Forwarded-For` hop count (default 0: the socket peer is the client).
|
|
79
|
-
* - `LENSMCP_CLIENT_IP_HEADER` — a front proxy's client-address header, honoured from trusted peers only.
|
|
80
|
-
* - `LENSMCP_CLIENT_IP_TRUSTED_PROXIES` — comma-separated CIDRs that may assert it (default: loopback).
|
|
81
|
-
*/
|
|
82
|
-
export declare function clientIpOptionsFromEnv(env?: NodeJS.ProcessEnv): ClientIpOptions;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var C=Object.defineProperty;var u=(e,t)=>C(e,"name",{value:t,configurable:!0});var S=Object.defineProperty,s=u((e,t)=>S(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.limiterKey=exports.stripPort=exports.addressIn=exports.normalizePeer=void 0,exports.createClientIpResolver=createClientIpResolver,exports.clientIpOptionsFromEnv=clientIpOptionsFromEnv;const node_crypto_1=require("node:crypto"),manifest_1=require("./manifest"),first=s(e=>{const t=Array.isArray(e)?e[0]:e;return typeof t=="string"&&t.length>0?t:void 0},"first"),normalizePeer=s(e=>e.startsWith("::ffff:")&&e.indexOf(":",7)===-1?e.slice(7):e,"normalizePeer");exports.normalizePeer=normalizePeer;const addressIn=s((e,t)=>{const a=(0,exports.normalizePeer)(e);return t.some(c=>c.includes("/")?(0,manifest_1.matchCidr)(a,c):(0,exports.normalizePeer)(c)===a)},"addressIn");exports.addressIn=addressIn;const stripPort=s(e=>{if(e.startsWith("[")){const a=e.indexOf("]");return a===-1?e:e.slice(1,a)}const t=e.indexOf(":");return t!==-1&&e.indexOf(":",t+1)===-1?e.slice(0,t):e},"stripPort");exports.stripPort=stripPort;const limiterKey=s((e,t=64)=>{const a=(0,exports.normalizePeer)(e);if(!a.includes(":"))return a;const c=(0,manifest_1.ipv6ToBigInt)(a);if(c===null)return a;if(c>>32n===0xffffn){const p=Number(c&0xffffffffn);return`${p>>>24}.${p>>>16&255}.${p>>>8&255}.${p&255}`}const d=Math.min(128,Math.max(1,Math.floor(t)));return`${(c>>BigInt(128-d)).toString(16)}::/${d}`},"limiterKey");exports.limiterKey=limiterKey;function createClientIpResolver(e={}){const t=e.clientIpHeader?.toLowerCase(),a=e.clientIpTrustedProxies??[],c=Math.max(0,Math.floor(e.trustProxyHops??0)),d=e.proxySecret?.value?(e.proxySecret.header??"x-lensmcp-proxy-secret").toLowerCase():void 0,p=d?Buffer.from(e.proxySecret.value):void 0,x=s(r=>{if(!r)return!1;const o=r.startsWith("::ffff:")?r.slice(7):r;return a.length===0?o==="127.0.0.1"||r==="::1":(0,exports.addressIn)(o,a)},"peerTrusted"),m=new WeakMap,P=s(r=>{if(!d)return!0;if(!r)return!1;let o=m.get(r);if(o===void 0){const n=Buffer.from(first(r.headers[d])??"");o=n.length===p.length&&(0,node_crypto_1.timingSafeEqual)(n,p),m.set(r,o)}return o},"secretOk"),g=s(r=>{d&&(P(r),delete r.headers[d])},"dropProxySecret"),I=s(r=>String(r.headers["x-forwarded-for"]??"").split(",").map(o=>o.trim()).filter(Boolean),"forwardedChain"),y=s(r=>{const o=t?first(r.headers[t]):void 0;return(o?(0,exports.stripPort)(o.split(",")[0].trim()):"")||void 0},"headerAddress");let v=!1;const l=s((r,o)=>{const n=o??r.socket?.remoteAddress??void 0;if(!P(r))return"none";const i=x(n);if(t&&i)return"header";if(c>0)return"chain";if(i)return"peer";if(t&&!v&&e.onIgnoredProxyHeader&&r.headers[t]!==void 0){v=!0;try{e.onIgnoredProxyHeader(n??"(unknown)",t)}catch{}}return"none"},"proxyKind"),E=s((r,o)=>{const n=l(r);if(n==="header"){const i=y(r);if(i)return i}if(c>0&&n!=="none"){const i=I(r),f=i.length-c;if(f>=0&&i[f])return(0,exports.stripPort)(i[f])}return(0,exports.normalizePeer)(o)},"clientIpOf"),_=s((r,o)=>{const n=l(r,o);return n==="header"||n==="chain"},"chainTrusted");return{clientIpOf:E,forwardedFor:s((r,o)=>{const n=(0,exports.normalizePeer)(o),i=l(r,o);if(i==="header"){const f=y(r);if(f)return`${f}, ${n}`}if(i==="header"||i==="chain"){const f=I(r);return f.length?`${f.join(", ")}, ${n}`:n}return n},"forwardedFor"),peerTrusted:x,peerAsserts:s((r,o)=>o?l(o,r)!=="none":!d&&(c>0||x(r)),"peerAsserts"),proxyKind:l,dropProxySecret:g,proxyHeaders:t?[t]:[],forwardedProto:s((r,o,n)=>{if(!_(r,o))return n;const i=first(r.headers["x-forwarded-proto"])?.split(",")[0].trim().toLowerCase();if(i==="https"||i==="http")return i;if(t==="cf-connecting-ip"){const f=first(r.headers["cf-visitor"]);if(f)try{const h=JSON.parse(f).scheme;if(h==="https"||h==="http")return h}catch{}}return n},"forwardedProto"),trustProxyHops:c}}u(createClientIpResolver,"createClientIpResolver"),s(createClientIpResolver,"createClientIpResolver");function clientIpOptionsFromEnv(e=process.env){const t=Number(e.LENSMCP_TRUST_PROXY),a=String(e.LENSMCP_CLIENT_IP_TRUSTED_PROXIES??"").split(",").map(c=>c.trim()).filter(Boolean);return{...Number.isFinite(t)&&t>0?{trustProxyHops:Math.floor(t)}:{},...e.LENSMCP_CLIENT_IP_HEADER?{clientIpHeader:e.LENSMCP_CLIENT_IP_HEADER}:{},...a.length?{clientIpTrustedProxies:a}:{}}}u(clientIpOptionsFromEnv,"clientIpOptionsFromEnv"),s(clientIpOptionsFromEnv,"clientIpOptionsFromEnv");
|