@lensmcp/core 1.25.79 → 1.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/lib/event-loop.d.ts +9 -1
- package/lib/event-loop.js +1 -1
- package/lib/flow-shape.d.ts +9 -2
- package/lib/flow-shape.js +1 -1
- package/lib/lens-config.d.ts +14 -0
- package/lib/lens-config.js +1 -0
- package/lib/lens-dir.d.ts +9 -0
- package/lib/lens-dir.js +6 -6
- package/lib/lens-store.d.ts +37 -0
- package/lib/lens-store.js +1 -0
- package/lib/patterns.d.ts +28 -12
- package/lib/patterns.js +1 -1
- package/lib/performance-window.d.ts +20 -3
- package/lib/performance-window.js +2 -2
- package/lib/queue-signals.d.ts +7 -0
- package/lib/queue-signals.js +1 -0
- package/lib/stores.js +2 -2
- package/package.json +17 -2
package/index.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export * from './lib/flow-shape.js';
|
|
|
15
15
|
export * from './lib/flow-segments.js';
|
|
16
16
|
export * from './lib/flow-categories.js';
|
|
17
17
|
export * from './lib/headless-flow.js';
|
|
18
|
+
export * from './lib/queue-signals.js';
|
|
18
19
|
export * from './lib/service-hop.js';
|
|
19
20
|
export * from './lib/flows-config.js';
|
|
20
21
|
export * from './lib/patterns.js';
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";export*from"./lib/common.js";export*from"./lib/ulid.js";export*from"./lib/event-bus.js";export*from"./lib/event-redactor.js";export*from"./lib/resource-store.js";export*from"./lib/answer-budget.js";export*from"./lib/graph-store.js";export*from"./lib/fingerprint.js";export*from"./lib/reducer-registry.js";export*from"./lib/story.js";export*from"./lib/route-template.js";export*from"./lib/sql-shape.js";export*from"./lib/http-shape.js";export*from"./lib/flow-shape.js";export*from"./lib/flow-segments.js";export*from"./lib/flow-categories.js";export*from"./lib/headless-flow.js";export*from"./lib/service-hop.js";export*from"./lib/flows-config.js";export*from"./lib/patterns.js";export*from"./lib/thresholds.js";export*from"./lib/performance-window.js";export*from"./lib/event-loop.js";export*from"./lib/event-loop-history.js";export*from"./lib/graph-from-events.js";
|
|
1
|
+
"use strict";export*from"./lib/common.js";export*from"./lib/ulid.js";export*from"./lib/event-bus.js";export*from"./lib/event-redactor.js";export*from"./lib/resource-store.js";export*from"./lib/answer-budget.js";export*from"./lib/graph-store.js";export*from"./lib/fingerprint.js";export*from"./lib/reducer-registry.js";export*from"./lib/story.js";export*from"./lib/route-template.js";export*from"./lib/sql-shape.js";export*from"./lib/http-shape.js";export*from"./lib/flow-shape.js";export*from"./lib/flow-segments.js";export*from"./lib/flow-categories.js";export*from"./lib/headless-flow.js";export*from"./lib/queue-signals.js";export*from"./lib/service-hop.js";export*from"./lib/flows-config.js";export*from"./lib/patterns.js";export*from"./lib/thresholds.js";export*from"./lib/performance-window.js";export*from"./lib/event-loop.js";export*from"./lib/event-loop-history.js";export*from"./lib/graph-from-events.js";
|
package/lib/event-loop.d.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type BaseEvent, type EventLoopIdentity, type EventLoopIncident, type EventLoopSample, type EventLoopStatus } from '@lensmcp/protocol-types';
|
|
2
2
|
import { LoopSampleRing } from './event-loop-history.js';
|
|
3
3
|
export declare function eventLoopIdentity(v: unknown): EventLoopIdentity | undefined;
|
|
4
4
|
/** Strictly project producer data. No raw request/response or AI content is copied into incident evidence. */
|
|
5
5
|
export declare function eventLoopIncident(e: BaseEvent): EventLoopIncident | undefined;
|
|
6
|
+
/** How long a watchdog observation waits for its callback's incident before it is kept as one of its own. */
|
|
7
|
+
export declare const HEARTBEAT_SETTLE_MS = 5000;
|
|
6
8
|
/** Bounded live index. Persist complete incident envelopes through onChange, not references to expiring events. */
|
|
7
9
|
export declare class EventLoopIndex {
|
|
8
10
|
private readonly onChange;
|
|
9
11
|
/** Every sample an event carried, to be kept: the store skips what it holds already. */
|
|
10
12
|
private readonly onSamples;
|
|
11
13
|
private readonly incidents;
|
|
14
|
+
/** Watchdog observations not kept yet: their callback's incident may still come (`settle`). */
|
|
15
|
+
private readonly unsettled;
|
|
12
16
|
private readonly loops;
|
|
13
17
|
private recent;
|
|
14
18
|
/** The last hour of each loop's 5 s samples (`raw.samples` of its `event-loop-lag` events). */
|
|
@@ -17,8 +21,12 @@ export declare class EventLoopIndex {
|
|
|
17
21
|
/** Every sample an event carried, to be kept: the store skips what it holds already. */
|
|
18
22
|
onSamples?: (loop: EventLoopIdentity, samples: EventLoopSample[]) => void);
|
|
19
23
|
ingest(e: BaseEvent): void;
|
|
24
|
+
private keep;
|
|
25
|
+
/** Keeps each watchdog observation no callback's incident claimed within {@link HEARTBEAT_SETTLE_MS} of its last word. */
|
|
26
|
+
settle(now?: number): void;
|
|
20
27
|
private attach;
|
|
21
28
|
statuses(now?: number): EventLoopStatus[];
|
|
29
|
+
/** With a flow: the stalls that ran its code or overlapped it (`flowStalls` reads them apart), never LensMCP's own work. */
|
|
22
30
|
list(flowId?: string): EventLoopIncident[];
|
|
23
31
|
}
|
|
24
32
|
export declare function setFlowLoopIncidents(read: (flowId: string) => EventLoopIncident[]): void;
|
package/lib/event-loop.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var v=(s,e)=>q(s,"name",{value:e,configurable:!0});var C=Object.defineProperty,l=v((s,e)=>C(s,"name",{value:e,configurable:!0}),"l");import{lensOwnWork as T}from"@lensmcp/protocol-types";import{LoopSampleRing as z,parseLoopSamples as j}from"./event-loop-history.js";const M=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"object"),i=l(s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0,"number"),a=l((s,e=250)=>typeof s=="string"&&s?s.slice(0,e):void 0,"text"),S=40;export function eventLoopIdentity(s){const e=M(s),t=a(e.id),o=a(e.project);if(!(!t||!o||e.runtime!=="node"&&e.runtime!=="browser"))return{id:t,project:o,runtime:e.runtime,...i(e.pid)!==void 0?{pid:i(e.pid)}:{},...i(e.threadId)!==void 0?{threadId:i(e.threadId)}:{},...a(e.tabId)?{tabId:a(e.tabId)}:{},...a(e.loadId)?{loadId:a(e.loadId)}:{}}}v(eventLoopIdentity,"eventLoopIdentity"),l(eventLoopIdentity,"eventLoopIdentity");export function eventLoopIncident(s){const e=M(s.raw);if(e.kind!=="event-loop-stall")return;const t=eventLoopIdentity(e.loop),o=i(e.startedAt),c=i(e.durationMs),n=e.mechanism;if(!t||o===void 0||c===void 0||!["callback","heartbeat","long-animation-frame","longtask"].includes(String(n)))return;const g=e.state==="unresponsive"?"unresponsive":e.state==="unknown"?"unknown":"recovered",m=[];for(const k of Array.isArray(e.scripts)?e.scripts.slice(0,8):[]){const u=M(k),r=a(u.url,512);r&&m.push({url:r,durationMs:i(u.durationMs)??0,startAt:i(u.startAt)??o,...a(u.functionName)?{functionName:a(u.functionName)}:{},...a(u.invoker)?{invoker:a(u.invoker)}:{}})}const f=a(e.cause,64),b=i(e.lensMs),A=i(e.deferredMs),h=T({durationMs:c,...f?{cause:f}:{},...b!==void 0?{lensMs:b}:{}}),I=n==="callback"&&!h?a(s.context?.flowId):void 0,w=h?void 0:a(s.context?.requestId);return{id:a(e.incidentId)??s.id,loop:t,startAt:o,durationMs:c,observedAt:s.timestamp,...g==="recovered"?{endAt:o+c}:{},state:g,mechanism:n,severity:h?"info":c>=1e3?"error":"warning",...I?{flowId:I}:{},...w?{requestId:w}:{},...a(e.callbackType)?{callbackType:a(e.callbackType)}:{},...f?{cause:f}:{},...b!==void 0?{lensMs:b}:{},...A?{deferredMs:A}:{},scripts:m,evidence:[],evidenceTruncated:e.scriptsTruncated===!0||(i(e.droppedIncidents)??0)>0||(i(e.floodSuppressed)??0)>0,explanation:h?`${h}. The pause is the lens's, not the app's: no flow ran it. What overlapped it waited behind it.`:n==="callback"?"Synchronous callback wall time, including any GC or process descheduling. Execution context identifies the flow; overlapping operations are not proven causes.":n==="heartbeat"?"The loop missed its heartbeat. The observer cannot identify executing code; overlapping work may have been delayed.":"Browser-measured main-thread work. Script timings identify contributing scripts where supported; overlapping flows are associated by time only."}}v(eventLoopIncident,"eventLoopIncident"),l(eventLoopIncident,"eventLoopIncident");export const HEARTBEAT_SETTLE_MS=5e3;const L=l(s=>s.endAt??Math.max(s.observedAt,s.startAt+s.durationMs),"endOf");function x(s,e){return s.loop.id!==e.loop.id||e.durationMs<=0?!1:Math.min(L(s),L(e))-Math.max(s.startAt,e.startAt)>=e.durationMs/2}v(x,"T"),l(x,"sameStall");export class EventLoopIndex{static{v(this,"EventLoopIndex")}static{l(this,"EventLoopIndex")}constructor(e=()=>{},t=()=>{}){this.onChange=e,this.onSamples=t,this.incidents=new Map,this.unsettled=new Set,this.loops=new Map,this.recent=[],this.history=new z}ingest(e){const t=M(e.raw),o=a(t.kind)??e.source,c=eventLoopIdentity(t.loop);if(c){const r=this.loops.get(c.id);if(!r||e.timestamp>=r.lastSeen)for(this.loops.set(c.id,{loop:c,lastSeen:e.timestamp,state:t.state==="unresponsive"?"unresponsive":t.state==="unknown"?"unknown":"observed",coverage:a(t.coverage,500)??r?.coverage??(c.runtime==="node"?"Instrumented Node thread":"Browser main thread; supported PerformanceObserver entries"),...r?{meanMs:r.meanMs,maxMs:r.maxMs,p99Ms:r.p99Ms,utilization:r.utilization}:{},...i(t.lagMs)!==void 0?{meanMs:i(t.lagMs),maxMs:i(t.maxMs),p99Ms:i(t.p99Ms),utilization:i(t.utilization)}:{}});this.loops.size>200;)this.loops.delete(this.loops.keys().next().value);if(o==="event-loop-lag"){const d=j(t.samples);d.length&&(this.history.add(c,d),this.onSamples(c,d))}}const n=eventLoopIncident(e);if(n){if(this.settle(e.timestamp),n.mechanism==="heartbeat"){const d=[...this.incidents.values()].find(p=>p.mechanism==="callback"&&x(p,n));if(d){d.heartbeatMs!==n.durationMs&&(d.heartbeatMs=n.durationMs,this.onChange(d));return}}const r=this.incidents.get(n.id);if(r&&r.observedAt>n.observedAt)return;if(r&&(n.evidence=r.evidence.slice(),n.evidenceTruncated||=r.evidenceTruncated),n.mechanism==="callback")for(const[d,p]of this.incidents)p.mechanism!=="heartbeat"||!x(n,p)||(n.heartbeatMs=Math.max(n.heartbeatMs??0,p.durationMs),n.evidence=[...new Map([...p.evidence,...n.evidence].map(y=>[y.eventId,y])).values()].slice(0,S),n.evidenceTruncated||=p.evidenceTruncated,this.unsettled.delete(d)||(n.id=d,n.observedAt=Math.max(n.observedAt,p.observedAt+1)),this.incidents.delete(d));for(const d of this.recent)this.attach(n,d);for(this.incidents.set(n.id,n);this.incidents.size>200;){const d=this.incidents.keys().next().value;this.keep(d),this.incidents.delete(d)}n.mechanism==="heartbeat"?this.unsettled.add(n.id):this.onChange(n);return}if(o.startsWith("event-loop-"))return;const g=a(t.loopId);if(!g)return;const m=M(t.span),f=M(t.request),b=M(t.render),A=i(t.durationMs)??i(m.durationMs)??i(f.durationMs)??i(b.actualDurationMs)??0,h=i(t.startedAt)??i(m.startTime)??i(f.startedAt)??e.timestamp-A,I=i(m.syncDurationMs),w=i(m.syncStartedAt),k=I!==void 0&&I>=50&&w!==void 0,u={loopId:g,eventId:e.id,title:(e.title??o).slice(0,250),kind:o,startAt:k?w:h,endAt:k?w+I:h+A,...e.context?.flowId?{flowId:e.context.flowId}:{},...e.context?.requestId?{requestId:e.context.requestId}:{},relation:k?"executing":"overlap"};this.recent.push(u),this.recent.length>2e3&&this.recent.splice(0,this.recent.length-2e3);for(const r of this.incidents.values())this.attach(r,u)&&!this.unsettled.has(r.id)&&this.onChange(r)}keep(e){const t=this.incidents.get(e);t&&this.unsettled.delete(e)&&this.onChange(t)}settle(e=Date.now()){for(const t of[...this.unsettled]){const o=this.incidents.get(t);(!o||e-o.observedAt>=HEARTBEAT_SETTLE_MS)&&this.keep(t),o||this.unsettled.delete(t)}}attach(e,t){if(t.loopId!==e.loop.id||t.endAt<e.startAt||t.startAt>(e.endAt??e.observedAt)||e.evidence.some(n=>n.eventId===t.eventId))return!1;if(e.evidence.length>=S){const n=!e.evidenceTruncated;return e.evidenceTruncated=!0,n}const{loopId:o,...c}=t;return e.evidence.push(c),!0}statuses(e=Date.now()){return[...this.loops.values()].map(t=>({...t,state:e-t.lastSeen>9e4?"unknown":t.state})).sort((t,o)=>o.lastSeen-t.lastSeen)}list(e){return[...this.incidents.values()].filter(t=>!e||!T(t)&&(t.flowId===e||t.evidence.some(o=>o.flowId===e))).sort((t,o)=>o.startAt-t.startAt)}}let E=l(()=>[],"readIncidents");export function setFlowLoopIncidents(s){E=s}v(setFlowLoopIncidents,"setFlowLoopIncidents"),l(setFlowLoopIncidents,"setFlowLoopIncidents");export function flowLoopIncidents(s){return E(s)}v(flowLoopIncidents,"flowLoopIncidents"),l(flowLoopIncidents,"flowLoopIncidents");
|
package/lib/flow-shape.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type QueueSignal } from './queue-signals.js';
|
|
1
2
|
import { type BaseEvent } from '@lensmcp/protocol-types';
|
|
2
3
|
/**
|
|
3
4
|
* Architectural area of one flow event — the swimlane it renders in, and a
|
|
@@ -71,7 +72,8 @@ export declare function trimFlowEvent(event: BaseEvent, opts?: FlowShapeOptions)
|
|
|
71
72
|
role?: string | undefined;
|
|
72
73
|
captured?: string[] | undefined;
|
|
73
74
|
error?: string | undefined;
|
|
74
|
-
|
|
75
|
+
signal?: QueueSignal | undefined;
|
|
76
|
+
outcome?: "returned" | "threw" | "signalled" | undefined;
|
|
75
77
|
calleeRequestId?: string | undefined;
|
|
76
78
|
hop?: true | undefined;
|
|
77
79
|
source: "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "react" | "valtio" | "nestjs" | "nextjs" | "db" | "redis" | "queue" | "memory" | "visual" | "perf" | "security" | "gateway" | "external" | "ai" | "lens" | "custom";
|
|
@@ -82,6 +84,8 @@ export declare function trimFlowEvent(event: BaseEvent, opts?: FlowShapeOptions)
|
|
|
82
84
|
area: FlowArea;
|
|
83
85
|
jobId?: string | undefined;
|
|
84
86
|
queue?: string | undefined;
|
|
87
|
+
broker?: string | undefined;
|
|
88
|
+
db?: string | undefined;
|
|
85
89
|
valuesId?: string | undefined;
|
|
86
90
|
method?: string;
|
|
87
91
|
/** The route template (`/companies/:id`): the framework's own when it says, else the path with its ids folded. */
|
|
@@ -145,7 +149,8 @@ export declare function buildFlowDetail(rawEvents: BaseEvent[], opts?: FlowShape
|
|
|
145
149
|
role?: string | undefined;
|
|
146
150
|
captured?: string[] | undefined;
|
|
147
151
|
error?: string | undefined;
|
|
148
|
-
|
|
152
|
+
signal?: QueueSignal | undefined;
|
|
153
|
+
outcome?: "returned" | "threw" | "signalled" | undefined;
|
|
149
154
|
calleeRequestId?: string | undefined;
|
|
150
155
|
hop?: true | undefined;
|
|
151
156
|
source: "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "react" | "valtio" | "nestjs" | "nextjs" | "db" | "redis" | "queue" | "memory" | "visual" | "perf" | "security" | "gateway" | "external" | "ai" | "lens" | "custom";
|
|
@@ -156,6 +161,8 @@ export declare function buildFlowDetail(rawEvents: BaseEvent[], opts?: FlowShape
|
|
|
156
161
|
area: FlowArea;
|
|
157
162
|
jobId?: string | undefined;
|
|
158
163
|
queue?: string | undefined;
|
|
164
|
+
broker?: string | undefined;
|
|
165
|
+
db?: string | undefined;
|
|
159
166
|
valuesId?: string | undefined;
|
|
160
167
|
method?: string;
|
|
161
168
|
/** The route template (`/companies/:id`): the framework's own when it says, else the path with its ids folded. */
|
package/lib/flow-shape.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var St=Object.defineProperty;var P=(i,g)=>St(i,"name",{value:g,configurable:!0});var Bt=Object.defineProperty,v=P((i,g)=>Bt(i,"name",{value:g,configurable:!0}),"y");import{redactDeep as At,redactText as at,redactUrlParams as Rt}from"./redact.js";import{templatisePath as $t}from"./route-template.js";import{SQL_ACCOUNT_KIND as Tt,sqlAccountingOf as Pt,stallsAfterResponse as Dt}from"./flow-segments.js";import{isServiceHopHost as yt}from"./service-hop.js";import{boundedClone as Ct}from"@lensmcp/protocol-types";export function areaOf(i){const{source:g,category:s,title:I,kind:l}=i;return g==="ai"?"ai":g==="perf"&&l==="event-loop-stall"?"services":l?.startsWith("memory")||l==="db-query"?"data":g==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":g==="db"||g==="redis"||g==="queue"||l==="redis-op"||l?.startsWith("queue-")||g==="fs"||l==="fs-ops"?"data":g==="exec"||l==="exec"||l==="egress"&&yt(i.host)?"services":g==="external"||l==="egress"?"network":g==="nestjs"||g==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(I)?"data":"services":g==="valtio"?"state":s==="network"?"network":"browser"}P(areaOf,"areaOf"),v(areaOf,"areaOf");const vt=240,Nt=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Ft=new Set(["tenantId","caller","userId","accountId","email","subject"]),Ot=8;function kt(i){const g=rt(i,0);return Ct(At({redacted:!0,...g}),{rawByteLimit:16*1024}).value}P(kt,"Ee"),v(kt,"aiProjection");function rt(i,g){if(typeof i=="string")return wt(i);if(i===null||typeof i!="object")return i;if(g>=Ot)return;if(Array.isArray(i))return i.slice(0,32).map(I=>rt(I,g+1));const s={};for(const[I,l]of Object.entries(i))if(!Ft.has(I)){if(Nt.has(I)){typeof l=="string"?s[`${I}Chars`]=l.length:Array.isArray(l)?s[`${I}Count`]=l.length:l!=null&&(s[`${I}Present`]=!0);continue}s[I]=rt(l,g+1)}return s}P(rt,"ae"),v(rt,"projectAi");function wt(i){return i.length<=vt?at(i):`${at(i.slice(0,vt))}\u2026`}P(wt,"Ne"),v(wt,"clipText");export function httpFacts(i,g){const s=v(q=>typeof q=="string"&&q.length>0?q:void 0,"str"),I=typeof g.status=="number"?g.status:void 0,l=v(q=>Rt(q.split("?")[0]??q)||"/","pathOf"),N=v((q,b,k={})=>({...q?{method:q.toUpperCase()}:{},...b?{rawPath:b,route:$t(b)}:{},...I!==void 0?{status:I}:{},...k}),"facts");if(i==="gateway-request"){const q=s(g.url);return N(s(g.method),q?l(q):void 0,{...s(g.host)?{host:s(g.host)}:{},...s(g.caller)?{caller:s(g.caller)}:{}})}if(i==="egress"){const q=s(g.path),b=s(g.exchangeId);return N(s(g.method)??"GET",q?l(q):void 0,{...s(g.host)?{host:s(g.host)}:{},...b?{exchangeId:b}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const q=s(g.href)??s(g.url);let b,k;if(q)try{const p=new URL(q,"http://relative.invalid");b=l(p.pathname),p.hostname!=="relative.invalid"&&(k=p.hostname)}catch{}return N(s(g.method)??"GET",b,k?{host:k}:{})}if(i==="ai-call")return{...I!==void 0?{status:I}:{},...g.stream===!0?{streamed:!0}:{}};const f=g.request;if(f&&typeof f=="object"){const q=f,b=s(q.route),k=s(q.method);if(!b&&!k)return{};const p=typeof q.status=="number"?q.status:void 0,F=b?l(b):void 0;return{...k?{method:k.toUpperCase()}:{},...F?{rawPath:F,route:F.includes(":")?F:$t(F)}:{},...p!==void 0?{status:p}:{}}}return{}}P(httpFacts,"httpFacts"),v(httpFacts,"httpFacts");export function trimFlowEvent(i,g={}){const s=i.raw??{},I=s.render??{},l=s.span??{},N=s.request??{},f=v(d=>typeof d=="number"?d:void 0,"num"),q=s.loop??{},b=s.effect??{},k=f(s.durationMs)??f(l.durationMs)??f(N.durationMs)??f(q.durationMs)??f(I.actualDurationMs)??f(b.durationMs),p=typeof s.kind=="string"?s.kind:void 0,F=p==="fetch-done"||p==="fetch-error",E=f(I.commitTime),X=p==="render"&&E!==void 0&&Math.abs(E-i.timestamp)<6e4,_=F?i.timestamp:X?E:f(s.startedAt)??f(l.startTime)??f(N.startedAt)??f(q.startedAt)??(k!==void 0?i.timestamp-k:i.timestamp);let x;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",m=typeof s.result=="string"?` \u2192 ${s.result}`:"";x=s.query+d+m}else if(typeof s.command=="string"){const d=typeof s.value=="string"?` \u2192 ${s.value}`:s.hit===!1?" \u2192 (miss)":"";x=s.command+d}else if(p==="state-update"){const d=s.update??{};let m="";try{m=JSON.stringify(d.preview)}catch{}x=`${d.storeId??""}.${d.path??""} = ${m}`}else if(p==="fs-ops"&&Array.isArray(s.paths))x=s.paths.slice(0,8).map(d=>{const m=d??{},B=typeof m.n=="number"&&m.n>1?` \xD7${m.n}`:"",T=typeof m.bytes=="number"&&m.bytes>0?` (${m.bytes>=1024?`${(m.bytes/1024).toFixed(1)} KB`:`${m.bytes} B`})`:"";return`${String(m.op??"?")} ${String(m.path??"?")}${B}${T}`}).join(" \xB7 ");else if(p==="exec"&&typeof s.cmd=="string")x=`${s.cmd} \u2192 ${s.code??s.signal??s.error??"?"}`;else if(p==="queue-completed"&&typeof s.returned=="string")x=`returned ${s.returned}`;else if(p==="queue-enqueued")x=`${s.job??"job"}#${s.jobId??"?"} \u2192 ${s.queue??""}${typeof s.data=="string"?" "+s.data:""}`;else if(p==="log"){const d=N.error??{},m=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;m&&m!==i.title&&(x=m)}let L,z,U,V;if(p==="span"){const d=l.outcome;if(L=d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,L==="threw"){const T=l.error??{},y=typeof T.name=="string"?T.name:void 0,G=typeof T.message=="string"?T.message:typeof i.message=="string"?i.message:void 0;U=y,z=at([y,G].filter(Boolean).join(": "))||void 0}const m=typeof l.args=="string"?l.args:void 0,B=typeof l.result=="string"?l.result:void 0;if(m!==void 0||B!==void 0){V=[...m!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const T=v(y=>y.length>Mt?`${y.slice(0,Mt)}\u2026`:y,"short");x=[m!==void 0?`args ${T(m)}`:"",B!==void 0?`returned ${T(B)}`:""].filter(Boolean).join(" \u2192 ")}}let W;if(p==="gateway-request")W=`${s.host??""}${String(s.url??"").split("?")[0]}`;else if(p==="fetch-start"||p==="fetch-done"||p==="fetch-error")try{const d=new URL(String(s.href??s.url??""));W=`${d.hostname}${d.pathname}`}catch{}let K;if(p==="gateway-request"&&Array.isArray(s.steps))K=s.steps.map(d=>{const m=[String(d.step)];return d.project&&m.push(String(d.project)),d.prefix&&m.push(String(d.prefix)),d.mode&&m.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&m.push("by "+String(d.caller)),d.pod&&m.push(String(d.pod)),typeof d.atMs=="number"&&m.push(`@${d.atMs}ms`),m.join(" ")}),x=K.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")x=`${s.method??"GET"} ${s.host??""} \u2192 ${s.status??"?"}`;else if(i.source==="ai"){if(p==="ai-call"){const d=s.usage??{},m=d.promptTokens!==void 0||d.completionTokens!==void 0?` \xB7 ${f(d.promptTokens)??"?"}\u2192${f(d.completionTokens)??"?"} tok`:"",B=s.status!==void 0?` \xB7 ${String(s.status)}`:s.error?" \xB7 failed":"",T=f(s.toolCallCount)?` \xB7 ${f(s.toolCallCount)} tool call${f(s.toolCallCount)===1?"":"s"}`:"",y=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.provider??""}/${s.model??"?"}${m}${B}${T}${y}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},m=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],T=`${f(m.promptTokens)??"?"}\u2192${f(m.completionTokens)??"?"} tok`,y=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",G=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.provider??""}/${d.model??""} \xB7 ${T}${y}${G}`}else if(p==="ai-turn-start"){const d=Array.isArray(s.tools)?s.tools:[];x=`skill ${s.skill??""} \xB7 ${s.output??""}${d.length?" \xB7 tools: "+d.join(", "):""}`}else if(p==="ai-tool-call"){const d=s.call??{},m=s.result??{},B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.name??"tool"} ${m.error!=null?"\u2717 "+String(m.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},m=f(s.rounds)!==void 0?` \xB7 ${f(s.rounds)} round${f(s.rounds)===1?"":"s"}`:"",B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.ok===!1?"FAILED":"ok"} \xB7 ${f(d.promptTokens)??"?"}+${f(d.completionTokens)??"?"} tok${m}${B}`}}let R;p==="db-query"&&typeof s.query=="string"?R=s.query:p==="redis-op"?R=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?R=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?R=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?R=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?R=l.name:p==="memory-mutation"&&(R=i.title);const O=i.context??{},Q=I.commitId??b.commitId??s.commitId,Y=Array.isArray(I.why)?I.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:_,...R?{sig:R}:{},...W?{urlKey:W}:{},...httpFacts(p,s),...(p==="db-query"||p==="redis-op")&&typeof s.valuesId=="string"?{valuesId:s.valuesId}:{},...typeof s.queue=="string"?{queue:s.queue}:{},...s.jobId!=null?{jobId:String(s.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:L==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${U?` ${U}`:""}${k!==void 0?` after ${k}ms`:""}`:i.title,kind:p,area:areaOf({source:i.source,category:i.category,title:i.title,kind:p,...typeof s.host=="string"?{host:s.host}:{}}),...p==="egress"&&yt(typeof s.host=="string"?s.host:void 0)?{hop:!0}:{},...p==="egress"&&typeof s.calleeRequestId=="string"?{calleeRequestId:s.calleeRequestId}:{},...L?{outcome:L}:{},...z?{error:z}:{},...V?{captured:V}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...p==="log"&&typeof s.level=="string"?{level:s.level}:{},...p==="log"&&typeof s.logger=="string"?{logger:s.logger}:{},...p==="log"&&typeof s.stream=="string"?{stream:s.stream}:{},...typeof O.requestId=="string"?{requestId:O.requestId}:{},...typeof O.parentRequestId=="string"?{parentRequestId:O.parentRequestId}:{},...typeof Q=="string"?{commitId:Q}:{},...typeof I.componentName=="string"?{component:I.componentName}:{},...typeof I.phase=="string"?{phase:I.phase}:{},...Y.length?{why:Y}:{},...p==="effect-run"&&typeof b.hookLogicalId=="string"?{hook:b.hookLogicalId}:{},...p==="effect-run"&&b.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:f(s.total),renderPublished:f(s.published),...f(s.walkStoppedAt)!==void 0?{renderWalkStoppedAt:f(s.walkStoppedAt)}:{}}:{},...typeof O.projectName=="string"?{project:O.projectName}:typeof s.project=="string"?{project:s.project}:{},...k!==void 0?{durationMs:k}:{},...F&&f(s.startedAt)!==void 0?{fetchStartedAt:f(s.startedAt)}:{},...i.source==="ai"?{ai:g.includeRaw?s:kt(s)}:{},...x?{detail:x}:{},...K?{steps:K}:{}}}P(trimFlowEvent,"trimFlowEvent"),v(trimFlowEvent,"trimFlowEvent");const Mt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Et=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),it=1;function qt(i){return i==="flow-origin"?0:i?.endsWith("-start")?1:i==="gateway-request"?2:i==="server-request"?3:i==="span"?4:i==="render"||i==="render-commit-truncated"?6:i==="effect-run"?7:5}P(qt,"_e"),v(qt,"kindRank");function J(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:qt(i.kind)}P(J,"X"),v(J,"causalRank");export function buildFlowDetail(i,g={}){const s=Pt(i),I=Dt(i),l=i.slice().filter(t=>{const r=t.raw??{},e=typeof r.kind=="string"?r.kind:"";if(e==="subscription-added"||e==="subscription-removed"||e==="hook-run"||e==="store-created"||e==="singleton-instance"||e===Tt)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,g)),N=new Set;for(let t=l.length-1;t>=0;t--)N.has(l[t].id)?l.splice(t,1):N.add(l[t].id);const f=new Map;for(const t of l)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!f.has(t.requestId)&&f.set(t.requestId,t.start);const q=v(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&f.has(t.requestId)?f.get(t.requestId):t.start,"anchorOf");l.sort((t,r)=>q(t)-q(r)||t.start-r.start||J(t)-J(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const b=v(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),k=l;for(const t of k)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const p=new Map;for(const t of k)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=p.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),p.set(t.requestId,r)}const F=v((t,r)=>{const e=p.get(t);if(e?.length)return e.every(o=>o.project===e[0].project)?e[0].project:e.filter(o=>o.start<=r+1&&o.end>=r-1).sort((o,n)=>n.start-o.start)[0]?.project},"projectOf");for(const t of k)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=F(t.requestId,t.start);r&&(t.project=r)}const E=new Map;for(const t of k)t.spanId&&E.set(t.spanId,t);const X=v((t,r)=>{let e=t.parentSpanId?E.get(t.parentSpanId):void 0;for(let o=0;e&&o<64;o++){if(e===r)return!0;e=e.parentSpanId?E.get(e.parentSpanId):void 0}return!1},"inside"),_=new Map(k.map((t,r)=>[t,r])),x=new Map,L=v(t=>{let r=x.get(t.group);r||x.set(t.group,r=new Map);const e=t.requestId;let o=r.get(e);return o||r.set(e,o={spans:[],next:0,alive:[]}),o},"legOf");for(const t of k)b(t)&&Number.isFinite(t.start)&&L(t).spans.push(t);for(const t of x.values())for(const r of t.values())r.spans.sort((e,o)=>e.start-o.start||_.get(e)-_.get(o));const z=v(t=>Number.isFinite(t.start)?t.start:1/0,"startOf");for(const t of k.slice().sort((r,e)=>z(r)-z(e))){const r=t.parentSpanId?E.get(t.parentSpanId):void 0;if(r&&r!==t&&r.group===t.group&&r.requestId===t.requestId){t.parent=r.id;continue}if(!Number.isFinite(t.start))continue;const e=L(t);for(;e.next<e.spans.length&&e.spans[e.next].start<=t.start+it;)e.alive.push(e.spans[e.next++]);e.alive=e.alive.filter(a=>a.start+(a.durationMs??0)>t.start);const o=e.alive.length>1?e.alive.slice().sort((a,h)=>_.get(a)-_.get(h)):e.alive;let n;for(const a of o){if(a===t)continue;const h=a.project,w=t.project;if(a.kind!=="gateway-request"&&t.kind!=="gateway-request"&&h!==void 0&&w!==void 0&&h!==w)continue;const u=a.durationMs??0,c=t.durationMs??0,$=Math.abs(a.start-t.start)<=it,M=J(a),A=J(t),j=a.start<=t.start;if(!(a.start+u>t.start&&(j||$&&M<A)&&(!$||(M!==A?M<A:j&&u>c))))continue;const C=n?J(n):-1,D=n?Math.abs(a.start-n.start)<=it:!1,H=n&&D&&M===C?X(a,n)?1:X(n,a)?-1:0:0;(!n||!D&&a.start>n.start||D&&M>C||H>0||H===0&&D&&M===C&&(a.durationMs??0)<(n.durationMs??0))&&(n=a)}n&&(t.parent=n.id)}for(const t of k)delete t.spanId,delete t.parentSpanId;{const t=new Set(k.map(a=>a.id)),r=new Set,e=new Map,o=[],n=v(a=>{const h=[a];for(;h.length;){const w=h.pop();o.push(w),r.add(w.id);const u=e.get(w.id);if(u){e.delete(w.id);for(let c=u.length-1;c>=0;c--)h.push(u[c])}}},"place");for(const a of k)if(a.parent&&a.parent!==a.id&&t.has(a.parent)&&!r.has(a.parent)){const h=e.get(a.parent)??[];h.push(a),e.set(a.parent,h)}else n(a);for(const a of k)r.has(a.id)||(o.push(a),r.add(a.id));for(let a=0;a<o.length;a++)k[a]=o[a]}const U=new Map;for(const t of k){if(!t.requestId)continue;const r=U.get(t.requestId);r?r.push(t):U.set(t.requestId,[t])}const V=new Map(k.map(t=>[t.id,t])),W=new Map;for(const t of k)t.calleeRequestId&&!W.has(t.calleeRequestId)&&W.set(t.calleeRequestId,t);const K=v((t,r)=>{const e=(U.get(t)??[]).filter(o=>b(o)&&o.start<=r&&o.start+(o.durationMs??0)>=r);if(e.length!==0)return e.sort((o,n)=>n.start-o.start||(o.durationMs??0)-(n.durationMs??0)),e[0]},"callerNodeFor");for(const t of k){if(!t.parentRequestId||t.kind!=="server-request"&&t.kind!=="gateway-request")continue;const r=t.parent?V.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=t.requestId?W.get(t.requestId):void 0,o=e&&e.start<=t.start?e:K(t.parentRequestId,t.start);o&&o!==t&&o.start<=t.start&&(t.parent=o.id)}const R=k,O=new Map;for(const t of R)t.kind==="gateway-request"&&t.requestId&&!O.has(t.requestId)&&O.set(t.requestId,t);for(const t of R)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=O.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const Q=new Set,Y=new Set,d=[];for(const t of R){if(t.kind!=="gateway-request")continue;if(!t.requestId){d.push(t);continue}const r=U.get(t.requestId)??[];if(r.filter(n=>n.kind==="gateway-request").sort((n,a)=>n.start-a.start)[0]!==t)continue;const e=r.find(n=>n.kind==="fetch-start"),o=r.find(n=>n.kind==="fetch-done"||n.kind==="fetch-error");if(!e&&!o){d.push(t);continue}e&&(t.fetchStartId=e.id,Q.add(e.id)),o&&(t.fetchDoneId=o.id,Y.add(o.id))}const m=new Map;for(const t of R){if(!t.urlKey)continue;const r=m.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?d.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?Q.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(Y.has(t.id)||r.dones.push(t)),m.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of m.values()){t.sort((n,a)=>n.start-a.start),r.sort((n,a)=>n.start-a.start);const o=new Set;t.forEach((n,a)=>{const h=r[a];h&&(n.fetchStartId=h.id);const w=h?h.t:n.start;let u,c=1/0;for(const $ of e){if(o.has($.id))continue;const M=$.fetchStartedAt??$.start-($.durationMs??0),A=Math.abs(M-w);A<c&&(c=A,u=$)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const B=new Map,T=new Map;for(const t of R)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&B.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&T.set(`${t.queue}#${t.jobId}`,t));for(const t of R){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=B.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}else if(t.kind==="queue-active"||t.kind==="queue-completed"||t.kind==="queue-failed"){const e=T.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}}{const t=new Map(k.map(r=>[r.id,r]));for(const r of k){if(!r.parent||!Et.has(r.kind??"")||r.durationMs===void 0)continue;const e=t.get(r.parent);if(!e||e.kind!=="span"||!((e.durationMs??0)>0))continue;const o=Math.round(r.start+r.durationMs-(e.start+e.durationMs));if(o<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=o;const n=e.leftRunning??{count:0,longestMs:0};e.leftRunning={count:n.count+1,longestMs:Math.max(n.longestMs,o)}}for(const r of k){const e=[];r.leftRunning&&e.push(`ended before ${r.leftRunning.count===1?"a call":`${r.leftRunning.count} calls`} it started had finished \u2014 ${r.leftRunning.count===1?"it":"the longest"} ran on ${r.leftRunning.longestMs}ms (a timeout that gave up, or work not awaited)`),r.outlivedParentMs!==void 0&&e.push(`ran on ${r.outlivedParentMs}ms after the span that started it had ended`),e.length>0&&(r.detail=[r.detail,...e].filter(Boolean).join(" \xB7 "))}}if(I.size>0)for(const t of k){const r=I.get(t.id);r!==void 0&&(t.afterResponseMs=r,t.detail=[t.detail,`began ${r}ms after the request's response had finished \u2014 not part of the request's time`].filter(Boolean).join(" \xB7 "))}let y=k;{const t=new Map;for(const e of y)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of y){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const o=[...t.values()].find(h=>h.requestId&&h.requestId===e.requestId)?.id,n=o?t.get(o):void 0;if(!n)continue;const a=e.fetchStartedAt??n.start;n.title=e.title,n.severity=e.severity,n.durationMs=e.durationMs??Math.max(0,e.t-a),n.kind="fetch",e.detail&&!n.detail&&(n.detail=e.detail),r.set(e.id,n.id)}if(r.size>0){y=y.filter(e=>!r.has(e.id));for(const e of y)for(e.fetchDoneId&&r.has(e.fetchDoneId)&&(e.fetchDoneId=r.get(e.fetchDoneId));e.parent&&r.has(e.parent);)e.parent=r.get(e.parent)}}const G=v(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),st=v(t=>[...new Set(t)],"uniq"),ot=v(t=>st(t.map(r=>r.component).filter(r=>!!r)),"named"),It=v(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),dt=v(t=>{const r=new Map;for(const e of t)e.component&&r.set(e.component,(r.get(e.component)??0)+1);return[...r].map(([e,o])=>o>1?`${e} \xD7${o}`:e).join(", ")},"tally"),bt=v(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),nt=v(t=>`${bt(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),ut=v(t=>{const r=Math.min(...t.map(o=>o.start)),e=Math.max(...t.map(o=>o.start+(o.durationMs??0)));return{start:r,durationMs:e-r}},"extent"),ct=v(t=>(delete t.component,delete t.why,delete t.phase,delete t.hook,delete t.cleanup,delete t.renderTotal,delete t.renderPublished,t),"asGroup");function lt(t){const r=t[0],e=t.filter(S=>S.kind==="render"),o=t.filter(S=>S.kind==="effect-run"),n=t.find(S=>S.kind==="render-commit-truncated"),a=[...e].sort((S,Z)=>(Z.durationMs??0)-(S.durationMs??0)),h=a.filter(S=>(S.why??[]).some(Z=>Z!=="parent-render")),w=st(h.flatMap(S=>(S.why??[]).filter(Z=>Z!=="parent-render"))),u=ot(h),c=e.filter(S=>S.phase==="mount"),$=e.filter(S=>S.phase!=="mount"&&!h.includes(S)),M=a[0]?.component??"view",A=e.length>0&&c.length===e.length,j=w.length?w.join(" + "):void 0,C=A?"mount":"update",D=u.length?`view update \xB7 ${It(u)} \u2190 ${j}`:A?`view mount \xB7 ${M}`:`view update \xB7 ${M}`,H=n?.renderTotal??e.length,jt=[c.length?`mounted ${dt(c)}`:"",$.length?`re-rendered ${dt($)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${H} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??e.length} recorded`:n?`${H} renders, ${n.renderPublished??e.length} recorded (per-commit cap)`:`${e.length} render${e.length===1?"":"s"}`,o.length?`${o.length} effect${o.length===1?"":"s"}: ${o.map(nt).join(", ")}`:""].filter(Boolean).join(" \xB7 "),ht=ot(e);return ct({...r,...ut(t),kind:"view-update",title:D,detail:jt,commitId:r.commitId,viewPhase:C,...j?{cause:j}:{},causeComponents:u,components:ht,mounted:ot(c),renderCount:H,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:o.length,effectHooks:o.map(nt),memberIds:t.map(S=>S.id),sig:`commit:${C}:${j??"-"}:${u.join(",")}:${ht.slice().sort().join(",")}`,severity:t.some(S=>S.severity==="error")?"error":r.severity})}P(lt,"Me"),v(lt,"viewUpdateNode");function pt(t){const r=t[0],e=t.map(nt);return ct({...r,...ut(t),kind:"commit-effects",title:t.length===1?`effect \xB7 ${e[0]}`:`effects \xB7 ${e[0]} + ${t.length-1} more`,detail:e.join(", "),commitId:r.commitId,effects:t.length,effectHooks:e,memberIds:t.map(o=>o.id),sig:`effects:${e.slice().sort().join(",")}`})}P(pt,"ke"),v(pt,"effectsNode");const xt=v(t=>st(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function ft(t,r){const e=t[0],o=t[t.length-1],n=t.length,a=e.detail,h=Math.min(...t.map($=>$.start)),w=Math.max(...t.map($=>$.start+($.durationMs??0))),u=Math.round(t.reduce(($,M)=>$+(M.durationMs??0),0)/n*10)/10,c=Math.round((w-h)*10)/10;e.count=n,e.avgMs=u,e.wallMs=c,e.durationMs=w-h,e.items=t.slice(0,12).map($=>({start:$.start-h,...$.durationMs!=null?{durationMs:$.durationMs}:{}})),e.memberIds=t.flatMap($=>$.memberIds??[$.id]),e.title=`\xD7${n} ${e.title}`,t.some($=>$.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${n} commits, ${r.length?`one per ${xt(r)}`:"back to back"}`,`avg ${u}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):e.kind==="state-update"&&a&&o.detail?e.detail=`${n} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${o.detail}`:e.detail=[`${n} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}P(ft,"we"),v(ft,"collapseRepeat");const tt=[],et=new Map,mt=new Set;for(let t=0;t<y.length;t++){if(mt.has(t))continue;const r=y[t];if(!G(r)){tt.push(r);continue}const e=[t];for(let a=t+1;a<y.length;a++){const h=y[a];if(h.group==="browser"){if(!G(h)||h.commitId!==r.commitId)break;e.push(a)}}for(const a of e)mt.add(a);const o=e.map(a=>y[a]),n=o.some(a=>a.kind!=="effect-run")?lt(o):pt(o);for(const a of o)a.id!==n.id&&et.set(a.id,n.id);tt.push(n)}if(et.size>0||tt.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){y=tt;for(const t of y)for(;t.parent&&et.has(t.parent);)t.parent=et.get(t.parent)}{const t=new Map;for(const r of y)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of y){if(r.kind!=="commit-effects"||r.parent||!r.commitId)continue;const e=t.get(r.commitId);e&&e.start<=r.start&&(r.parent=e.id)}}{const t=new Set(["state-update","fetch","fetch-start","fetch-done","fetch-error","flow-origin"]),r=y.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),e=v(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),o=r.map(u=>e(y[u])),n=v((u,c,$)=>{for(let M=0;M<$;M++)if(o[u+M]!==o[c+M])return!1;return!0},"sameBlock"),a=v(u=>o[u].split("|")[0],"kindAt"),h=v(u=>{let c=0,$=1;for(let M=1;M<=4&&u+M<=o.length;M++){let A=1;for(;u+(A+1)*M<=o.length&&n(u,u+A*M,M);)A+=1;A>=3&&M*A>c*$&&(c=M,$=A)}return{k:c,r:$}},"bestBlockAt"),w=new Map;for(let u=0;u<o.length;){const{k:c,r:$}=h(u);if(c===0){u+=1;continue}const M=[...Array(c).keys()].find(j=>t.has(a(u+j)));if(M!==void 0&&M>0){const j=h(u+M);if(j.k===c&&j.r>=3&&j.r>=$-1){u+=M;continue}}const A=o.slice(u,u+c).map(j=>j.split("|")[0]).filter(j=>t.has(j));for(let j=0;j<c;j++){const C=[];for(let D=0;D<$;D++)C.push(y[r[u+j+D*c]]);ft(C,A);for(const D of C.slice(1))w.set(D.id,C[0].id)}u+=c*$}if(w.size>0){y=y.filter(u=>!w.has(u.id));for(const u of y)for(;u.parent&&w.has(u.parent);)u.parent=w.get(u.parent)}}{const t=new Map(y.map(r=>[r.id,r]));for(const r of y){const e=new Set([r.id]);let o=r;for(;o?.parent;){if(e.has(o.parent)){o.parent=void 0;break}e.add(o.parent),o=t.get(o.parent)}}}const gt=v(t=>{const r=new Map;for(const o of y){if(!o.sig||b(o)!==t||o.kind==="server-request"||o.kind==="gateway-request"||o.group==="browser")continue;const n=`${o.parent??"root"}|${o.kind}|${o.sig}`,a=r.get(n);a?a.push(o):r.set(n,[o])}const e=new Map;for(const o of r.values()){if(o.length<3)continue;o.sort((c,$)=>c.start-$.start);const n=o[0];let a=!1;for(let c=0;c+1<o.length;c++)if(o[c+1].start<o[c].start+(o[c].durationMs??0)){a=!0;break}const h=n.start,w=Math.max(...o.map(c=>c.start+(c.durationMs??0))),u=o.reduce((c,$)=>c+($.durationMs??0),0);n.count=o.length,n.parallel=a,n.avgMs=Math.round(u/o.length*10)/10,n.wallMs=w-h,n.durationMs=w-h,n.title=`\xD7${o.length} ${n.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,n.detail=`${n.sig} \xD7${o.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${n.avgMs}ms \xB7 wall ${n.wallMs}ms`,n.items=o.slice(0,12).map(c=>({start:c.start-h,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),n.memberIds=o.flatMap(c=>c.memberIds??[c.id]),o.some(c=>c.severity==="error")&&(n.severity="error");for(const c of o.slice(1))e.set(c.id,n.id)}if(e.size!==0){y=y.filter(o=>!e.has(o.id));for(const o of y)for(;o.parent&&e.has(o.parent);)o.parent=e.get(o.parent)}},"aggregatePass");gt(!0),gt(!1);for(const t of y){if(!b(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=y.filter(w=>w.parent===t.id&&(w.durationMs??0)>0).map(w=>[w.start,w.start+(w.durationMs??0)]).sort((w,u)=>w[0]-u[0]);let o=0,n=-1,a=-1;for(const[w,u]of e)w>a?(a>n&&(o+=a-n),n=w,a=u):u>a&&(a=u);a>n&&(o+=a-n);const h=Math.max(0,r-o);(h>=50||h/r>=.7&&r>=40)&&(t.selfMs=h,t.detail=`\u26A0 cpu-heavy: ${h}ms self-time of ${r}ms${t.detail?" \xB7 "+t.detail:""}`)}return{events:y,...s?{sql:s}:{}}}P(buildFlowDetail,"buildFlowDetail"),v(buildFlowDetail,"buildFlowDetail");
|
|
1
|
+
"use strict";var Bt=Object.defineProperty;var R=(i,m)=>Bt(i,"name",{value:m,configurable:!0});var At=Object.defineProperty,k=R((i,m)=>At(i,"name",{value:m,configurable:!0}),"I");import{redactDeep as Rt,redactText as at,redactUrlParams as Tt}from"./redact.js";import{templatisePath as $t}from"./route-template.js";import{SQL_ACCOUNT_KIND as Dt,sqlAccountingOf as Ct,stallsAfterResponse as Pt}from"./flow-segments.js";import{isServiceHopHost as yt}from"./service-hop.js";import{queueSignalOf as vt,queueSignalWords as Ot}from"./queue-signals.js";import{boundedClone as Ft}from"@lensmcp/protocol-types";export function areaOf(i){const{source:m,category:s,title:I,kind:l}=i;return m==="ai"?"ai":m==="perf"&&l==="event-loop-stall"?"services":l?.startsWith("memory")||l==="db-query"?"data":m==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":m==="db"||m==="redis"||m==="queue"||l==="redis-op"||l?.startsWith("queue-")||m==="fs"||l==="fs-ops"?"data":m==="exec"||l==="exec"||l==="egress"&&yt(i.host)?"services":m==="external"||l==="egress"?"network":m==="nestjs"||m==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(I)?"data":"services":m==="valtio"?"state":s==="network"?"network":"browser"}R(areaOf,"areaOf"),k(areaOf,"areaOf");const kt=240,Nt=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Et=new Set(["tenantId","caller","userId","accountId","email","subject"]),Lt=8;function qt(i){const m=st(i,0);return Ft(Rt({redacted:!0,...m}),{rawByteLimit:16*1024}).value}R(qt,"Be"),k(qt,"aiProjection");function st(i,m){if(typeof i=="string")return wt(i);if(i===null||typeof i!="object")return i;if(m>=Lt)return;if(Array.isArray(i))return i.slice(0,32).map(I=>st(I,m+1));const s={};for(const[I,l]of Object.entries(i))if(!Et.has(I)){if(Nt.has(I)){typeof l=="string"?s[`${I}Chars`]=l.length:Array.isArray(l)?s[`${I}Count`]=l.length:l!=null&&(s[`${I}Present`]=!0);continue}s[I]=st(l,m+1)}return s}R(st,"ae"),k(st,"projectAi");function wt(i){return i.length<=kt?at(i):`${at(i.slice(0,kt))}\u2026`}R(wt,"_e"),k(wt,"clipText");export function httpFacts(i,m){const s=k(M=>typeof M=="string"&&M.length>0?M:void 0,"str"),I=typeof m.status=="number"?m.status:void 0,l=k(M=>Tt(M.split("?")[0]??M)||"/","pathOf"),F=k((M,b,y={})=>({...M?{method:M.toUpperCase()}:{},...b?{rawPath:b,route:$t(b)}:{},...I!==void 0?{status:I}:{},...y}),"facts");if(i==="gateway-request"){const M=s(m.url);return F(s(m.method),M?l(M):void 0,{...s(m.host)?{host:s(m.host)}:{},...s(m.caller)?{caller:s(m.caller)}:{}})}if(i==="egress"){const M=s(m.path),b=s(m.exchangeId);return F(s(m.method)??"GET",M?l(M):void 0,{...s(m.host)?{host:s(m.host)}:{},...b?{exchangeId:b}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const M=s(m.href)??s(m.url);let b,y;if(M)try{const p=new URL(M,"http://relative.invalid");b=l(p.pathname),p.hostname!=="relative.invalid"&&(y=p.hostname)}catch{}return F(s(m.method)??"GET",b,y?{host:y}:{})}if(i==="ai-call")return{...I!==void 0?{status:I}:{},...m.stream===!0?{streamed:!0}:{}};const f=m.request;if(f&&typeof f=="object"){const M=f,b=s(M.route),y=s(M.method);if(!b&&!y)return{};const p=typeof M.status=="number"?M.status:void 0,N=b?l(b):void 0;return{...y?{method:y.toUpperCase()}:{},...N?{rawPath:N,route:N.includes(":")?N:$t(N)}:{},...p!==void 0?{status:p}:{}}}return{}}R(httpFacts,"httpFacts"),k(httpFacts,"httpFacts");export function trimFlowEvent(i,m={}){const s=i.raw??{},I=s.render??{},l=s.span??{},F=s.request??{},f=k(d=>typeof d=="number"?d:void 0,"num"),M=s.loop??{},b=s.effect??{},y=f(s.durationMs)??f(l.durationMs)??f(F.durationMs)??f(M.durationMs)??f(I.actualDurationMs)??f(b.durationMs),p=typeof s.kind=="string"?s.kind:void 0,N=p==="fetch-done"||p==="fetch-error",W=f(I.commitTime),tt=p==="render"&&W!==void 0&&Math.abs(W-i.timestamp)<6e4,z=N?i.timestamp:tt?W:f(s.startedAt)??f(l.startTime)??f(F.startedAt)??f(M.startedAt)??(y!==void 0?i.timestamp-y:i.timestamp);let x;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",g=typeof s.result=="string"?` \u2192 ${s.result}`:"";x=s.query+d+g}else if(typeof s.command=="string"){const d=typeof s.value=="string"?` \u2192 ${s.value}`:s.hit===!1?" \u2192 (miss)":"";x=s.command+d}else if(p==="state-update"){const d=s.update??{};let g="";try{g=JSON.stringify(d.preview)}catch{}x=`${d.storeId??""}.${d.path??""} = ${g}`}else if(p==="fs-ops"&&Array.isArray(s.paths))x=s.paths.slice(0,8).map(d=>{const g=d??{},B=typeof g.n=="number"&&g.n>1?` \xD7${g.n}`:"",h=typeof g.bytes=="number"&&g.bytes>0?` (${g.bytes>=1024?`${(g.bytes/1024).toFixed(1)} KB`:`${g.bytes} B`})`:"";return`${String(g.op??"?")} ${String(g.path??"?")}${B}${h}`}).join(" \xB7 ");else if(p==="exec"&&typeof s.cmd=="string")x=`${s.cmd} \u2192 ${s.code??s.signal??s.error??"?"}`;else if(p==="queue-completed"&&typeof s.returned=="string")x=`returned ${s.returned}`;else if(p==="queue-enqueued")x=`${s.job??"job"}#${s.jobId??"?"} \u2192 ${s.queue??""}${typeof s.data=="string"?" "+s.data:""}`;else if(p==="log"){const d=F.error??{},g=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;g&&g!==i.title&&(x=g)}let U,E;p==="queue-process"&&(E=vt(s.status));let _,Y,H;if(p==="span"){const d=l.outcome;if(E=d==="signalled"?vt(l.signal):void 0,U=E?"signalled":d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,U==="threw"){const h=l.error??{},D=typeof h.name=="string"?h.name:void 0,K=typeof h.message=="string"?h.message:typeof i.message=="string"?i.message:void 0;Y=D,_=at([D,K].filter(Boolean).join(": "))||void 0}const g=typeof l.args=="string"?l.args:void 0,B=typeof l.result=="string"?l.result:void 0;if(g!==void 0||B!==void 0){H=[...g!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const h=k(D=>D.length>Mt?`${D.slice(0,Mt)}\u2026`:D,"short");x=[g!==void 0?`args ${h(g)}`:"",B!==void 0?`returned ${h(B)}`:""].filter(Boolean).join(" \u2192 ")}}let G;if(p==="gateway-request")G=`${s.host??""}${String(s.url??"").split("?")[0]}`;else if(p==="fetch-start"||p==="fetch-done"||p==="fetch-error")try{const d=new URL(String(s.href??s.url??""));G=`${d.hostname}${d.pathname}`}catch{}let P;if(p==="gateway-request"&&Array.isArray(s.steps))P=s.steps.map(d=>{const g=[String(d.step)];return d.project&&g.push(String(d.project)),d.prefix&&g.push(String(d.prefix)),d.mode&&g.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&g.push("by "+String(d.caller)),d.pod&&g.push(String(d.pod)),typeof d.atMs=="number"&&g.push(`@${d.atMs}ms`),g.join(" ")}),x=P.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")x=`${s.method??"GET"} ${s.host??""} \u2192 ${s.status??"?"}`;else if(i.source==="ai"){if(p==="ai-call"){const d=s.usage??{},g=d.promptTokens!==void 0||d.completionTokens!==void 0?` \xB7 ${f(d.promptTokens)??"?"}\u2192${f(d.completionTokens)??"?"} tok`:"",B=s.status!==void 0?` \xB7 ${String(s.status)}`:s.error?" \xB7 failed":"",h=f(s.toolCallCount)?` \xB7 ${f(s.toolCallCount)} tool call${f(s.toolCallCount)===1?"":"s"}`:"",D=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.provider??""}/${s.model??"?"}${g}${B}${h}${D}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},g=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],h=`${f(g.promptTokens)??"?"}\u2192${f(g.completionTokens)??"?"} tok`,D=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",K=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.provider??""}/${d.model??""} \xB7 ${h}${D}${K}`}else if(p==="ai-turn-start"){const d=Array.isArray(s.tools)?s.tools:[];x=`skill ${s.skill??""} \xB7 ${s.output??""}${d.length?" \xB7 tools: "+d.join(", "):""}`}else if(p==="ai-tool-call"){const d=s.call??{},g=s.result??{},B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.name??"tool"} ${g.error!=null?"\u2717 "+String(g.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},g=f(s.rounds)!==void 0?` \xB7 ${f(s.rounds)} round${f(s.rounds)===1?"":"s"}`:"",B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.ok===!1?"FAILED":"ok"} \xB7 ${f(d.promptTokens)??"?"}+${f(d.completionTokens)??"?"} tok${g}${B}`}}let T;p==="db-query"&&typeof s.query=="string"?T=s.query:p==="redis-op"?T=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?T=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?T=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?T=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?T=l.name:p==="memory-mutation"&&(T=i.title);const L=i.context??{},Z=I.commitId??b.commitId??s.commitId,Q=Array.isArray(I.why)?I.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:z,...T?{sig:T}:{},...G?{urlKey:G}:{},...httpFacts(p,s),...(p==="db-query"||p==="redis-op")&&typeof s.valuesId=="string"?{valuesId:s.valuesId}:{},...p==="db-query"&&typeof s.name=="string"&&s.name!=="postgres"?{db:s.name}:{},...p?.startsWith("queue-")&&typeof s.broker=="string"?{broker:s.broker}:{},...typeof s.queue=="string"?{queue:s.queue}:{},...s.jobId!=null?{jobId:String(s.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:U==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${Y?` ${Y}`:""}${y!==void 0?` after ${y}ms`:""}`:p==="queue-process"&&E?`process ${String(s.job??"job")}#${String(s.jobId??"?")} \u2014 ran, ${Ot(E,f(s.delayMs))}${y!==void 0?` (${y}ms)`:""}`:i.title,kind:p,area:areaOf({source:i.source,category:i.category,title:i.title,kind:p,...typeof s.host=="string"?{host:s.host}:{}}),...p==="egress"&&yt(typeof s.host=="string"?s.host:void 0)?{hop:!0}:{},...p==="egress"&&typeof s.calleeRequestId=="string"?{calleeRequestId:s.calleeRequestId}:{},...U?{outcome:U}:{},...E?{signal:E}:{},..._?{error:_}:{},...H?{captured:H}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...p==="log"&&typeof s.level=="string"?{level:s.level}:{},...p==="log"&&typeof s.logger=="string"?{logger:s.logger}:{},...p==="log"&&typeof s.stream=="string"?{stream:s.stream}:{},...typeof L.requestId=="string"?{requestId:L.requestId}:{},...typeof L.parentRequestId=="string"?{parentRequestId:L.parentRequestId}:{},...typeof Z=="string"?{commitId:Z}:{},...typeof I.componentName=="string"?{component:I.componentName}:{},...typeof I.phase=="string"?{phase:I.phase}:{},...Q.length?{why:Q}:{},...p==="effect-run"&&typeof b.hookLogicalId=="string"?{hook:b.hookLogicalId}:{},...p==="effect-run"&&b.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:f(s.total),renderPublished:f(s.published),...f(s.walkStoppedAt)!==void 0?{renderWalkStoppedAt:f(s.walkStoppedAt)}:{}}:{},...typeof L.projectName=="string"?{project:L.projectName}:typeof s.project=="string"?{project:s.project}:{},...y!==void 0?{durationMs:y}:{},...N&&f(s.startedAt)!==void 0?{fetchStartedAt:f(s.startedAt)}:{},...i.source==="ai"?{ai:m.includeRaw?s:qt(s)}:{},...x?{detail:x}:{},...P?{steps:P}:{}}}R(trimFlowEvent,"trimFlowEvent"),k(trimFlowEvent,"trimFlowEvent");const Mt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Wt=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),it=1;function It(i){return i==="flow-origin"?0:i?.endsWith("-start")?1:i==="gateway-request"?2:i==="server-request"?3:i==="span"?4:i==="render"||i==="render-commit-truncated"?6:i==="effect-run"?7:5}R(It,"Oe"),k(It,"kindRank");function V(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:It(i.kind)}R(V,"Z"),k(V,"causalRank");export function buildFlowDetail(i,m={}){const s=Ct(i),I=Pt(i),l=i.slice().filter(t=>{const r=t.raw??{},e=typeof r.kind=="string"?r.kind:"";if(e==="subscription-added"||e==="subscription-removed"||e==="hook-run"||e==="store-created"||e==="singleton-instance"||e===Dt)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,m)),F=new Set;for(let t=l.length-1;t>=0;t--)F.has(l[t].id)?l.splice(t,1):F.add(l[t].id);const f=new Map;for(const t of l)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!f.has(t.requestId)&&f.set(t.requestId,t.start);const M=k(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&f.has(t.requestId)?f.get(t.requestId):t.start,"anchorOf");l.sort((t,r)=>M(t)-M(r)||t.start-r.start||V(t)-V(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const b=k(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),y=l;for(const t of y)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const p=new Map;for(const t of y)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=p.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),p.set(t.requestId,r)}const N=k((t,r)=>{const e=p.get(t);if(e?.length)return e.every(o=>o.project===e[0].project)?e[0].project:e.filter(o=>o.start<=r+1&&o.end>=r-1).sort((o,n)=>n.start-o.start)[0]?.project},"projectOf");for(const t of y)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=N(t.requestId,t.start);r&&(t.project=r)}const W=new Map;for(const t of y)t.spanId&&W.set(t.spanId,t);const tt=k((t,r)=>{let e=t.parentSpanId?W.get(t.parentSpanId):void 0;for(let o=0;e&&o<64;o++){if(e===r)return!0;e=e.parentSpanId?W.get(e.parentSpanId):void 0}return!1},"inside"),z=new Map(y.map((t,r)=>[t,r])),x=new Map,U=k(t=>{let r=x.get(t.group);r||x.set(t.group,r=new Map);const e=t.requestId;let o=r.get(e);return o||r.set(e,o={spans:[],next:0,alive:[]}),o},"legOf");for(const t of y)b(t)&&Number.isFinite(t.start)&&U(t).spans.push(t);for(const t of x.values())for(const r of t.values())r.spans.sort((e,o)=>e.start-o.start||z.get(e)-z.get(o));const E=k(t=>Number.isFinite(t.start)?t.start:1/0,"startOf");for(const t of y.slice().sort((r,e)=>E(r)-E(e))){const r=t.parentSpanId?W.get(t.parentSpanId):void 0;if(r&&r!==t&&r.group===t.group&&r.requestId===t.requestId){t.parent=r.id;continue}if(!Number.isFinite(t.start))continue;const e=U(t);for(;e.next<e.spans.length&&e.spans[e.next].start<=t.start+it;)e.alive.push(e.spans[e.next++]);e.alive=e.alive.filter(a=>a.start+(a.durationMs??0)>t.start);const o=e.alive.length>1?e.alive.slice().sort((a,$)=>z.get(a)-z.get($)):e.alive;let n;for(const a of o){if(a===t)continue;const $=a.project,q=t.project;if(a.kind!=="gateway-request"&&t.kind!=="gateway-request"&&$!==void 0&&q!==void 0&&$!==q)continue;const u=a.durationMs??0,c=t.durationMs??0,v=Math.abs(a.start-t.start)<=it,w=V(a),A=V(t),j=a.start<=t.start;if(!(a.start+u>t.start&&(j||v&&w<A)&&(!v||(w!==A?w<A:j&&u>c))))continue;const O=n?V(n):-1,C=n?Math.abs(a.start-n.start)<=it:!1,J=n&&C&&w===O?tt(a,n)?1:tt(n,a)?-1:0:0;(!n||!C&&a.start>n.start||C&&w>O||J>0||J===0&&C&&w===O&&(a.durationMs??0)<(n.durationMs??0))&&(n=a)}n&&(t.parent=n.id)}for(const t of y)delete t.spanId,delete t.parentSpanId;{const t=new Set(y.map(a=>a.id)),r=new Set,e=new Map,o=[],n=k(a=>{const $=[a];for(;$.length;){const q=$.pop();o.push(q),r.add(q.id);const u=e.get(q.id);if(u){e.delete(q.id);for(let c=u.length-1;c>=0;c--)$.push(u[c])}}},"place");for(const a of y)if(a.parent&&a.parent!==a.id&&t.has(a.parent)&&!r.has(a.parent)){const $=e.get(a.parent)??[];$.push(a),e.set(a.parent,$)}else n(a);for(const a of y)r.has(a.id)||(o.push(a),r.add(a.id));for(let a=0;a<o.length;a++)y[a]=o[a]}const _=new Map;for(const t of y){if(!t.requestId)continue;const r=_.get(t.requestId);r?r.push(t):_.set(t.requestId,[t])}const Y=new Map(y.map(t=>[t.id,t])),H=new Map;for(const t of y)t.calleeRequestId&&!H.has(t.calleeRequestId)&&H.set(t.calleeRequestId,t);const G=k((t,r)=>{const e=(_.get(t)??[]).filter(o=>b(o)&&o.start<=r&&o.start+(o.durationMs??0)>=r);if(e.length!==0)return e.sort((o,n)=>n.start-o.start||(o.durationMs??0)-(n.durationMs??0)),e[0]},"callerNodeFor");for(const t of y){if(!t.parentRequestId||t.kind!=="server-request"&&t.kind!=="gateway-request")continue;const r=t.parent?Y.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=t.requestId?H.get(t.requestId):void 0,o=e&&e.start<=t.start?e:G(t.parentRequestId,t.start);o&&o!==t&&o.start<=t.start&&(t.parent=o.id)}const P=y,T=new Map;for(const t of P)t.kind==="gateway-request"&&t.requestId&&!T.has(t.requestId)&&T.set(t.requestId,t);for(const t of P)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=T.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const L=new Set,Z=new Set,Q=[];for(const t of P){if(t.kind!=="gateway-request")continue;if(!t.requestId){Q.push(t);continue}const r=_.get(t.requestId)??[];if(r.filter(n=>n.kind==="gateway-request").sort((n,a)=>n.start-a.start)[0]!==t)continue;const e=r.find(n=>n.kind==="fetch-start"),o=r.find(n=>n.kind==="fetch-done"||n.kind==="fetch-error");if(!e&&!o){Q.push(t);continue}e&&(t.fetchStartId=e.id,L.add(e.id)),o&&(t.fetchDoneId=o.id,Z.add(o.id))}const d=new Map;for(const t of P){if(!t.urlKey)continue;const r=d.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?Q.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?L.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(Z.has(t.id)||r.dones.push(t)),d.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of d.values()){t.sort((n,a)=>n.start-a.start),r.sort((n,a)=>n.start-a.start);const o=new Set;t.forEach((n,a)=>{const $=r[a];$&&(n.fetchStartId=$.id);const q=$?$.t:n.start;let u,c=1/0;for(const v of e){if(o.has(v.id))continue;const w=v.fetchStartedAt??v.start-(v.durationMs??0),A=Math.abs(w-q);A<c&&(c=A,u=v)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const g=new Map,B=new Map;for(const t of P)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&g.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&B.set(`${t.queue}#${t.jobId}`,t));for(const t of P){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=g.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}else if(t.kind==="queue-active"||t.kind==="queue-completed"||t.kind==="queue-failed"){const e=B.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}}{const t=new Map(y.map(r=>[r.id,r]));for(const r of y){if(!r.parent||!Wt.has(r.kind??"")||r.durationMs===void 0)continue;const e=t.get(r.parent);if(!e||e.kind!=="span"||!((e.durationMs??0)>0))continue;const o=Math.round(r.start+r.durationMs-(e.start+e.durationMs));if(o<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=o;const n=e.leftRunning??{count:0,longestMs:0};e.leftRunning={count:n.count+1,longestMs:Math.max(n.longestMs,o)}}for(const r of y){const e=[];r.leftRunning&&e.push(`ended before ${r.leftRunning.count===1?"a call":`${r.leftRunning.count} calls`} it started had finished \u2014 ${r.leftRunning.count===1?"it":"the longest"} ran on ${r.leftRunning.longestMs}ms (a timeout that gave up, or work not awaited)`),r.outlivedParentMs!==void 0&&e.push(`ran on ${r.outlivedParentMs}ms after the span that started it had ended`),e.length>0&&(r.detail=[r.detail,...e].filter(Boolean).join(" \xB7 "))}}if(I.size>0)for(const t of y){const r=I.get(t.id);r!==void 0&&(t.afterResponseMs=r,t.detail=[t.detail,`began ${r}ms after the request's response had finished \u2014 not part of the request's time`].filter(Boolean).join(" \xB7 "))}let h=y;{const t=new Map;for(const e of h)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of h){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const o=[...t.values()].find($=>$.requestId&&$.requestId===e.requestId)?.id,n=o?t.get(o):void 0;if(!n)continue;const a=e.fetchStartedAt??n.start;n.title=e.title,n.severity=e.severity,n.durationMs=e.durationMs??Math.max(0,e.t-a),n.kind="fetch",e.detail&&!n.detail&&(n.detail=e.detail),r.set(e.id,n.id)}if(r.size>0){h=h.filter(e=>!r.has(e.id));for(const e of h)for(e.fetchDoneId&&r.has(e.fetchDoneId)&&(e.fetchDoneId=r.get(e.fetchDoneId));e.parent&&r.has(e.parent);)e.parent=r.get(e.parent)}}const D=k(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),K=k(t=>[...new Set(t)],"uniq"),ot=k(t=>K(t.map(r=>r.component).filter(r=>!!r)),"named"),bt=k(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),dt=k(t=>{const r=new Map;for(const e of t)e.component&&r.set(e.component,(r.get(e.component)??0)+1);return[...r].map(([e,o])=>o>1?`${e} \xD7${o}`:e).join(", ")},"tally"),xt=k(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),nt=k(t=>`${xt(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),ut=k(t=>{const r=Math.min(...t.map(o=>o.start)),e=Math.max(...t.map(o=>o.start+(o.durationMs??0)));return{start:r,durationMs:e-r}},"extent"),ct=k(t=>(delete t.component,delete t.why,delete t.phase,delete t.hook,delete t.cleanup,delete t.renderTotal,delete t.renderPublished,t),"asGroup");function lt(t){const r=t[0],e=t.filter(S=>S.kind==="render"),o=t.filter(S=>S.kind==="effect-run"),n=t.find(S=>S.kind==="render-commit-truncated"),a=[...e].sort((S,X)=>(X.durationMs??0)-(S.durationMs??0)),$=a.filter(S=>(S.why??[]).some(X=>X!=="parent-render")),q=K($.flatMap(S=>(S.why??[]).filter(X=>X!=="parent-render"))),u=ot($),c=e.filter(S=>S.phase==="mount"),v=e.filter(S=>S.phase!=="mount"&&!$.includes(S)),w=a[0]?.component??"view",A=e.length>0&&c.length===e.length,j=q.length?q.join(" + "):void 0,O=A?"mount":"update",C=u.length?`view update \xB7 ${bt(u)} \u2190 ${j}`:A?`view mount \xB7 ${w}`:`view update \xB7 ${w}`,J=n?.renderTotal??e.length,St=[c.length?`mounted ${dt(c)}`:"",v.length?`re-rendered ${dt(v)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${J} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??e.length} recorded`:n?`${J} renders, ${n.renderPublished??e.length} recorded (per-commit cap)`:`${e.length} render${e.length===1?"":"s"}`,o.length?`${o.length} effect${o.length===1?"":"s"}: ${o.map(nt).join(", ")}`:""].filter(Boolean).join(" \xB7 "),ht=ot(e);return ct({...r,...ut(t),kind:"view-update",title:C,detail:St,commitId:r.commitId,viewPhase:O,...j?{cause:j}:{},causeComponents:u,components:ht,mounted:ot(c),renderCount:J,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:o.length,effectHooks:o.map(nt),memberIds:t.map(S=>S.id),sig:`commit:${O}:${j??"-"}:${u.join(",")}:${ht.slice().sort().join(",")}`,severity:t.some(S=>S.severity==="error")?"error":r.severity})}R(lt,"ke"),k(lt,"viewUpdateNode");function pt(t){const r=t[0],e=t.map(nt);return ct({...r,...ut(t),kind:"commit-effects",title:t.length===1?`effect \xB7 ${e[0]}`:`effects \xB7 ${e[0]} + ${t.length-1} more`,detail:e.join(", "),commitId:r.commitId,effects:t.length,effectHooks:e,memberIds:t.map(o=>o.id),sig:`effects:${e.slice().sort().join(",")}`})}R(pt,"Me"),k(pt,"effectsNode");const jt=k(t=>K(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function ft(t,r){const e=t[0],o=t[t.length-1],n=t.length,a=e.detail,$=Math.min(...t.map(v=>v.start)),q=Math.max(...t.map(v=>v.start+(v.durationMs??0))),u=Math.round(t.reduce((v,w)=>v+(w.durationMs??0),0)/n*10)/10,c=Math.round((q-$)*10)/10;e.count=n,e.avgMs=u,e.wallMs=c,e.durationMs=q-$,e.items=t.slice(0,12).map(v=>({start:v.start-$,...v.durationMs!=null?{durationMs:v.durationMs}:{}})),e.memberIds=t.flatMap(v=>v.memberIds??[v.id]),e.title=`\xD7${n} ${e.title}`,t.some(v=>v.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${n} commits, ${r.length?`one per ${jt(r)}`:"back to back"}`,`avg ${u}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):e.kind==="state-update"&&a&&o.detail?e.detail=`${n} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${o.detail}`:e.detail=[`${n} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}R(ft,"be"),k(ft,"collapseRepeat");const et=[],rt=new Map,mt=new Set;for(let t=0;t<h.length;t++){if(mt.has(t))continue;const r=h[t];if(!D(r)){et.push(r);continue}const e=[t];for(let a=t+1;a<h.length;a++){const $=h[a];if($.group==="browser"){if(!D($)||$.commitId!==r.commitId)break;e.push(a)}}for(const a of e)mt.add(a);const o=e.map(a=>h[a]),n=o.some(a=>a.kind!=="effect-run")?lt(o):pt(o);for(const a of o)a.id!==n.id&&rt.set(a.id,n.id);et.push(n)}if(rt.size>0||et.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){h=et;for(const t of h)for(;t.parent&&rt.has(t.parent);)t.parent=rt.get(t.parent)}{const t=new Map;for(const r of h)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of h){if(r.kind!=="commit-effects"||r.parent||!r.commitId)continue;const e=t.get(r.commitId);e&&e.start<=r.start&&(r.parent=e.id)}}{const t=new Set(["state-update","fetch","fetch-start","fetch-done","fetch-error","flow-origin"]),r=h.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),e=k(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),o=r.map(u=>e(h[u])),n=k((u,c,v)=>{for(let w=0;w<v;w++)if(o[u+w]!==o[c+w])return!1;return!0},"sameBlock"),a=k(u=>o[u].split("|")[0],"kindAt"),$=k(u=>{let c=0,v=1;for(let w=1;w<=4&&u+w<=o.length;w++){let A=1;for(;u+(A+1)*w<=o.length&&n(u,u+A*w,w);)A+=1;A>=3&&w*A>c*v&&(c=w,v=A)}return{k:c,r:v}},"bestBlockAt"),q=new Map;for(let u=0;u<o.length;){const{k:c,r:v}=$(u);if(c===0){u+=1;continue}const w=[...Array(c).keys()].find(j=>t.has(a(u+j)));if(w!==void 0&&w>0){const j=$(u+w);if(j.k===c&&j.r>=3&&j.r>=v-1){u+=w;continue}}const A=o.slice(u,u+c).map(j=>j.split("|")[0]).filter(j=>t.has(j));for(let j=0;j<c;j++){const O=[];for(let C=0;C<v;C++)O.push(h[r[u+j+C*c]]);ft(O,A);for(const C of O.slice(1))q.set(C.id,O[0].id)}u+=c*v}if(q.size>0){h=h.filter(u=>!q.has(u.id));for(const u of h)for(;u.parent&&q.has(u.parent);)u.parent=q.get(u.parent)}}{const t=new Map(h.map(r=>[r.id,r]));for(const r of h){const e=new Set([r.id]);let o=r;for(;o?.parent;){if(e.has(o.parent)){o.parent=void 0;break}e.add(o.parent),o=t.get(o.parent)}}}const gt=k(t=>{const r=new Map;for(const o of h){if(!o.sig||b(o)!==t||o.kind==="server-request"||o.kind==="gateway-request"||o.group==="browser")continue;const n=`${o.parent??"root"}|${o.kind}|${o.sig}`,a=r.get(n);a?a.push(o):r.set(n,[o])}const e=new Map;for(const o of r.values()){if(o.length<3)continue;o.sort((c,v)=>c.start-v.start);const n=o[0];let a=!1;for(let c=0;c+1<o.length;c++)if(o[c+1].start<o[c].start+(o[c].durationMs??0)){a=!0;break}const $=n.start,q=Math.max(...o.map(c=>c.start+(c.durationMs??0))),u=o.reduce((c,v)=>c+(v.durationMs??0),0);n.count=o.length,n.parallel=a,n.avgMs=Math.round(u/o.length*10)/10,n.wallMs=q-$,n.durationMs=q-$,n.title=`\xD7${o.length} ${n.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,n.detail=`${n.sig} \xD7${o.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${n.avgMs}ms \xB7 wall ${n.wallMs}ms`,n.items=o.slice(0,12).map(c=>({start:c.start-$,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),n.memberIds=o.flatMap(c=>c.memberIds??[c.id]),o.some(c=>c.severity==="error")&&(n.severity="error");for(const c of o.slice(1))e.set(c.id,n.id)}if(e.size!==0){h=h.filter(o=>!e.has(o.id));for(const o of h)for(;o.parent&&e.has(o.parent);)o.parent=e.get(o.parent)}},"aggregatePass");gt(!0),gt(!1);for(const t of h){if(!b(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=h.filter(q=>q.parent===t.id&&(q.durationMs??0)>0).map(q=>[q.start,q.start+(q.durationMs??0)]).sort((q,u)=>q[0]-u[0]);let o=0,n=-1,a=-1;for(const[q,u]of e)q>a?(a>n&&(o+=a-n),n=q,a=u):u>a&&(a=u);a>n&&(o+=a-n);const $=Math.max(0,r-o);($>=50||$/r>=.7&&r>=40)&&(t.selfMs=$,t.detail=`\u26A0 cpu-heavy: ${$}ms self-time of ${r}ms${t.detail?" \xB7 "+t.detail:""}`)}return{events:h,...s?{sql:s}:{}}}R(buildFlowDetail,"buildFlowDetail"),k(buildFlowDetail,"buildFlowDetail");
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The workspace's lens configuration (planning/global Z1): `lensmcp.json` → `config` first, then `nx.json` → `lensmcp`,
|
|
3
|
+
* key by key — retention, redaction, channels, thresholds, flows, stores, instances, tests, ai, key. A project detached
|
|
4
|
+
* from Nx wiring keeps it in `lensmcp.json` alone; one set up before keeps it in `nx.json`. Lock-step copy: libs/cli
|
|
5
|
+
* lens-config.ts (the CLI imports no package), byte for byte.
|
|
6
|
+
*/
|
|
7
|
+
export type WorkspaceConfig = Record<string, unknown>;
|
|
8
|
+
export type WorkspaceConfigSource = 'lensmcp.json' | 'nx.json';
|
|
9
|
+
/** The merged configuration at `root`: a key `lensmcp.json` → `config` sets wins over the same key in `nx.json` → `lensmcp`. */
|
|
10
|
+
export declare function readWorkspaceConfig(root: string): WorkspaceConfig;
|
|
11
|
+
/** Which file a key of the configuration comes from, or undefined when neither sets it. */
|
|
12
|
+
export declare function workspaceConfigSource(root: string, key: string): WorkspaceConfigSource | undefined;
|
|
13
|
+
/** The nearest folder at or above `from` (8 levels at most) holding `nx.json` or `lensmcp.json` — the workspace whose configuration applies. */
|
|
14
|
+
export declare function findWorkspaceConfigRoot(from: string): string | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var f=Object.defineProperty;var e=(o,n)=>f(o,"name",{value:n,configurable:!0});var p=Object.defineProperty,c=e((o,n)=>p(o,"name",{value:n,configurable:!0}),"e");import{existsSync as a,readFileSync as u}from"node:fs";import{dirname as j,join as r}from"node:path";const l=c(o=>!!o&&typeof o=="object"&&!Array.isArray(o),"isObj");function i(o,n){try{const s=JSON.parse(u(o,"utf8"))?.[n];return l(s)?s:{}}catch{return{}}}e(i,"t"),c(i,"block");export function readWorkspaceConfig(o){return{...i(r(o,"nx.json"),"lensmcp"),...i(r(o,"lensmcp.json"),"config")}}e(readWorkspaceConfig,"readWorkspaceConfig"),c(readWorkspaceConfig,"readWorkspaceConfig");export function workspaceConfigSource(o,n){return n in i(r(o,"lensmcp.json"),"config")?"lensmcp.json":n in i(r(o,"nx.json"),"lensmcp")?"nx.json":void 0}e(workspaceConfigSource,"workspaceConfigSource"),c(workspaceConfigSource,"workspaceConfigSource");export function findWorkspaceConfigRoot(o){let n=o;for(let s=0;s<8;s++){if(a(r(n,"nx.json"))||a(r(n,"lensmcp.json")))return n;const t=j(n);if(t===n)break;n=t}}e(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),c(findWorkspaceConfigRoot,"findWorkspaceConfigRoot");
|
package/lib/lens-dir.d.ts
CHANGED
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
* And `.lensmcp/ai-names/`: the names people gave the AI calls page's agents and actions, so the team sees the same
|
|
11
11
|
* (the AI agent review's own instructions are `.lensmcp/ai-review/`). And `.lensmcp/team/`: the agent team's role files
|
|
12
12
|
* and its flow of hand-offs (`@lensmcp/storage` team-files.ts), so every agent on the repository works by the same rules —
|
|
13
|
+
* and, under it, `.lensmcp/team/skills/<name>/`: the project's own skills, each a SKILL.md with its references and the
|
|
14
|
+
* pins of the sources it was written from (`@lensmcp/storage` skill-layers.ts). `team` lets the whole folder back in,
|
|
15
|
+
* so the skills need no line of their own (lens-dir.spec.ts holds that) —
|
|
13
16
|
* and `.lensmcp/team-design/`: the project's own instructions to the run that designs that team.
|
|
14
17
|
*
|
|
15
18
|
* The .gitignore that keeps both right ignores the folder's children — at any depth, as `.lensmcp/` did — and lets
|
|
@@ -24,6 +27,12 @@
|
|
|
24
27
|
* Lock-step copies: `@lensmcp/nx-plugin` init (writes the lines) and `lensmcp doctor` (checks them).
|
|
25
28
|
*/
|
|
26
29
|
export declare const LENS_SHARED_DIRS: readonly string[];
|
|
30
|
+
/**
|
|
31
|
+
* The team's files that sit deeper than a shared folder's root — a project skill's SKILL.md, its pins and a reference:
|
|
32
|
+
* the lines above must let each through (lens-dir.spec.ts), and `lensmcp doctor` says when a line of the repository's
|
|
33
|
+
* own keeps one out. Lock-step with the CLI's lens-ignore.ts LENS_SHARED_FILES.
|
|
34
|
+
*/
|
|
35
|
+
export declare const LENS_SHARED_FILES: readonly string[];
|
|
27
36
|
/** The .gitignore lines for `.lensmcp/`: at any depth (prefix `**\/`), or at the root only (`/`). */
|
|
28
37
|
export declare function lensGitignoreLines(prefix?: '**/' | '/'): string[];
|
|
29
38
|
/**
|
package/lib/lens-dir.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var u=Object.defineProperty;var
|
|
2
|
-
`),
|
|
3
|
-
`)?`${
|
|
4
|
-
`:
|
|
1
|
+
"use strict";var u=Object.defineProperty;var n=(i,e)=>u(i,"name",{value:e,configurable:!0});var p=Object.defineProperty,m=n((i,e)=>p(i,"name",{value:e,configurable:!0}),"c");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"],LENS_SHARED_FILES=["team/skills/a-skill/SKILL.md","team/skills/a-skill/sources.json","team/skills/a-skill/references/more.md"];export function lensGitignoreLines(i="**/"){return[`${i}.lensmcp/*`,...LENS_SHARED_DIRS.map(e=>`!${i}.lensmcp/${e}/`)]}n(lensGitignoreLines,"lensGitignoreLines"),m(lensGitignoreLines,"lensGitignoreLines");const $="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";export function fixLensGitignore(i){const e=i.split(`
|
|
2
|
+
`),c=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let s=e.findIndex(t=>c.test(t.trim())),r=!1;if(s<0){const t=i.length&&!i.endsWith(`
|
|
3
|
+
`)?`${i}
|
|
4
|
+
`:i;return{text:`${t}${t.trim()?`
|
|
5
5
|
`:""}${$}
|
|
6
6
|
${lensGitignoreLines().join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,changed:!0}}const c
|
|
9
|
-
`),changed:
|
|
8
|
+
`,changed:!0}}const l=c.exec(e[s].trim())[1]==="/"?"/":"**/";e[s].trim()!==`${l}.lensmcp/*`&&(e[s]=`${l}.lensmcp/*`,r=!0);for(const t of LENS_SHARED_DIRS){const o=`!${l}.lensmcp/${t}/`;e.some(a=>a.trim()===o||a.trim()===o.slice(0,-1))||(e.splice(++s,0,o),r=!0)}return{text:e.join(`
|
|
9
|
+
`),changed:r}}n(fixLensGitignore,"fixLensGitignore"),m(fixLensGitignore,"fixLensGitignore");
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface StoredLensmcp {
|
|
2
|
+
home: string;
|
|
3
|
+
version: string;
|
|
4
|
+
dir: string;
|
|
5
|
+
pkg: string;
|
|
6
|
+
cli: string;
|
|
7
|
+
launcher: string;
|
|
8
|
+
}
|
|
9
|
+
export declare const lensStoreHome: (env?: NodeJS.ProcessEnv) => string;
|
|
10
|
+
export declare function storedLensmcp(home: string, version: string): StoredLensmcp | undefined;
|
|
11
|
+
export declare function storeCurrent(env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
|
|
12
|
+
export declare function inLensStore(path: string, env?: NodeJS.ProcessEnv): boolean;
|
|
13
|
+
/** The stored version a path lies in (as named, or as it really is through `current`), when it is a whole one. */
|
|
14
|
+
export declare function storeVersionOf(path: string, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* The stored lensmcp a process hands out: a process that runs from the store keeps its own version until it restarts
|
|
17
|
+
* (owner, 2026-11-10); only one that runs from elsewhere takes the store's current version.
|
|
18
|
+
*/
|
|
19
|
+
export declare function storeOwnOrCurrent(entry?: string | undefined, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
|
|
20
|
+
/** The published packages installed beside lensmcp in every version folder (libs/cli store.ts OPTIONAL_PACKAGES). */
|
|
21
|
+
export declare const LENS_OPTIONAL_PACKAGES: readonly string[];
|
|
22
|
+
/** The optional packages a version folder holds. */
|
|
23
|
+
export declare function storedOptionalNames(home: string, version: string): string[];
|
|
24
|
+
/** Semver order, a pre-release before its release and `rc.9` before `rc.10` (libs/cli store.ts compareVersions). */
|
|
25
|
+
export declare function compareLensVersions(a: string, b: string): number;
|
|
26
|
+
/** Every whole version the store holds, oldest first. */
|
|
27
|
+
export declare function storedVersionNames(home: string): string[];
|
|
28
|
+
/** The versions forwarded lensmcp processes run (`versions/.running/<pid>`, libs/cli store.ts markForwarded), by pid; gone pids are left out. */
|
|
29
|
+
export declare function storeForwardedRunning(home: string): Map<string, number[]>;
|
|
30
|
+
export declare function linkedCheckout(pkg: string): boolean;
|
|
31
|
+
export declare function storeFirst(project: string | undefined, env?: NodeJS.ProcessEnv, entry?: string | undefined): string[];
|
|
32
|
+
export declare const STORE_FIRST_MCP = "h=\"${LENSMCP_HOME:-$HOME/.lensmcp}\"; [ \"${LENSMCP_NO_STORE:-}\" != 1 ] && [ -x \"$h/bin/lensmcp\" ] && [ -f \"$h/current/node_modules/lensmcp/bin.js\" ] && exec \"$h/bin/lensmcp\" mcp; exec npx ";
|
|
33
|
+
export declare function storeFirstMcpEntry(fallback: readonly string[]): {
|
|
34
|
+
command: string;
|
|
35
|
+
args: string[];
|
|
36
|
+
};
|
|
37
|
+
export declare function storeFirstFallback(entry: unknown): string[] | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var S=Object.defineProperty;var i=(r,t)=>S(r,"name",{value:t,configurable:!0});var N=Object.defineProperty,o=i((r,t)=>N(r,"name",{value:t,configurable:!0}),"s");import{existsSync as v,readdirSync as x,readFileSync as y,readlinkSync as b,realpathSync as E}from"node:fs";import{homedir as _}from"node:os";import{basename as k,join as u,sep as f}from"node:path";export const lensStoreHome=o((r=process.env)=>r.LENSMCP_HOME||u(_(),".lensmcp"),"lensStoreHome");const d=o(r=>{try{return E(r)}catch{return r}},"realOr");export function storedLensmcp(r,t){const e=u(r,"versions",t),n=u(e,"node_modules","lensmcp"),s=u(n,"bin.js");if(v(s)){try{if(JSON.parse(y(u(n,"package.json"),"utf8")).version!==t)return}catch{return}return{home:r,version:t,dir:e,pkg:n,cli:s,launcher:u(r,"bin","lensmcp")}}}i(storedLensmcp,"storedLensmcp"),o(storedLensmcp,"storedLensmcp");export function storeCurrent(r=process.env){if(r.LENSMCP_NO_STORE==="1")return;const t=lensStoreHome(r);let e;try{e=k(b(u(t,"current")))}catch{return}return storedLensmcp(t,e)}i(storeCurrent,"storeCurrent"),o(storeCurrent,"storeCurrent");export function inLensStore(r,t=process.env){const e=u(lensStoreHome(t),"versions");return r.startsWith(e+f)||d(r).startsWith(d(e)+f)}i(inLensStore,"inLensStore"),o(inLensStore,"inLensStore");const g=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;export function storeVersionOf(r,t=process.env){const e=lensStoreHome(t),n=u(e,"versions");for(const[s,p]of[[r,n],[d(r),d(n)]]){if(!s.startsWith(p+f))continue;const l=s.slice(p.length+1).split(f,1)[0]??"";if(g.test(l))return storedLensmcp(e,l)}}i(storeVersionOf,"storeVersionOf"),o(storeVersionOf,"storeVersionOf");export function storeOwnOrCurrent(r=process.argv[1],t=process.env){if(t.LENSMCP_NO_STORE!=="1")return r&&inLensStore(r,t)?storeVersionOf(r,t):storeCurrent(t)}i(storeOwnOrCurrent,"storeOwnOrCurrent"),o(storeOwnOrCurrent,"storeOwnOrCurrent");export const LENS_OPTIONAL_PACKAGES=["@lensmcp/terminals","@lensmcp/vite-plugin","@lensmcp/bridge","@lensmcp/client-runtime","@lensmcp/react-instrumentation","@lensmcp/valtio-instrumentation"];export function storedOptionalNames(r,t){return LENS_OPTIONAL_PACKAGES.filter(e=>v(u(r,"versions",t,"node_modules",e,"package.json")))}i(storedOptionalNames,"storedOptionalNames"),o(storedOptionalNames,"storedOptionalNames");export function compareLensVersions(r,t){const e=o(c=>{const a=c.indexOf("-");return{nums:(a<0?c:c.slice(0,a)).split(".").map(m=>Number(m)||0),pre:a<0?void 0:c.slice(a+1)}},"parse"),n=e(r),s=e(t);for(let c=0;c<3;c++){const a=(n.nums[c]??0)-(s.nums[c]??0);if(a)return a<0?-1:1}if(n.pre===s.pre)return 0;if(n.pre===void 0)return 1;if(s.pre===void 0)return-1;const p=n.pre.split("."),l=s.pre.split(".");for(let c=0;c<Math.max(p.length,l.length);c++){const a=p[c],m=l[c];if(a===void 0)return-1;if(m===void 0)return 1;if(a===m)continue;const h=/^\d+$/.test(a),O=/^\d+$/.test(m);return h&&O?Number(a)<Number(m)?-1:1:h!==O?h?-1:1:a<m?-1:1}return 0}i(compareLensVersions,"compareLensVersions"),o(compareLensVersions,"compareLensVersions");export function storedVersionNames(r){let t;try{t=x(u(r,"versions"))}catch{return[]}return t.filter(e=>g.test(e)&&storedLensmcp(r,e)!==void 0).sort(compareLensVersions)}i(storedVersionNames,"storedVersionNames"),o(storedVersionNames,"storedVersionNames");const M=o(r=>{try{return process.kill(r,0),!0}catch(t){return t.code==="EPERM"}},"pidAlive");export function storeForwardedRunning(r){const t=new Map,e=u(r,"versions",".running");let n;try{n=x(e)}catch{return t}for(const s of n){const p=Number(s);if(!Number.isInteger(p)||p<=0||!M(p))continue;let l;try{l=y(u(e,s),"utf8").trim()}catch{continue}g.test(l)&&t.set(l,[...t.get(l)??[],p])}return t}i(storeForwardedRunning,"storeForwardedRunning"),o(storeForwardedRunning,"storeForwardedRunning");export function linkedCheckout(r){if(!v(u(r,"package.json")))return!1;const t=d(r).split(f);return t[t.length-1]!=="lensmcp"||t[t.length-2]!=="node_modules"}i(linkedCheckout,"linkedCheckout"),o(linkedCheckout,"linkedCheckout");export function storeFirst(r,t=process.env,e=process.argv[1]){const n=storeOwnOrCurrent(e,t);return!n||r&&linkedCheckout(r)?r?[r]:[]:r?[n.pkg,r]:[n.pkg]}i(storeFirst,"storeFirst"),o(storeFirst,"storeFirst");export const STORE_FIRST_MCP='h="${LENSMCP_HOME:-$HOME/.lensmcp}"; [ "${LENSMCP_NO_STORE:-}" != 1 ] && [ -x "$h/bin/lensmcp" ] && [ -f "$h/current/node_modules/lensmcp/bin.js" ] && exec "$h/bin/lensmcp" mcp; exec npx ';export function storeFirstMcpEntry(r){return{command:"sh",args:["-c",`${STORE_FIRST_MCP}${r.join(" ")}`]}}i(storeFirstMcpEntry,"storeFirstMcpEntry"),o(storeFirstMcpEntry,"storeFirstMcpEntry");export function storeFirstFallback(r){if(!r||typeof r!="object"||Array.isArray(r))return;const{command:t,args:e,...n}=r;if(t!=="sh"||Object.keys(n).length>0||!Array.isArray(e)||e.length!==2||e[0]!=="-c")return;const s=e[1];if(typeof s!="string"||!s.startsWith(STORE_FIRST_MCP))return;const p=s.slice(STORE_FIRST_MCP.length).split(" ");return p.every(l=>/^[\w@.-]+$/.test(l))?p:void 0}i(storeFirstFallback,"storeFirstFallback"),o(storeFirstFallback,"storeFirstFallback");
|
package/lib/patterns.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* call them on demand.
|
|
6
6
|
*
|
|
7
7
|
* Detectors covered (Phase 7):
|
|
8
|
-
* - db-in-loop — a `loop` node
|
|
8
|
+
* - db-in-loop — a `loop` node: one statement shape repeated inside one method (`dbLoopBreaks`)
|
|
9
9
|
* - n+1-query — the same query signature repeated ≥ N times in a window
|
|
10
10
|
* - slow-path — the longest cumulative duration on the caused/async axis
|
|
11
11
|
* - render-storm — one componentInstanceId rendered > N times in < T ms
|
|
@@ -24,24 +24,40 @@ export interface PatternMatch {
|
|
|
24
24
|
detectedAt: number;
|
|
25
25
|
}
|
|
26
26
|
export interface DbInLoopOptions {
|
|
27
|
-
/**
|
|
27
|
+
/** `dbInLoop`: a statement run with the SAME values more often than this inside one method is a repeated read. Default 5. */
|
|
28
28
|
threshold?: number;
|
|
29
|
+
/** `nPlusOne`: a statement run with varying values this often inside one method is a loop. Default 3. */
|
|
30
|
+
nPlusOne?: number;
|
|
29
31
|
}
|
|
30
|
-
/**
|
|
31
|
-
* The DB calls a loop is judged by (`dbInLoop`): all it made — or, for a loop of a stream that says how many fell within
|
|
32
|
-
* two neighbouring seconds (`dbBurst`), those. A stream's pump reads every few seconds for as long as the stream is open:
|
|
33
|
-
* only a burst inside it is a loop's work (issues/closed/foodguard-148).
|
|
34
|
-
*/
|
|
32
|
+
/** The runs of the one statement a loop repeated — a stream's, within two seconds (`dbBurst`, foodguard-148). */
|
|
35
33
|
export declare function loopDbCalls(loop: {
|
|
36
34
|
dbCallsInsideLoop?: unknown;
|
|
37
35
|
dbBurst?: unknown;
|
|
38
36
|
stream?: unknown;
|
|
39
37
|
}): number;
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
38
|
+
/** A method's DB work: one shape with varying values (`loop`), the same values (`repeated-read`), or distinct ones (`sequential`). */
|
|
39
|
+
export type DbWorkClass = 'loop' | 'repeated-read' | 'sequential';
|
|
40
|
+
export declare const DB_WORK_CLASSES: readonly DbWorkClass[];
|
|
41
|
+
/** A `loop` event's class — undefined from a tap before statement shapes, which counted every DB call of the method. */
|
|
42
|
+
export declare function dbLoopClass(loop: {
|
|
43
|
+
class?: unknown;
|
|
44
|
+
}): DbWorkClass | undefined;
|
|
45
|
+
/** The repeats of one shape with varying values that make a loop: `nPlusOne`, or fewer when `dbInLoop` is set lower. */
|
|
46
|
+
export declare const loopRepeatsLimit: (l: {
|
|
47
|
+
nPlusOne: number;
|
|
48
|
+
dbInLoop: number;
|
|
49
|
+
}) => number;
|
|
50
|
+
/** A loop from `loopRepeatsLimit` repeats, a repeated read above `dbInLoop`; sequential or class-less (an older tap) never (overseer-73). */
|
|
51
|
+
export declare function dbLoopBreaks(loop: {
|
|
52
|
+
class?: unknown;
|
|
53
|
+
dbCallsInsideLoop?: unknown;
|
|
54
|
+
dbBurst?: unknown;
|
|
55
|
+
stream?: unknown;
|
|
56
|
+
}, l: {
|
|
57
|
+
nPlusOne: number;
|
|
58
|
+
dbInLoop: number;
|
|
59
|
+
}): boolean;
|
|
60
|
+
/** Flag `loop` events (`raw.loop`, `LoopAttrs`) whose DB work breaks the limits (`dbLoopBreaks`). */
|
|
45
61
|
export declare function detectDbInLoop(events: readonly BaseEvent[], options?: DbInLoopOptions): PatternMatch[];
|
|
46
62
|
export interface AbandonedAwaitOptions {
|
|
47
63
|
/** How long a call must run past the end of the method that started it. Default 250 ms. */
|
package/lib/patterns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var p=(e,n)=>w(e,"name",{value:n,configurable:!0});var g=Object.defineProperty,u=p((e,n)=>g(e,"name",{value:n,configurable:!0}),"u");export function loopDbCalls(e){const n=typeof e.dbCallsInsideLoop=="number"?e.dbCallsInsideLoop:0;return e.stream===!0&&typeof e.dbBurst=="number"?Math.min(n,e.dbBurst):n}p(loopDbCalls,"loopDbCalls"),u(loopDbCalls,"loopDbCalls");export const DB_WORK_CLASSES=["loop","repeated-read","sequential"];export function dbLoopClass(e){return DB_WORK_CLASSES.includes(e.class)?e.class:void 0}p(dbLoopClass,"dbLoopClass"),u(dbLoopClass,"dbLoopClass");export const loopRepeatsLimit=u(e=>Math.min(e.nPlusOne,e.dbInLoop+1),"loopRepeatsLimit");export function dbLoopBreaks(e,n){const i=dbLoopClass(e),d=loopDbCalls(e);return i==="loop"?d>=loopRepeatsLimit(n):i==="repeated-read"?d>n.dbInLoop:!1}p(dbLoopBreaks,"dbLoopBreaks"),u(dbLoopBreaks,"dbLoopBreaks");export function detectDbInLoop(e,n={}){const i=n.threshold??5,d={dbInLoop:i,nPlusOne:n.nPlusOne??3},o=[];for(const s of e){const t=s.raw??null;if(t?.kind!=="loop"||!t.loop||!dbLoopBreaks(t.loop,d))continue;const r=loopDbCalls(t.loop),a=t.loop.dbCallsInsideLoop??0,l=r<a,f=dbLoopClass(t.loop),c=typeof t.loop.calls=="number"&&typeof t.loop.distinctStatements=="number"?` \u2014 ${t.loop.calls} DB calls, ${t.loop.distinctStatements} statements`:"";o.push({kind:"db-in-loop",severity:"warning",title:l?`one statement ${r}\xD7 within two seconds of a stream's loop (${a} over its life)${c}`:`${f==="loop"?"loop":"repeated read"}: one statement ${r}\xD7 inside one method${c}`,evidence:[s.id],details:{class:f,dbCallsInsideLoop:a,...l?{dbBurst:r,stream:!0}:{},...t.loop.sqlId?{sqlId:t.loop.sqlId}:{},...typeof t.loop.calls=="number"?{calls:t.loop.calls}:{},...typeof t.loop.distinctStatements=="number"?{distinctStatements:t.loop.distinctStatements}:{},...typeof t.loop.distinctValues=="number"?{distinctValues:t.loop.distinctValues}:{},iterations:t.loop.iterations,durationMs:t.loop.durationMs,threshold:i},detectedAt:s.timestamp})}return o}p(detectDbInLoop,"detectDbInLoop"),u(detectDbInLoop,"detectDbInLoop");const I=new Set(["egress","db-query","redis-op","ai-call"]);function y(e){const n=e.raw??null;if(!n||typeof n.kind!="string"||!I.has(n.kind))return;const i=typeof n.durationMs=="number"?n.durationMs:void 0;if(i===void 0)return;const d=typeof n.startedAt=="number"?n.startedAt:e.timestamp-i,o=e.context??{};return{id:e.id,start:d,end:d+i,label:e.title,...typeof o.requestId=="string"?{requestId:o.requestId}:{},...typeof n.project=="string"?{project:n.project}:typeof o.projectName=="string"?{project:o.projectName}:{}}}p(y,"M"),u(y,"timedCall");function M(e){const n=e.raw??null,i=n?.kind==="span"?n.span:void 0;if(!i||typeof i.name!="string"||i.name.startsWith("nest.request "))return;const d=typeof i.durationMs=="number"?i.durationMs:void 0;if(d===void 0||d<=0)return;const o=typeof i.startTime=="number"?i.startTime:e.timestamp-d,s=e.context??{};return{id:e.id,start:o,end:o+d,label:i.name,...typeof s.requestId=="string"?{requestId:s.requestId}:{},...typeof n?.project=="string"?{project:n.project}:typeof s.projectName=="string"?{project:s.projectName}:{}}}p(M,"g"),u(M,"timedSpan");export function abandonedAwaitOf(e,n,i={}){const d=i.thresholdMs??250,o=y(e);if(!o||!o.requestId||o.end-o.start<d)return;let s;for(const r of n){const a=M(r);!a||a.requestId!==o.requestId||a.project!==void 0&&o.project!==void 0&&a.project!==o.project||a.start>o.start||a.end<=o.start||(!s||a.start>s.start||a.start===s.start&&a.end<s.end)&&(s=a)}if(!s)return;const t=Math.round(o.end-s.end);if(!(t<d))return{kind:"abandoned-await",severity:"warning",title:`${s.label} ended ${t}ms before a call it started had finished (${o.label})`,evidence:[s.id,o.id],details:{span:s.label,call:o.label,ranOnMs:t,spanMs:Math.round(s.end-s.start),callMs:Math.round(o.end-o.start),thresholdMs:d,...o.project?{project:o.project}:{}},detectedAt:e.timestamp}}p(abandonedAwaitOf,"abandonedAwaitOf"),u(abandonedAwaitOf,"abandonedAwaitOf");export function detectAbandonedAwait(e,n={}){const i=[];for(const d of e){const o=abandonedAwaitOf(d,e,n);o&&i.push(o)}return i}p(detectAbandonedAwait,"detectAbandonedAwait"),u(detectAbandonedAwait,"detectAbandonedAwait");export function detectNPlusOne(e,n={}){const i=n.threshold??3,d=new Map;for(const s of e){const t=s.raw??null;if(t?.kind!=="db-query"||!t.query?.signature)continue;const r=t.query.signature;let a=d.get(r);a||(a=[],d.set(r,a)),a.push(s)}const o=[];for(const[s,t]of d)t.length>=i&&o.push({kind:"n+1-query",severity:"warning",title:`Query repeated ${t.length}\xD7 \u2014 likely N+1`,evidence:t.map(r=>r.id),details:{signature:s,count:t.length,threshold:i},detectedAt:t[t.length-1].timestamp});return o}p(detectNPlusOne,"detectNPlusOne"),u(detectNPlusOne,"detectNPlusOne");export function detectRenderStorm(e,n={}){const i=n.threshold??5,d=n.windowMs??250,o=new Map;for(const t of e){if(t.source!=="react")continue;const r=t.raw??null;if(r?.kind!=="render"||!r.render?.componentInstanceId)continue;const a=r.render.componentInstanceId;let l=o.get(a);l||(l=[],o.set(a,l)),l.push(t)}const s=[];for(const[t,r]of o){r.sort((l,f)=>l.timestamp-f.timestamp);let a=0;for(let l=0;l<r.length;l++){for(;r[l].timestamp-r[a].timestamp>d;)a++;const f=l-a+1;if(f>i){const c=r.slice(a,l+1),m=c[0].raw.render?.componentName??t;s.push({kind:"render-storm",severity:"warning",title:`${m} rendered ${f}\xD7 in ${d}ms`,evidence:c.map(b=>b.id),details:{componentInstanceId:t,count:f,windowMs:d,threshold:i},detectedAt:c[c.length-1].timestamp});break}}}return s}p(detectRenderStorm,"detectRenderStorm"),u(detectRenderStorm,"detectRenderStorm");export function findSlowPath(e,n,i){const d=new Map,o=new Set;function s(r){const a=d.get(r);if(a)return a;if(o.has(r))return{path:[r],totalDurationMs:i(r)};o.add(r);const l=i(r),f=n.get(r)??[];let c;for(const b of f){const h=s(b);(!c||h.totalDurationMs>c.totalDurationMs)&&(c=h)}o.delete(r);const m=c?{path:[r,...c.path],totalDurationMs:l+c.totalDurationMs}:{path:[r],totalDurationMs:l};return d.set(r,m),m}p(s,"a"),u(s,"best");let t={path:[],totalDurationMs:0};for(const r of e){const a=s(r);a.totalDurationMs>t.totalDurationMs&&(t=a)}return t}p(findSlowPath,"findSlowPath"),u(findSlowPath,"findSlowPath");
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { BaseEvent } from '@lensmcp/protocol-types';
|
|
2
|
+
import { type DbWorkClass } from './patterns.js';
|
|
2
3
|
import { type LensmcpThresholds } from './thresholds.js';
|
|
3
4
|
/**
|
|
4
5
|
* How one checkout performed over one window — the routes it served, the statements it ran, the pages it loaded — and
|
|
@@ -12,8 +13,11 @@ import { type LensmcpThresholds } from './thresholds.js';
|
|
|
12
13
|
* - a route, a statement or a page is slow when it ran at or above its limit MORE THAN ONCE (the perf reducer's rule —
|
|
13
14
|
* a one-off spike, the first call after a rebuild, is not a breach; it is still in the numbers);
|
|
14
15
|
* - N+1: one request ran the same statement `nPlusOne` times or more — a streaming one, within one burst: its reads
|
|
15
|
-
* seconds apart are a stream's periodic work over its life, not a loop (issues/closed/foodguard-147)
|
|
16
|
-
*
|
|
16
|
+
* seconds apart are a stream's periodic work over its life, not a loop (issues/closed/foodguard-147). Its class says
|
|
17
|
+
* whether the values varied (`loop`) or not (`repeated-read`: the same row re-read at fixed steps);
|
|
18
|
+
* - DB in a loop: ONE statement shape repeated inside one method (`dbLoopBreaks`) — never many different statements
|
|
19
|
+
* run once each, which is straight-line code (issues/closed/overseer-73). Folded per route, statement and method,
|
|
20
|
+
* with the requests it ran in; one that names the statement an N+1 of the same route names is folded into it.
|
|
17
21
|
* A streaming response's time is how long it stayed open, not how slow it was: it is counted, never timed. A page the dev
|
|
18
22
|
* server reloaded (`cause: 'hmr'`) is left out, and a hard load is timed from the app's entry (`appReadyMs`), not from
|
|
19
23
|
* the dev server serving it.
|
|
@@ -93,6 +97,12 @@ export interface PerformanceBreach {
|
|
|
93
97
|
limit: string;
|
|
94
98
|
/** Up to five event ids that show it. */
|
|
95
99
|
evidence: string[];
|
|
100
|
+
/** An N+1's or DB loop's class, the method's DB calls and statements, its requests and method (overseer-73). */
|
|
101
|
+
class?: DbWorkClass;
|
|
102
|
+
calls?: number;
|
|
103
|
+
distinctStatements?: number;
|
|
104
|
+
requests?: number;
|
|
105
|
+
site?: string;
|
|
96
106
|
/** Waived by the person: why. A waived breach does not fail the window. */
|
|
97
107
|
waived?: string;
|
|
98
108
|
/**
|
|
@@ -109,7 +119,7 @@ export interface PerformanceBreach {
|
|
|
109
119
|
/**
|
|
110
120
|
* A window's numbers by subject, kept small: what a later window is compared with — main's, for a QA run's breaches
|
|
111
121
|
* (issues/closed/foodguard-181). Timings are p95 ms; `repeats` the most runs of a statement in one request of a route
|
|
112
|
-
* (`<route>\0<sql>`), at any count; `loops` the most
|
|
122
|
+
* (`<route>\0<sql>`), at any count; `loops` the most repeats of one statement in one method, by route and statement (`<route>\0<sql>`).
|
|
113
123
|
*/
|
|
114
124
|
export interface PerformanceBaseline {
|
|
115
125
|
limits: PerformanceLimits;
|
|
@@ -145,6 +155,8 @@ export interface PerformanceReport {
|
|
|
145
155
|
slow: number;
|
|
146
156
|
failed: number;
|
|
147
157
|
};
|
|
158
|
+
/** Class-less `loop` events of an older tap, not judged: they counted every DB call of the method. */
|
|
159
|
+
unjudgedLoops?: number;
|
|
148
160
|
/** Slowest p95 first. */
|
|
149
161
|
routes: RouteStat[];
|
|
150
162
|
sql: SqlStat[];
|
|
@@ -170,7 +182,10 @@ export declare class PerformanceWindow {
|
|
|
170
182
|
private readonly streams;
|
|
171
183
|
/** N+1 per route and statement: the worst count, and where — and how many of its requests were streams. */
|
|
172
184
|
private readonly repeated;
|
|
185
|
+
/** DB loops by route, statement and method — and those whose request has not ended yet (its route not known). */
|
|
173
186
|
private readonly loops;
|
|
187
|
+
private readonly loopsWaiting;
|
|
188
|
+
private unjudgedLoops;
|
|
174
189
|
/** Where each statement runs (planning/code-locations `raw.site`): the files of its frames, and whether a run carried none. */
|
|
175
190
|
private readonly sqlFiles;
|
|
176
191
|
private readonly sqlUnlocated;
|
|
@@ -198,6 +213,8 @@ export declare class PerformanceWindow {
|
|
|
198
213
|
*/
|
|
199
214
|
private close;
|
|
200
215
|
private loop;
|
|
216
|
+
/** One DB loop under its route: one finding per route, statement and method, its worst, and the requests it ran in. */
|
|
217
|
+
private foldLoop;
|
|
201
218
|
private page;
|
|
202
219
|
/** The person's why for a breach, when a waiver matches what it is about; undefined: it stands. */
|
|
203
220
|
private waiverOf;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var M=(i,t)=>E(i,"name",{value:t,configurable:!0});var I=Object.defineProperty,c=M((i,t)=>I(i,"name",{value:t,configurable:!0}),"f");import{loopDbCalls as L}from"./patterns.js";import{resolveThresholds as F}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...i){let t={};for(const r of i)r&&(t={...t,...S(r)});const e=F(t);return{slowRouteMs:e.slowRouteMs,slowQueryMs:e.slowQueryMs,nPlusOne:e.nPlusOne,dbInLoop:e.dbInLoop,slowPageMs:e.slowPageMs}}M(performanceLimits,"performanceLimits"),c(performanceLimits,"performanceLimits");function S(i){const t={};for(const[e,r]of Object.entries(i))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[e]=r);return t}M(S,"P"),c(S,"resolveThresholdsOnly");const q=c(i=>i&&typeof i=="object"?i:{},"obj"),m=c(i=>typeof i=="string"&&i?i:void 0,"str"),f=c(i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,"num"),N=2e3,b=5e3,k=2e4,D=1e3,Q=1024,T=12,A=200;function z(i){let t=0;for(const[e,r]of i)t=Math.max(t,r+(i.get(e+1)??0));return t}M(z,"L"),c(z,"burstOf");const O=c(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function y(i,t,e,r){if(i.max=Math.max(i.max,t),t>=e&&(i.slow+=1,i.evidence.length<5&&i.evidence.push(r)),i.times.length<N)i.times.push(t);else{let o=0;for(let n=1;n<i.times.length;n++)i.times[n]<i.times[o]&&(o=n);t>i.times[o]&&(i.times[o]=t)}}M(y,"S"),c(y,"time");function P(i,t){return i.length?i[Math.min(i.length-1,Math.floor(i.length*t))]:0}M(P,"j"),c(P,"percentile");function x(i){const t=[...i.times].sort((e,r)=>e-r);return{count:i.count,timed:i.times.length,p50Ms:Math.round(P(t,.5)),p95Ms:Math.round(P(t,.95)),maxMs:Math.round(i.max),slow:i.slow}}M(x,"k"),c(x,"timing");function $(i,t,e){return i.includes("*")?new RegExp(`^${i.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(t):e?t===i:t.includes(i)}M($,"y"),c($,"matches");export class PerformanceWindow{static{M(this,"PerformanceWindow")}static{c(this,"PerformanceWindow")}constructor(t,e=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.streams=new Set,this.repeated=new Map,this.loops=[],this.sqlFiles=new Map,this.sqlUnlocated=new Set,this.routeSql=new Map,this.mostRuns=new Map,this.limits=t,this.waivers=e.filter(r=>typeof r?.why=="string"&&(r.route||r.sql||r.page))}add(t){const e=q(t.raw),r=e.kind;if(r!=="server-request"&&r!=="db-query"&&r!==SQL_DROPS_KIND&&r!=="loop"&&r!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,t.timestamp),this.to=Math.max(this.to,t.timestamp);const o=q(t.context),n=m(o.projectName)??m(e.project),u=m(o.requestId);r==="server-request"?this.request(t,e,n,u):r==="db-query"?this.statement(t,e,n,u):r===SQL_DROPS_KIND?this.dropped(t,e,n):r==="loop"?this.loop(t,e,u):this.page(t,e)}request(t,e,r,o){const n=q(e.request),u=m(n.method)??"?",l=m(n.route)??"?",d=`${u} ${l}`;let p=this.routes.get(d);if(!p){if(this.routes.size>=b)return;p={...O(),method:u,route:l,...r?{project:r}:{},errors:0,streaming:0},this.routes.set(d,p)}p.count+=1;const h=f(n.status);h!==void 0&&h>=500&&(p.errors+=1);const w=f(n.durationMs);n.streaming===!0?p.streaming+=1:w!==void 0&&y(p,w,this.limits.slowRouteMs,t.id),o&&(this.routeOf.set(o,d),this.routeOf.size>k&&this.routeOf.delete(this.routeOf.keys().next().value),n.streaming===!0&&(this.streams.add(o),this.streams.size>k&&this.streams.delete(this.streams.keys().next().value)),this.close(o))}sqlEntry(t,e,r){let o=this.sql.get(t);if(!o&&this.sql.size<b){o={...O(),failed:0,dropped:0};const n=m(e.sqlName),u=m(e.op),l=m(e.table);n&&(o.name=n),r&&(o.project=r),u&&(o.op=u),l&&(o.table=l),this.sql.set(t,o)}return o}statement(t,e,r,o){const n=m(e.statement)??m(e.query),u=m(e.sqlId)??n?.slice(0,300);if(!u)return;const l=1+Math.max(0,f(e.floodSuppressed)??0),d=this.sqlEntry(u,e,r);if(d){this.located(u,e.site),d.count+=l,!d.text&&n&&(d.text=n.slice(0,300)),e.error!==void 0&&e.error!==null&&(d.failed+=1);const a=f(e.durationMs);a!==void 0&&y(d,a,this.limits.slowQueryMs,t.id)}if(!o)return;let p=this.open.get(o);p||(this.open.size>=k&&this.close(this.open.keys().next().value),p=new Map,this.open.set(o,p));let h=p.get(u);h?h.n+=l:p.set(u,h={n:l,first:t.id,seconds:new Map});const w=Math.floor(t.timestamp/D),s=h.seconds.get(w);s!==void 0?h.seconds.set(w,s+l):h.seconds.size<Q&&h.seconds.set(w,l)}located(t,e){const r=(Array.isArray(q(e).frames)?q(e).frames:[]).slice(0,3).map(n=>m(q(n).file)).filter(n=>!!n);if(!r.length){this.sqlUnlocated.add(t);return}let o=this.sqlFiles.get(t);o||this.sqlFiles.set(t,o=new Set);for(const n of r)o.size<T&&o.add(n.slice(0,1024))}dropped(t,e,r){const o=f(e.slowMs)??-1/0,n=c((p,h)=>Math.max(this.limits.slowQueryMs<=o?Math.max(0,f(p.slow)??0):0,h>=this.limits.slowQueryMs?1:0),"slowOf"),u=Array.isArray(e.shapes)?e.shapes:[];for(const p of u){const h=q(p),w=m(h.sqlId),s=Math.max(0,f(h.runs)??0);if(!w||!s)continue;const a=Math.max(0,f(h.maxMs)??0),g=Math.max(0,f(h.failed)??0),j=n(h,a);this.drops.runs+=s,this.drops.slow+=j,this.drops.failed+=g;const v=this.sqlEntry(w,h,r);if(v){if(v.count+=s,v.dropped+=s,v.failed+=g,v.max=Math.max(v.max,a),!v.text){const R=m(h.query);R&&(v.text=R.slice(0,300))}j&&(v.slow+=j,v.evidence.length<5&&v.evidence.push(t.id))}}const l=q(e.overflow),d=Math.max(0,f(l.runs)??0);if(d){const p=Math.max(0,f(l.maxMs)??0);this.drops.runs+=d,this.drops.slow+=n(l,p),this.drops.failed+=Math.max(0,f(l.failed)??0)}}close(t){const e=this.open.get(t);if(!e)return;this.open.delete(t);const r=this.routeOf.get(t),o=r??"a request with no route seen",n=this.streams.delete(t);let u=r?this.routeSql.get(r):void 0;r&&!u&&this.routeSql.size<b&&this.routeSql.set(r,u=new Set);for(const[l,{n:d,first:p,seconds:h}]of e){const w=n?z(h):d;u&&u.size<A&&u.add(l);const s=`${o}\0${l}`;if(w>(this.mostRuns.get(s)??0)&&(this.mostRuns.has(s)||this.mostRuns.size<b*4)&&this.mostRuns.set(s,w),w<this.limits.nPlusOne)continue;const a=`${o}\0${l}`,g=this.repeated.get(a)??{route:o,sql:l,worst:0,requests:0,streams:0,evidence:[]};g.worst=Math.max(g.worst,w),g.requests+=1,n&&(g.streams+=1),g.evidence.length<5&&g.evidence.push(p),this.repeated.set(a,g)}}loop(t,e,r){const o=q(e.loop),n=L(o);if(n<=this.limits.dbInLoop)return;const u=f(o.dbCallsInsideLoop)??0,l=(r&&this.routeOf.get(r))??t.title??"a loop";this.loops.length>=200||this.loops.push({id:`db-in-loop:${l}`,kind:"db-in-loop",subject:l,measured:n<u?`${n} DB calls within two seconds of one loop of a stream (${u} over its life)`:`${n} DB calls inside one loop (${f(o.iterations)??"?"} iterations)`,limit:`more than ${this.limits.dbInLoop} (dbInLoop)`,evidence:[t.id],about:{route:l},value:n})}page(t,e){if(e.phase!=="ready"||e.cause==="hmr")return;const r=m(e.app)??"?",o=m(e.pattern)??m(e.path)??"?",n=`${r} ${o}`;let u=this.pages.get(n);if(!u){if(this.pages.size>=b)return;u={...O(),app:r,path:o},this.pages.set(n,u)}u.count+=1;const l=e.nav==="hard"?f(e.appReadyMs)??f(e.readyMs):f(e.readyMs);l!==void 0&&y(u,l,this.limits.slowPageMs,t.id)}waiverOf(t){for(const e of this.waivers)if(e.route&&t.route&&$(e.route,t.route,!0)||e.sql&&t.sql&&($(e.sql,t.sql,!1)||t.sqlText!==void 0&&$(e.sql,t.sqlText,!1))||e.page&&t.page&&$(e.page,t.page,!0))return e.why}report(t){for(const s of[...this.open.keys()])this.close(s);const e=this.limits,r=[],o=c((s,a="runs")=>`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.timed} ${a} at or above`,"slowWords"),n=[...this.routes.entries()].map(([s,a])=>({key:s,method:a.method,route:a.route,...a.project?{project:a.project}:{},errors:a.errors,streaming:a.streaming,...x(a),evidence:a.evidence}));for(const s of n)s.slow>1&&r.push({breach:{id:`slow-route:${s.key}`,kind:"slow-route",subject:s.key,measured:o(s),limit:`${e.slowRouteMs} ms (slowRouteMs)`,evidence:s.evidence,about:{route:s.key},value:s.p95Ms},about:{route:s.key}});const u=[...this.sql.entries()].map(([s,a])=>({key:s,...a.name?{name:a.name}:{},...a.project?{project:a.project}:{},...a.op?{op:a.op}:{},...a.table?{table:a.table}:{},...a.text?{text:a.text}:{},failed:a.failed,...a.dropped?{dropped:a.dropped}:{},...x(a),evidence:a.evidence}));for(const s of u){const a=s.dropped?`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.count} runs at or above (${s.dropped} counted from the service's drop record, not timed)`:o(s);s.slow>1&&r.push({breach:{id:`slow-query:${s.key}`,kind:"slow-query",subject:s.name??s.key,measured:a,limit:`${e.slowQueryMs} ms (slowQueryMs)`,evidence:s.evidence,about:{sql:s.key},value:s.p95Ms},about:{sql:s.key,...s.text?{sqlText:s.text}:{}}})}for(const s of this.repeated.values()){const a=this.sql.get(s.sql);r.push({breach:{id:`n+1-query:${s.route}:${s.sql}`,kind:"n+1-query",subject:`${s.route} runs ${a?.name??s.sql}`,measured:s.streams===s.requests?`up to ${s.worst}\xD7 in one burst of a stream, within two seconds (${s.streams} stream${s.streams===1?"":"s"})`:`up to ${s.worst}\xD7 in one request (${s.requests} request${s.requests===1?"":"s"})`,limit:`fewer than ${e.nPlusOne} (nPlusOne)`,evidence:s.evidence,about:{route:s.route,sql:s.sql},value:s.worst},about:{route:s.route,sql:s.sql,...a?.text?{sqlText:a.text}:{}}})}for(const s of this.loops)r.push({breach:s,about:{route:s.subject}});const l=[...this.pages.entries()].map(([s,a])=>({key:s,app:a.app,path:a.path,...x(a),evidence:a.evidence}));for(const s of l)s.slow>1&&r.push({breach:{id:`slow-page:${s.key}`,kind:"slow-page",subject:s.key,measured:o(s,"visits"),limit:`${e.slowPageMs} ms (slowPageMs)`,evidence:s.evidence,about:{page:s.key},value:s.p95Ms},about:{page:s.path}});const d=[],p=[];for(const{breach:s,about:a}of r){const g=this.waiverOf(a);g?p.push({...s,waived:g}):d.push(s)}const h=c(s=>{const{evidence:a,...g}=s;return g},"strip"),w=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:t??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...e},verdict:d.length?"fail":w?"pass":"unmeasured",breaches:d,waived:p,...this.drops.runs?{dropped:{...this.drops}}:{},routes:n.map(h).sort((s,a)=>a.p95Ms-s.p95Ms),sql:u.map(h).sort((s,a)=>a.p95Ms-s.p95Ms),pages:l.map(h).sort((s,a)=>a.p95Ms-s.p95Ms)}}locate(t){if(!t||t.page)return;const e=c(n=>this.sqlUnlocated.has(n)||!this.sqlFiles.get(n)?.size?void 0:[...this.sqlFiles.get(n)],"ofSql");if(t.sql)return e(t.sql);if(!t.route)return;const r=this.routeSql.get(t.route);if(!r?.size)return;const o=new Set;for(const n of r){const u=e(n);if(!u)return;for(const l of u)o.add(l)}return[...o]}baseline(t){const e=this.report(t),r={};for(const o of this.loops)o.about?.route&&(o.value??0)>(r[o.about.route]??0)&&(r[o.about.route]=o.value??0);return{limits:{...this.limits},window:e.window,events:e.events,routes:Object.fromEntries(e.routes.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),sql:Object.fromEntries(e.sql.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),pages:Object.fromEntries(e.pages.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),repeats:Object.fromEntries(this.mostRuns),loops:r}}}export function describePerformance(i,t=12){const e=i.limits,r=[i.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${i.verdict==="pass"?"PASS":`FAIL \u2014 ${i.breaches.length} breach${i.breaches.length===1?"":"es"}`} over ${i.routes.length} route${i.routes.length===1?"":"s"}, ${i.sql.length} statement${i.sql.length===1?"":"s"}, ${i.pages.length} page${i.pages.length===1?"":"s"} (limits: route ${e.slowRouteMs} ms, query ${e.slowQueryMs} ms, N+1 ${e.nPlusOne}, DB in a loop ${e.dbInLoop}, page ${e.slowPageMs} ms).`],o=i.dropped;o&&r.push(`${o.runs} statement run${o.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${o.slow} slow, ${o.failed} failed \u2014 counted above, not in the percentiles.`);for(const n of i.breaches.slice(0,t))r.push(`- ${n.kind} \xB7 ${n.subject}: ${n.measured}; limit ${n.limit}`);return i.breaches.length>t&&r.push(`- \u2026 ${i.breaches.length-t} more`),i.waived.length&&r.push(`Waived by .lensmcp/team/performance.json: ${i.waived.map(n=>`${n.kind} \xB7 ${n.subject} (${n.waived})`).slice(0,t).join("; ")}`),r.join(`
|
|
2
|
-
`)}M(describePerformance,"describePerformance"),
|
|
1
|
+
"use strict";var N=Object.defineProperty;var M=(r,o)=>N(r,"name",{value:o,configurable:!0});var F=Object.defineProperty,w=M((r,o)=>F(r,"name",{value:o,configurable:!0}),"m");import{dbLoopBreaks as A,dbLoopClass as Q,loopDbCalls as R,loopRepeatsLimit as T}from"./patterns.js";import{resolveThresholds as B}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...r){let o={};for(const i of r)i&&(o={...o,...I(i)});const s=B(o);return{slowRouteMs:s.slowRouteMs,slowQueryMs:s.slowQueryMs,nPlusOne:s.nPlusOne,dbInLoop:s.dbInLoop,slowPageMs:s.slowPageMs}}M(performanceLimits,"performanceLimits"),w(performanceLimits,"performanceLimits");function I(r){const o={};for(const[s,i]of Object.entries(r))typeof i=="number"&&Number.isFinite(i)&&i>=0&&(o[s]=i);return o}M(I,"F"),w(I,"resolveThresholdsOnly");const b=w(r=>r&&typeof r=="object"?r:{},"obj"),f=w(r=>typeof r=="string"&&r?r:void 0,"str"),g=w(r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,"num"),C=2e3,x=5e3,k=2e4,_=1e3,U=4,K=2e3,V=1e3,X=1024,G=12,H=200;function W(r){let o=0;for(const[s,i]of r)o=Math.max(o,i+(r.get(s+1)??0));return o}M(W,"V"),w(W,"burstOf");const S=w(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function L(r,o,s,i){if(r.max=Math.max(r.max,o),o>=s&&(r.slow+=1,r.evidence.length<5&&r.evidence.push(i)),r.times.length<C)r.times.push(o);else{let t=0;for(let n=1;n<r.times.length;n++)r.times[n]<r.times[t]&&(t=n);o>r.times[t]&&(r.times[t]=o)}}M(L,"k"),w(L,"time");function z(r,o){return r.length?r[Math.min(r.length-1,Math.floor(r.length*o))]:0}M(z,"E"),w(z,"percentile");function O(r){const o=[...r.times].sort((s,i)=>s-i);return{count:r.count,timed:r.times.length,p50Ms:Math.round(z(o,.5)),p95Ms:Math.round(z(o,.95)),maxMs:Math.round(r.max),slow:r.slow}}M(O,"O"),w(O,"timing");function j(r,o,s){return r.includes("*")?new RegExp(`^${r.split("*").map(i=>i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(o):s?o===r:o.includes(r)}M(j,"S"),w(j,"matches");export class PerformanceWindow{static{M(this,"PerformanceWindow")}static{w(this,"PerformanceWindow")}constructor(o,s=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.streams=new Set,this.repeated=new Map,this.loops=new Map,this.loopsWaiting=new Map,this.unjudgedLoops=0,this.sqlFiles=new Map,this.sqlUnlocated=new Set,this.routeSql=new Map,this.mostRuns=new Map,this.limits=o,this.waivers=s.filter(i=>typeof i?.why=="string"&&(i.route||i.sql||i.page))}add(o){const s=b(o.raw),i=s.kind;if(i!=="server-request"&&i!=="db-query"&&i!==SQL_DROPS_KIND&&i!=="loop"&&i!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,o.timestamp),this.to=Math.max(this.to,o.timestamp);const t=b(o.context),n=f(t.projectName)??f(s.project),l=f(t.requestId);i==="server-request"?this.request(o,s,n,l):i==="db-query"?this.statement(o,s,n,l):i===SQL_DROPS_KIND?this.dropped(o,s,n):i==="loop"?this.loop(o,s,l):this.page(o,s)}request(o,s,i,t){const n=b(s.request),l=f(n.method)??"?",u=f(n.route)??"?",h=`${l} ${u}`;let p=this.routes.get(h);if(!p){if(this.routes.size>=x)return;p={...S(),method:l,route:u,...i?{project:i}:{},errors:0,streaming:0},this.routes.set(h,p)}p.count+=1;const d=g(n.status);d!==void 0&&d>=500&&(p.errors+=1);const v=g(n.durationMs);if(n.streaming===!0?p.streaming+=1:v!==void 0&&L(p,v,this.limits.slowRouteMs,o.id),t){this.routeOf.set(t,h),this.routeOf.size>k&&this.routeOf.delete(this.routeOf.keys().next().value),n.streaming===!0&&(this.streams.add(t),this.streams.size>k&&this.streams.delete(this.streams.keys().next().value)),this.close(t);const m=this.loopsWaiting.get(t);if(m){this.loopsWaiting.delete(t);for(const $ of m)this.foldLoop(h,$)}}}sqlEntry(o,s,i){let t=this.sql.get(o);if(!t&&this.sql.size<x){t={...S(),failed:0,dropped:0};const n=f(s.sqlName),l=f(s.op),u=f(s.table);n&&(t.name=n),i&&(t.project=i),l&&(t.op=l),u&&(t.table=u),this.sql.set(o,t)}return t}statement(o,s,i,t){const n=f(s.statement)??f(s.query),l=f(s.sqlId)??n?.slice(0,300);if(!l)return;const u=1+Math.max(0,g(s.floodSuppressed)??0),h=this.sqlEntry(l,s,i);if(h){this.located(l,s.site),h.count+=u,!h.text&&n&&(h.text=n.slice(0,300)),s.error!==void 0&&s.error!==null&&(h.failed+=1);const $=g(s.durationMs);$!==void 0&&L(h,$,this.limits.slowQueryMs,o.id)}if(!t)return;let p=this.open.get(t);p||(this.open.size>=k&&this.close(this.open.keys().next().value),p=new Map,this.open.set(t,p));let d=p.get(l);d?d.n+=u:p.set(l,d={n:u,first:o.id,seconds:new Map,values:new Set}),d.values.size<U&&d.values.add(Array.isArray(s.params)?s.params.map(String).join(""):"");const v=Math.floor(o.timestamp/_),m=d.seconds.get(v);m!==void 0?d.seconds.set(v,m+u):d.seconds.size<X&&d.seconds.set(v,u)}located(o,s){const i=(Array.isArray(b(s).frames)?b(s).frames:[]).slice(0,3).map(n=>f(b(n).file)).filter(n=>!!n);if(!i.length){this.sqlUnlocated.add(o);return}let t=this.sqlFiles.get(o);t||this.sqlFiles.set(o,t=new Set);for(const n of i)t.size<G&&t.add(n.slice(0,1024))}dropped(o,s,i){const t=g(s.slowMs)??-1/0,n=w((p,d)=>Math.max(this.limits.slowQueryMs<=t?Math.max(0,g(p.slow)??0):0,d>=this.limits.slowQueryMs?1:0),"slowOf"),l=Array.isArray(s.shapes)?s.shapes:[];for(const p of l){const d=b(p),v=f(d.sqlId),m=Math.max(0,g(d.runs)??0);if(!v||!m)continue;const $=Math.max(0,g(d.maxMs)??0),e=Math.max(0,g(d.failed)??0),a=n(d,$);this.drops.runs+=m,this.drops.slow+=a,this.drops.failed+=e;const c=this.sqlEntry(v,d,i);if(c){if(c.count+=m,c.dropped+=m,c.failed+=e,c.max=Math.max(c.max,$),!c.text){const q=f(d.query);q&&(c.text=q.slice(0,300))}a&&(c.slow+=a,c.evidence.length<5&&c.evidence.push(o.id))}}const u=b(s.overflow),h=Math.max(0,g(u.runs)??0);if(h){const p=Math.max(0,g(u.maxMs)??0);this.drops.runs+=h,this.drops.slow+=n(u,p),this.drops.failed+=Math.max(0,g(u.failed)??0)}}close(o){const s=this.open.get(o);if(!s)return;this.open.delete(o);const i=this.routeOf.get(o),t=i??"a request with no route seen",n=this.streams.delete(o);let l=i?this.routeSql.get(i):void 0;i&&!l&&this.routeSql.size<x&&this.routeSql.set(i,l=new Set);for(const[u,{n:h,first:p,seconds:d,values:v}]of s){const m=n?W(d):h;l&&l.size<H&&l.add(u);const $=`${t}\0${u}`;if(m>(this.mostRuns.get($)??0)&&(this.mostRuns.has($)||this.mostRuns.size<x*4)&&this.mostRuns.set($,m),m<this.limits.nPlusOne)continue;const e=`${t}\0${u}`,a=this.repeated.get(e)??{route:t,sql:u,worst:0,requests:0,streams:0,varying:0,evidence:[]};a.worst=Math.max(a.worst,m),a.requests+=1,n&&(a.streams+=1),v.size>1&&(a.varying+=1),a.evidence.length<5&&a.evidence.push(p),this.repeated.set(e,a)}}loop(o,s,i){const t=b(s.loop),n=Q(t);if(!n){R(t)>this.limits.dbInLoop&&(this.unjudgedLoops+=1);return}if(!A(t,this.limits))return;const l=f(t.method)??/^(?:loop|repeated read) in (\S+) \(/.exec(o.title??"")?.[1]??"?",u={id:o.id,...i?{requestId:i}:{},sql:f(t.sqlId)??"?",site:l,class:n,value:R(t),total:g(t.dbCallsInsideLoop)??0,calls:g(t.calls),distinct:g(t.distinctStatements)},h=i?this.routeOf.get(i):void 0;if(h||!i){this.foldLoop(h??"work outside a request",u);return}let p=this.loopsWaiting.get(i);if(!p){if(this.loopsWaiting.size>=k){const[d,v]=this.loopsWaiting.entries().next().value;this.loopsWaiting.delete(d);for(const m of v)this.foldLoop("a request with no route seen",m)}this.loopsWaiting.set(i,p=[])}p.length<50&&p.push(u)}foldLoop(o,s){const i=`${o}\0${s.sql}\0${s.site}`;let t=this.loops.get(i);if(!t){if(this.loops.size>=K)return;this.loops.set(i,t={route:o,sql:s.sql,site:s.site,class:s.class,worst:0,total:0,requests:new Set,seen:0,evidence:[]})}t.seen+=1,s.requestId&&t.requests.size<V&&t.requests.add(s.requestId),s.class==="loop"&&(t.class="loop"),s.value>t.worst&&(t.worst=s.value,t.total=s.total,s.calls!==void 0&&(t.calls=s.calls),s.distinct!==void 0&&(t.distinct=s.distinct)),t.evidence.length<5&&t.evidence.push(s.id)}page(o,s){if(s.phase!=="ready"||s.cause==="hmr")return;const i=f(s.app)??"?",t=f(s.pattern)??f(s.path)??"?",n=`${i} ${t}`;let l=this.pages.get(n);if(!l){if(this.pages.size>=x)return;l={...S(),app:i,path:t},this.pages.set(n,l)}l.count+=1;const u=s.nav==="hard"?g(s.appReadyMs)??g(s.readyMs):g(s.readyMs);u!==void 0&&L(l,u,this.limits.slowPageMs,o.id)}waiverOf(o){for(const s of this.waivers)if(s.route&&o.route&&j(s.route,o.route,!0)||s.sql&&o.sql&&(j(s.sql,o.sql,!1)||o.sqlText!==void 0&&j(s.sql,o.sqlText,!1))||s.page&&o.page&&j(s.page,o.page,!0))return s.why}report(o){for(const e of[...this.open.keys()])this.close(e);for(const[e,a]of[...this.loopsWaiting]){this.loopsWaiting.delete(e);for(const c of a)this.foldLoop("a request with no route seen",c)}const s=this.limits,i=[],t=w((e,a="runs")=>`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.timed} ${a} at or above`,"slowWords"),n=[...this.routes.entries()].map(([e,a])=>({key:e,method:a.method,route:a.route,...a.project?{project:a.project}:{},errors:a.errors,streaming:a.streaming,...O(a),evidence:a.evidence}));for(const e of n)e.slow>1&&i.push({breach:{id:`slow-route:${e.key}`,kind:"slow-route",subject:e.key,measured:t(e),limit:`${s.slowRouteMs} ms (slowRouteMs)`,evidence:e.evidence,about:{route:e.key},value:e.p95Ms},about:{route:e.key}});const l=[...this.sql.entries()].map(([e,a])=>({key:e,...a.name?{name:a.name}:{},...a.project?{project:a.project}:{},...a.op?{op:a.op}:{},...a.table?{table:a.table}:{},...a.text?{text:a.text}:{},failed:a.failed,...a.dropped?{dropped:a.dropped}:{},...O(a),evidence:a.evidence}));for(const e of l){const a=e.dropped?`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.count} runs at or above (${e.dropped} counted from the service's drop record, not timed)`:t(e);e.slow>1&&i.push({breach:{id:`slow-query:${e.key}`,kind:"slow-query",subject:e.name??e.key,measured:a,limit:`${s.slowQueryMs} ms (slowQueryMs)`,evidence:e.evidence,about:{sql:e.key},value:e.p95Ms},about:{sql:e.key,...e.text?{sqlText:e.text}:{}}})}const u=new Map;for(const e of this.loops.values()){const a=`${e.route}\0${e.sql}`;this.repeated.has(a)&&u.set(a,[...u.get(a)??[],e])}const h=w(e=>e.calls!==void 0&&e.distinct!==void 0?` (its ${e.calls} DB calls, ${e.distinct} statement${e.distinct===1?"":"s"})`:"","ofCalls");for(const e of this.repeated.values()){const a=this.sql.get(e.sql),c=(u.get(`${e.route}\0${e.sql}`)??[]).sort((y,E)=>E.worst-y.worst),q=c[0],P=e.varying>0||c.some(y=>y.class==="loop")?"loop":"repeated-read",D=q?`; in ${c.map(y=>y.site).slice(0,3).join(", ")}${h(q)}`:"";i.push({breach:{id:`n+1-query:${e.route}:${e.sql}`,kind:"n+1-query",subject:`${e.route} runs ${a?.name??e.sql}`,measured:`${e.streams===e.requests?`up to ${e.worst}\xD7 in one burst of a stream, within two seconds (${e.streams} stream${e.streams===1?"":"s"})`:`up to ${e.worst}\xD7 in one request (${e.requests} request${e.requests===1?"":"s"})`}, ${P==="loop"?"varying values":"the same values each time"}${D}`,limit:`fewer than ${s.nPlusOne} (nPlusOne)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:Math.max(e.worst,q?.worst??0),class:P,requests:e.requests,...q?{site:q.site,...q.calls!==void 0?{calls:q.calls}:{},...q.distinct!==void 0?{distinctStatements:q.distinct}:{}}:{}},about:{route:e.route,sql:e.sql,...a?.text?{sqlText:a.text}:{}}})}for(const e of this.loops.values()){if(this.repeated.has(`${e.route}\0${e.sql}`))continue;const a=this.sql.get(e.sql),c=e.requests.size,q=e.worst<e.total?`up to ${e.worst}\xD7 within two seconds of one call of a stream's ${e.site} (${e.total} over its life)`:`up to ${e.worst}\xD7 in one call of ${e.site}`;i.push({breach:{id:`db-in-loop:${e.route}:${e.sql}:${e.site}`,kind:"db-in-loop",subject:`${e.route} runs ${a?.name??e.sql} in ${e.site}`,measured:`${e.class==="loop"?"loop":"repeated read"}: one statement ${q}, ${e.class==="loop"?"varying values":"the same values each time"}${h(e)} \u2014 ${e.seen} time${e.seen===1?"":"s"}${c?`, \xD7${c} request${c===1?"":"s"}`:""}`,limit:e.class==="loop"?`fewer than ${T(s)} repeats of one statement in one method (nPlusOne)`:`at most ${s.dbInLoop} repeats of one statement with the same values (dbInLoop)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:e.worst,class:e.class,requests:c,site:e.site,...e.calls!==void 0?{calls:e.calls}:{},...e.distinct!==void 0?{distinctStatements:e.distinct}:{}},about:{route:e.route,sql:e.sql,...a?.text?{sqlText:a.text}:{}}})}const p=[...this.pages.entries()].map(([e,a])=>({key:e,app:a.app,path:a.path,...O(a),evidence:a.evidence}));for(const e of p)e.slow>1&&i.push({breach:{id:`slow-page:${e.key}`,kind:"slow-page",subject:e.key,measured:t(e,"visits"),limit:`${s.slowPageMs} ms (slowPageMs)`,evidence:e.evidence,about:{page:e.key},value:e.p95Ms},about:{page:e.path}});const d=[],v=[];for(const{breach:e,about:a}of i){const c=this.waiverOf(a);c?v.push({...e,waived:c}):d.push(e)}const m=w(e=>{const{evidence:a,...c}=e;return c},"strip"),$=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:o??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...s},verdict:d.length?"fail":$?"pass":"unmeasured",breaches:d,waived:v,...this.drops.runs?{dropped:{...this.drops}}:{},...this.unjudgedLoops?{unjudgedLoops:this.unjudgedLoops}:{},routes:n.map(m).sort((e,a)=>a.p95Ms-e.p95Ms),sql:l.map(m).sort((e,a)=>a.p95Ms-e.p95Ms),pages:p.map(m).sort((e,a)=>a.p95Ms-e.p95Ms)}}locate(o){if(!o||o.page)return;const s=w(n=>this.sqlUnlocated.has(n)||!this.sqlFiles.get(n)?.size?void 0:[...this.sqlFiles.get(n)],"ofSql");if(o.sql)return s(o.sql);if(!o.route)return;const i=this.routeSql.get(o.route);if(!i?.size)return;const t=new Set;for(const n of i){const l=s(n);if(!l)return;for(const u of l)t.add(u)}return[...t]}baseline(o){const s=this.report(o),i={};for(const t of this.loops.values()){const n=`${t.route}\0${t.sql}`;t.worst>(i[n]??0)&&(i[n]=t.worst)}return{limits:{...this.limits},window:s.window,events:s.events,routes:Object.fromEntries(s.routes.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),sql:Object.fromEntries(s.sql.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),pages:Object.fromEntries(s.pages.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),repeats:Object.fromEntries(this.mostRuns),loops:i}}}export function describePerformance(r,o=12){const s=r.limits,i=[r.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${r.verdict==="pass"?"PASS":`FAIL \u2014 ${r.breaches.length} breach${r.breaches.length===1?"":"es"}`} over ${r.routes.length} route${r.routes.length===1?"":"s"}, ${r.sql.length} statement${r.sql.length===1?"":"s"}, ${r.pages.length} page${r.pages.length===1?"":"s"} (limits: route ${s.slowRouteMs} ms, query ${s.slowQueryMs} ms, N+1 ${s.nPlusOne}, DB in a loop ${s.dbInLoop}, page ${s.slowPageMs} ms).`],t=r.dropped;t&&i.push(`${t.runs} statement run${t.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${t.slow} slow, ${t.failed} failed \u2014 counted above, not in the percentiles.`);for(const n of r.breaches.slice(0,o))i.push(`- ${n.kind}${n.class?` [${n.class}]`:""} \xB7 ${n.subject}: ${n.measured}; limit ${n.limit}`);return r.breaches.length>o&&i.push(`- \u2026 ${r.breaches.length-o} more`),r.unjudgedLoops&&i.push(`${r.unjudgedLoops} loop report${r.unjudgedLoops===1?"":"s"} from an older @lensmcp/nest-instrumentation not judged: it counted every DB call of a method, so it could not tell a loop from straight-line code (N+1s are still judged per request).`),r.waived.length&&i.push(`Waived by .lensmcp/team/performance.json: ${r.waived.map(n=>`${n.kind} \xB7 ${n.subject} (${n.waived})`).slice(0,o).join("; ")}`),i.join(`
|
|
2
|
+
`)}M(describePerformance,"describePerformance"),w(describePerformance,"describePerformance");
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type QueueSignal = 'delayed' | 'waiting-children' | 'rate-limited' | 'waiting';
|
|
2
|
+
export declare const QUEUE_SIGNALS: readonly QueueSignal[];
|
|
3
|
+
export declare const RATE_LIMIT_MESSAGE = "bullmq:rateLimitExceeded";
|
|
4
|
+
export declare function isControlFlowThrow(err: unknown): QueueSignal | undefined;
|
|
5
|
+
export declare function queueSignalOf(status: unknown): QueueSignal | undefined;
|
|
6
|
+
export declare const queueSignalTitle: (signal: QueueSignal) => string;
|
|
7
|
+
export declare function queueSignalWords(signal: QueueSignal, delayMs?: number): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var s=Object.defineProperty;var i=(e,t)=>s(e,"name",{value:t,configurable:!0});var g=Object.defineProperty,n=i((e,t)=>g(e,"name",{value:t,configurable:!0}),"n");export const QUEUE_SIGNALS=["delayed","waiting-children","rate-limited","waiting"];const l=new Map([["DelayedError","delayed"],["WaitingChildrenError","waiting-children"],["WaitingError","waiting"]]);export const RATE_LIMIT_MESSAGE="bullmq:rateLimitExceeded";export function isControlFlowThrow(e){try{if(!e||typeof e!="object")return;const t=e;if(t.message===RATE_LIMIT_MESSAGE)return"rate-limited";const o=typeof t.name=="string"?l.get(t.name):void 0;if(o)return o;for(let r=Object.getPrototypeOf(e),a=0;r&&r!==Error.prototype&&a<8;r=Object.getPrototypeOf(r),a+=1){const u=r.constructor?.name,d=typeof u=="string"?l.get(u):void 0;if(d)return d}}catch{return}}i(isControlFlowThrow,"isControlFlowThrow"),n(isControlFlowThrow,"isControlFlowThrow");export function queueSignalOf(e){return typeof e=="string"&&QUEUE_SIGNALS.includes(e)?e:void 0}i(queueSignalOf,"queueSignalOf"),n(queueSignalOf,"queueSignalOf");const c={delayed:"re-delayed","waiting-children":"waiting for its children","rate-limited":"rate-limited",waiting:"back to wait"};export const queueSignalTitle=n(e=>c[e],"queueSignalTitle");const f=n(e=>e<1e3?`${Math.round(e)} ms`:e<6e4?`${Math.round(e/1e3)} s`:e<36e5?`${Math.round(e/6e4)} min`:`${Math.round(e/36e5)} h`,"span");export function queueSignalWords(e,t){return e!=="delayed"?c[e]:`asked to run again${typeof t=="number"&&Number.isFinite(t)&&t>=0?` in ${f(t)}`:""}`}i(queueSignalWords,"queueSignalWords"),n(queueSignalWords,"queueSignalWords");
|
package/lib/stores.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)):
|
|
1
|
+
"use strict";var y=Object.defineProperty;var p=(t,e)=>y(t,"name",{value:e,configurable:!0});var x=Object.defineProperty,l=p((t,e)=>x(t,"name",{value:e,configurable:!0}),"u");import{readFileSync as U}from"node:fs";import{join as v}from"node:path";import{readWorkspaceConfig as A}from"./lens-config.js";const R=/^[A-Za-z0-9_-]+$/,j=new Set(["kind","url","databases","lens","run"]);export function readStoresDecl(t){const e=A(t).stores;return e===void 0?{stores:{},errors:[],notes:[]}:validateStoresDecl(e)}p(readStoresDecl,"readStoresDecl"),l(readStoresDecl,"readStoresDecl");export function validateStoresDecl(t){const e=[],n=[],i={};if(!t||typeof t!="object"||Array.isArray(t))return{stores:i,errors:["`lensmcp.stores` must be an object"],notes:n};for(const[s,a]of Object.entries(t)){const r=`stores.${s}`;if(!R.test(s)){e.push(`${r}: a store name is letters, digits, '-' and '_'`);continue}if(!a||typeof a!="object"||Array.isArray(a)){e.push(`${r}: must be an object`);continue}const o=a,f=o.kind;if(f!=="postgres"&&f!=="redis"){e.push(`${r}.kind: one of "postgres", "redis"`);continue}const h=typeof o.url=="string"?o.url.trim():"";if(!h){e.push(`${r}.url: the connection URL is required (e.g. "\${${f==="postgres"?"PG_URL":"REDIS_URL"}}")`);continue}const m=o.databases??[];if(!Array.isArray(m)||!m.every(u=>typeof u=="string"&&u.trim())){e.push(`${r}.databases: a list of URLs or database names`);continue}if(m.length&&f!=="postgres"){e.push(`${r}.databases: only a postgres store has databases`);continue}const d=o.lens??{};if(!d||typeof d!="object"||Array.isArray(d)){e.push(`${r}.lens: must be an object`);continue}const c=d;if(c.url!==void 0&&(typeof c.url!="string"||!c.url.trim())){e.push(`${r}.lens.url: a connection URL`);continue}if(c.read!==void 0&&typeof c.read!="boolean"){e.push(`${r}.lens.read: true or false`);continue}if(c.prepare!==void 0&&typeof c.prepare!="boolean"){e.push(`${r}.lens.prepare: true or false`);continue}o.run!==void 0&&n.push(`${r}.run: planned \u2014 lensmcp does not start stores yet; the store is used as declared`);for(const u of Object.keys(o))j.has(u)||n.push(`${r}.${u}: not a store setting \u2014 ignored`);i[s]={kind:f,url:h,databases:m.map(u=>u.trim()),lens:{...typeof c.url=="string"?{url:c.url.trim()}:{},read:c.read!==!1,prepare:c.prepare!==!1}}}return{stores:i,errors:e,notes:n}}p(validateStoresDecl,"validateStoresDecl"),l(validateStoresDecl,"validateStoresDecl");export function parseDotenv(t,e={}){const n={},i=l(s=>s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,r)=>n[r]??e[r]??""),"expand");for(const s of t.split(/\r?\n/)){const a=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(s);if(!a)continue;const r=a[1],o=a[2];o.startsWith("'")&&o.indexOf("'",1)>0?n[r]=o.slice(1,o.indexOf("'",1)):o.startsWith('"')&&o.indexOf('"',1)>0?n[r]=i(o.slice(1,o.indexOf('"',1)).replace(/\\n/g,`
|
|
2
|
+
`)):n[r]=i(o.replace(/\s+#.*$/,""))}return n}p(parseDotenv,"parseDotenv"),l(parseDotenv,"parseDotenv");function g(t,e){try{return parseDotenv(U(t,"utf8"),e)}catch{return{}}}p(g,"g"),l(g,"readDotenv");export function checkoutEnv(t,e=process.env){let n={};for(const s of[".env",".env.local"])n={...n,...g(v(t,s),{...n})};const i=Object.fromEntries(Object.entries(e).filter(s=>typeof s[1]=="string"));n={...n,...i};for(const s of[v(".lensmcp","instance.resources.env"),v(".lensmcp","instance.env")])n={...n,...g(v(t,s),{...n})};return n}p(checkoutEnv,"checkoutEnv"),l(checkoutEnv,"checkoutEnv");export function expandVars(t,e){const n=[];return{value:t.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(i,s)=>{const a=e[s];return(a===void 0||a==="")&&n.push(s),a??""}),missing:n}}p(expandVars,"expandVars"),l(expandVars,"expandVars");const $=l(t=>t.port||(t.protocol.startsWith("redis")?"6379":"5432"),"portOf");export function withDatabase(t,e){const n=new URL(t);return n.pathname=`/${e}`,n.toString()}p(withDatabase,"withDatabase"),l(withDatabase,"withDatabase");export function redactUrl(t){try{const e=new URL(t);return`${e.protocol}//${e.username?`${decodeURIComponent(e.username)}@`:""}${e.hostname}:${$(e)}${e.pathname}`}catch{return"(not a URL)"}}p(redactUrl,"redactUrl"),l(redactUrl,"redactUrl");export function resolveStores(t,e){return Object.entries(t).map(([n,i])=>{const s=expandVars(i.url,e),a=[...s.missing];let r;try{r=s.missing.length?void 0:new URL(s.value)}catch{r=void 0}const o=[];if(r&&i.kind==="postgres"){o.push({name:decodeURIComponent(r.pathname.replace(/^\//,""))||"postgres",url:s.value});for(const m of i.databases){const d=expandVars(m,e);if(d.missing.length){a.push(...d.missing);continue}const c=/^[a-z]+:\/\//i.test(d.value)?d.value:withDatabase(s.value,d.value);try{const u=decodeURIComponent(new URL(c).pathname.replace(/^\//,""));u&&!o.some(b=>b.name===u)&&o.push({name:u,url:c})}catch{}}}const f=i.lens.url?expandVars(i.lens.url,e):void 0;f?.missing.length&&a.push(...f.missing);const h=i.lens.read?a.length?`${[...new Set(a)].map(m=>`\${${m}}`).join(", ")} not set in this checkout`:r?void 0:"`url` is not a connection URL":"reading is off (`lens.read: false`)";return{name:n,kind:i.kind,server:r?`${r.hostname}:${$(r)}`:"?",databases:o,...h?{noRead:h}:{readUrl:f?.value||s.value},prepare:i.lens.prepare!==!1,missing:[...new Set(a)]}})}p(resolveStores,"resolveStores"),l(resolveStores,"resolveStores");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.26.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"module": "./index.js",
|
|
@@ -42,6 +42,16 @@
|
|
|
42
42
|
"import": "./lib/lens-dir.js",
|
|
43
43
|
"default": "./lib/lens-dir.js"
|
|
44
44
|
},
|
|
45
|
+
"./lens-store": {
|
|
46
|
+
"types": "./lib/lens-store.d.ts",
|
|
47
|
+
"import": "./lib/lens-store.js",
|
|
48
|
+
"default": "./lib/lens-store.js"
|
|
49
|
+
},
|
|
50
|
+
"./lens-config": {
|
|
51
|
+
"types": "./lib/lens-config.d.ts",
|
|
52
|
+
"import": "./lib/lens-config.js",
|
|
53
|
+
"default": "./lib/lens-config.js"
|
|
54
|
+
},
|
|
45
55
|
"./settings": {
|
|
46
56
|
"types": "./lib/settings.d.ts",
|
|
47
57
|
"import": "./lib/settings.js",
|
|
@@ -91,10 +101,15 @@
|
|
|
91
101
|
"types": "./lib/headless-flow.d.ts",
|
|
92
102
|
"import": "./lib/headless-flow.js",
|
|
93
103
|
"default": "./lib/headless-flow.js"
|
|
104
|
+
},
|
|
105
|
+
"./queue-signals": {
|
|
106
|
+
"types": "./lib/queue-signals.d.ts",
|
|
107
|
+
"import": "./lib/queue-signals.js",
|
|
108
|
+
"default": "./lib/queue-signals.js"
|
|
94
109
|
}
|
|
95
110
|
},
|
|
96
111
|
"dependencies": {
|
|
97
|
-
"@lensmcp/protocol-types": "1.
|
|
112
|
+
"@lensmcp/protocol-types": "1.26.1",
|
|
98
113
|
"tslib": "^2.3.0"
|
|
99
114
|
},
|
|
100
115
|
"license": "Apache-2.0",
|