@lensmcp/core 1.25.53 → 1.25.54
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/lib/flow-segments.d.ts +11 -0
- package/lib/flow-segments.js +1 -1
- package/lib/flow-shape.js +1 -1
- package/lib/resource-store.d.ts +6 -0
- package/lib/resource-store.js +1 -1
- package/package.json +2 -2
package/lib/flow-segments.d.ts
CHANGED
|
@@ -107,6 +107,11 @@ export interface FlowSegment {
|
|
|
107
107
|
hot?: string[];
|
|
108
108
|
/** Set when a request or burst was cut by the size cap. */
|
|
109
109
|
part?: SegmentPart;
|
|
110
|
+
/**
|
|
111
|
+
* Event-loop stalls stamped with this request that began after its response had finished (foodguard-192): in
|
|
112
|
+
* `eventIds`, but not in `start`/`end`/`durationMs` — they delayed nothing the request did.
|
|
113
|
+
*/
|
|
114
|
+
stallsAfterResponse?: number;
|
|
110
115
|
worstSeverity: 'debug' | 'info' | 'warning' | 'error' | 'fatal';
|
|
111
116
|
/**
|
|
112
117
|
* Whether this request's SQL on the bus is all of it — on a unit that ran SQL, and on the first
|
|
@@ -137,6 +142,12 @@ export interface FlowSegmentation {
|
|
|
137
142
|
/** The flow's SQL completeness boundary — absent when no request in it ran SQL. */
|
|
138
143
|
sql?: FlowSqlAccounting;
|
|
139
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* {@link lateStallsOf} over a flow's events, request by request: event id → ms after its request's response. Every
|
|
147
|
+
* call of one request id is read as one request (a script that reuses its id), so a stall between two of them is not
|
|
148
|
+
* after the response. Empty when the flow holds no stall.
|
|
149
|
+
*/
|
|
150
|
+
export declare function stallsAfterResponse(events: readonly BaseEvent[]): Map<string, number>;
|
|
140
151
|
export declare function segmentFlow(input: readonly BaseEvent[], options?: SegmentOptions): FlowSegmentation;
|
|
141
152
|
/** Whether the SQL the bus holds for a request (or a flow) is all of it. */
|
|
142
153
|
export type SqlCompleteness = 'complete' | 'incomplete' | 'unverified';
|
package/lib/flow-segments.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Y=Object.defineProperty;var b=(e,t)=>Y(e,"name",{value:t,configurable:!0});var Z=Object.defineProperty,m=b((e,t)=>Z(e,"name",{value:t,configurable:!0}),"h");export const DEFAULT_SEGMENT_OPTIONS={phaseGapMs:1500,burstGapMs:250,attachWindowMs:400,maxSegmentEvents:400,occurrenceSlackMs:10},FLOW_BOOKKEEPING_KINDS=new Set(["subscription-added","subscription-removed","hook-run","store-created","singleton-instance","visual-frame"]),SQL_ACCOUNT_KIND="db-request-account";const ee=new Set(["react","valtio","client-runtime","chrome","visual"]),S=m(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),v=m(e=>typeof e=="string"&&e!==""?e:void 0,"str"),M=m(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),W=new WeakMap;function F(e){let t=W.get(e);return t||(t=G(e),W.set(e,t)),t}b(F,"U"),m(F,"itemOf");function G(e){const t=S(e.raw)?e.raw:{},s=S(t.request)?t.request:{},o=S(t.span)?t.span:{},i=e.context??{},n=v(t.kind)??"",p=n===SQL_ACCOUNT_KIND,g=(p?M(t.lastEndedAt):void 0)??M(e.timestamp)??0,q=M(s.startedAt)??M(o.startTime)??M(t.startedAt)??(p?M(t.firstStartedAt):void 0),I=M(s.endedAt)??M(o.endTime)??(q!==void 0&&M(t.durationMs)!==void 0?q+t.durationMs:void 0),w=Math.min(g,q??g),$=Math.max(g,I??g),a=S(t.render)?t.render:{},u=S(t.update)?t.update:{},j=n==="render"?v(a.componentName):n==="state-update"?v(u.path)?.split(".").slice(0,2).join("."):void 0,d=v(t.queue),c=v(t.jobId),f=String(e.source),r=v(t.project)??v(i.projectName),l=n==="fetch-start"||n==="fetch-done"||n==="gateway-request";return{event:e,id:e.id,ts:g,from:w,to:$,kind:n,source:f,requestId:v(i.requestId),parentRequestId:v(i.parentRequestId),queueKey:d&&c?`${d}#${c}`:void 0,browser:ee.has(f)||f==="memory"&&r===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(n),project:r,subject:j,route:l?T(v(t.url)):n==="server-request"?v(s.route):void 0,method:l?v(t.method):n==="server-request"?v(s.method):void 0}}b(G,"L"),m(G,"readItem");function T(e){if(!e)return;const t=e.search(/[?#]/),s=t===-1?e:e.slice(0,t),o=/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$/i.exec(s);return o?o[1]??"/":s}b(T,"B"),m(T,"pathOnly");const te=m(e=>e.split(".")[0],"rootOf"),_=m((e,t)=>e.reduce((s,o)=>Math.min(s,t(o)),1/0),"minOf"),B=m((e,t)=>e.reduce((s,o)=>Math.max(s,t(o)),-1/0),"maxOf"),O=m((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),K=m(e=>e.requestId&&!e.requestId.startsWith("job:")?te(e.requestId):void 0,"directFamilyOf");function U(e){if(e.requestId?.startsWith("job:"))return e.requestId.slice(4);if(e.queueKey&&e.kind!=="queue-enqueued"&&!e.requestId)return e.queueKey}b(U,"D"),m(U,"jobKeyOf");function D(e,t){const s=e.filter(n=>!n.parentRequestId&&(n.kind==="server-request"||n.kind==="gateway-request"||n.kind==="fetch-start"||n.kind==="fetch-done")).sort((n,p)=>n.from-p.from||O(n,p));if(s.length<2)return[e];const o=[];for(const n of s){const p=o[o.length-1];p&&n.from<=p.to+t?p.to=Math.max(p.to,n.to):o.push({from:n.from,to:n.to})}if(o.length<2)return[e];const i=o.map(()=>[]);for(const n of e)i[t>=0?z(o,n.ts,t):R(o,n.ts,t)].push(n);return i.filter(n=>n.length>0)}b(D,"z"),m(D,"occurrencesOf");function R(e,t,s){const o=e.findIndex(n=>t>=n.from-s&&t<=n.to+s);if(o!==-1)return o;let i=0;for(let n=0;n<e.length;n+=1)e[n].from<=t&&(i=n);return i}b(R,"P"),m(R,"spanScan");function z(e,t,s){let o=0,i=e.length;for(;o<i;){const n=o+i>>1;e[n].to+s<t?o=n+1:i=n}if(o<e.length&&t>=e[o].from-s)return o;for(o=0,i=e.length;o<i;){const n=o+i>>1;e[n].from<=t?o=n+1:i=n}return Math.max(0,o-1)}b(z,"Q"),m(z,"spanAt");const C={debug:0,info:1,warning:2,error:3,fatal:4};function A(e,t){const s=[];let o=[];for(const i of e){const n=o[o.length-1];n&&i.ts-n.ts>=t&&(s.push(o),o=[]),o.push(i)}return o.length&&s.push(o),s}b(A,"R"),m(A,"runs");export function segmentFlow(e,t={}){const s={...DEFAULT_SEGMENT_OPTIONS};for(const[r,l]of Object.entries(t))typeof l=="number"&&Number.isFinite(l)&&(s[r]=l);const o=new Set,i=[];for(const r of e)o.has(r.id)||(o.add(r.id),i.push(F(r)));i.sort(O);const n=v(i[0]?.event.context?.flowId)??v(i[0]?.event.raw?.flowId)??"",p=new Map;for(const r of i)r.kind==="queue-enqueued"&&r.queueKey&&r.requestId&&!r.requestId.startsWith("job:")&&!p.has(r.queueKey)&&p.set(r.queueKey,r);const g=new Map,q=new Map,I=[];for(const r of i){const l=U(r),h=K(r);if(l!==void 0){const k=q.get(l);k?k.push(r):q.set(l,[r])}else if(h!==void 0){const k=g.get(h);k?k.push(r):g.set(h,[r])}else I.push(r)}const w=[],$=new Map;for(const[r,l]of g)D(l,s.occurrenceSlackMs).forEach((h,k)=>{const x={id:`${n}~r:${r}${k===0?"":`@${k+1}`}`,kind:"request",items:h,requestId:r};if(w.push(x),p.size)for(const y of h)y.kind==="queue-enqueued"&&$.set(y,x)});for(const[r,l]of q){const h=p.get(r),k=h?$.get(h):void 0;k?k.items.push(...l):w.push({id:`${n}~r:job:${r}`,kind:"request",items:l,requestId:`job:${r}`})}const a=i.filter(r=>r.kind==="fetch-done"&&K(r)!==void 0),u=new Map;for(const r of w)r.requestId&&u.set(r.requestId,[...u.get(r.requestId)??[],r]);const j=m((r,l)=>{const h=u.get(r);if(h)return h.find(k=>k.items.some(x=>x.kind==="fetch-done"&&x.ts===l))??h[h.length-1]},"owningUnit"),d=I.filter(r=>r.browser);for(const r of A(d,s.burstGapMs)){const l=r[0].ts,h=a.filter(y=>y.ts<=l&&l-y.ts<=s.attachWindowMs),k=[...new Set(h.map(y=>K(y)))];if(k.length===1){const y=j(k[0],h[h.length-1].ts);if(y){y.items.push(...r);continue}}const x=r.some(y=>y.kind==="flow-origin");w.push({id:`${n}~${x?"o":"u"}:${r[0].id}`,kind:x?"origin":"ui",items:r,...k.length>1?{after:k.sort()}:{}})}for(const r of A(I.filter(l=>!l.browser),s.phaseGapMs))w.push({id:`${n}~a:${r[0].id}`,kind:"ambient",items:r});const c=L(n,i.length,w,s),f=N(i);return f?{...c,sql:f}:c}b(segmentFlow,"segmentFlow"),m(segmentFlow,"segmentFlow");function L(e,t,s,o){for(const a of s)a.items.sort(O);const i=s.map(a=>({unit:a,from:_(a.items,u=>u.from),to:B(a.items,u=>u.to)}));i.sort((a,u)=>a.from-u.from||(a.unit.id<u.unit.id?-1:1));const n=new Map;let p=0,g=-1/0;for(const a of i)(p===0||a.from-g>=o.phaseGapMs)&&(p+=1),g=Math.max(g,a.to),n.set(a.unit,p);const q=[];for(const a of i){const u=P(a.unit.items,o.maxSegmentEvents),j=a.unit.kind==="request"?N(a.unit.items):void 0;u.forEach((d,c)=>{const f=Q(e,a.unit,d,n.get(a.unit),u.length>1?{index:c+1,total:u.length}:void 0);q.push(j&&c===0?{...f,sql:j}:f)})}const I={};for(const a of q)for(const u of a.eventIds)I[u]=a.id;const w=[];for(const a of q){let u=w[a.phase-1];u||(u={index:a.phase,start:a.start,end:a.end,segmentIds:[]},w[a.phase-1]=u),u.start=Math.min(u.start,a.start),u.end=Math.max(u.end,a.end),u.segmentIds.push(a.id)}const $=q.reduce((a,u)=>a+u.counts.signal,0);return{flowId:e,segments:q,phases:w.filter(Boolean),assignment:I,stats:{events:t,signal:$,bookkeeping:t-$,segments:q.length,phases:w.filter(Boolean).length,largestSegment:q.reduce((a,u)=>Math.max(a,u.counts.total),0)}}}b(L,"V"),m(L,"assemble");function P(e,t){if(e.filter(n=>!n.bookkeeping).length<=t)return[e];const s=[];let o=[],i=0;for(const n of e)!n.bookkeeping&&i===t&&(s.push(o),o=[],i=0),o.push(n),n.bookkeeping||(i+=1);return o.length&&s.push(o),s}b(P,"X"),m(P,"chunk");function Q(e,t,s,o,i){const n={total:s.length,signal:0,bookkeeping:0,errors:0,warnings:0},p=new Set;let g="debug";for(const u of s){u.bookkeeping?n.bookkeeping+=1:n.signal+=1;const j=String(u.event.severity);j==="error"||j==="fatal"?n.errors+=1:j==="warning"&&(n.warnings+=1),(C[j]??1)>(C[g]??0)&&(g=j),u.project&&p.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?J(s):[],I=_(s,u=>u.from),w=B(s,u=>u.to),$=H(t.items),a=t.id;return{id:i&&i.index>1?`${a}#${i.index}`:a,flowId:e,kind:t.kind,label:V(t,s,$,i,q),phase:o,start:I,end:w,durationMs:w-I,eventIds:s.map(u=>u.id),counts:n,projects:[...p].sort(),...$.route?{route:$.route}:{},...$.method?{method:$.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...i?{part:i}:{},worstSeverity:g}}b(Q,"Y"),m(Q,"toSegment");function H(e){const t=e.find(s=>s.kind==="fetch-start"&&s.route)??e.find(s=>s.kind==="server-request"&&!s.parentRequestId&&s.route)??e.find(s=>s.kind==="gateway-request"&&s.route)??e.find(s=>s.kind==="fetch-done"&&s.route);return{...t?.route?{route:t.route}:{},...t?.method?{method:t.method.toUpperCase()}:{}}}b(H,"H"),m(H,"routeOf");function J(e){const t=new Map;for(const s of e)s.subject&&!s.bookkeeping&&t.set(s.subject,(t.get(s.subject)??0)+1);return[...t.entries()].sort((s,o)=>o[1]-s[1]||(s[0]<o[0]?-1:1)).slice(0,3).map(([s,o])=>o>1?`${s} \xD7${o}`:s)}b(J,"J"),m(J,"hotOf");function V(e,t,s,o,i){const n=o?` (part ${o.index}/${o.total})`:"";if(e.kind==="request"){if(s.route)return`${s.method?`${s.method} `:""}${s.route}${n}`;const p=t.find(g=>g.queueKey);return p?`job ${p.queueKey}${n}`:`request ${e.requestId??""}${n}`}return e.kind==="origin"?`${t.find(p=>p.kind==="flow-origin")?.event.title||"start"}${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:e.kind==="ui"?`UI update${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:`background${n}`}b(V,"Z"),m(V,"labelOf");const X=50;export function sqlAccountingOf(e){return E(e,!1)}b(sqlAccountingOf,"sqlAccountingOf"),m(sqlAccountingOf,"sqlAccountingOf");function N(e){return E(e.map(t=>t.event),!0)}b(N,"T"),m(N,"accountSqlOfItems");function E(e,t){const s=new Map,o=new Map,i=t?void 0:new Set;for(const d of e){if(i){if(i.has(d.id))continue;i.add(d.id)}const c=S(d.raw)?d.raw:{},f=v(c.kind),r=v(d.context?.requestId);if(!r)continue;const l=v(c.project)??v(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(r)??{count:0,workMs:0,...l?{project:l}:{}};h.count+=1,h.workMs+=M(c.durationMs)??0,o.set(r,h)}else if(f===SQL_ACCOUNT_KIND){const h=v(c.accountId)??d.id,k=M(c.seq)??0,x=s.get(h);if(x&&x.seq>=k)continue;s.set(h,{requestId:r,...l?{project:l}:{},seq:k,basis:c.basis==="end"?"end":"settled",statements:M(c.statements)??0,failed:M(c.failed)??0,workMs:M(c.workMs)??0,recorded:M(c.recorded)??0,suppressed:M(c.suppressed)??0,unwritten:M(c.unwritten)??0})}}const n=new Map;for(const d of s.values()){const c=n.get(d.requestId);if(!c){n.set(d.requestId,{...d});continue}d.basis==="settled"&&(c.basis="settled"),c.statements+=d.statements,c.failed+=d.failed,c.workMs+=d.workMs,c.recorded+=d.recorded,c.suppressed+=d.suppressed,c.unwritten+=d.unwritten}const p=[...new Set([...o.keys(),...n.keys()])].sort();if(p.length===0)return;const g={statements:0,failed:0,workMs:0,recorded:0,suppressed:0,unwritten:0},q={statements:0,workMs:0},I=[];for(const d of p){const c=o.get(d),f=n.get(d),r=c?.count??0;q.statements+=r,q.workMs+=c?.workMs??0;const l=!f||r>f.statements?"unverified":r===f.statements?"complete":"incomplete";f&&l!=="unverified"&&(g.statements+=f.statements,g.failed+=f.failed,g.workMs+=f.workMs,g.recorded+=f.recorded,g.suppressed+=f.suppressed,g.unwritten+=f.unwritten);const h=c?.project??f?.project;I.push({requestId:d,...h?{project:h}:{},status:l,observed:r,observedWorkMs:c?.workMs??0,...f?{basis:f.basis,statements:f.statements,failed:f.failed,workMs:f.workMs,recorded:f.recorded,suppressed:f.suppressed,unwritten:f.unwritten}:{}})}const w=m(d=>I.filter(c=>c.status===d).length,"tally"),$=w("unverified"),a=w("incomplete"),u=m(d=>(d.statements??0)-d.observed,"missing"),j=I.filter(d=>d.status!=="complete").sort((d,c)=>(d.status==="incomplete"?0:1)-(c.status==="incomplete"?0:1)||u(c)-u(d)||(d.requestId<c.requestId?-1:d.requestId>c.requestId?1:0));return{status:$>0?"unverified":a>0?"incomplete":"complete",requests:I.length,complete:w("complete"),incomplete:a,unverified:$,settled:I.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:q,accounted:g,gaps:j.slice(0,X),gapsTruncated:j.length>X}}b(E,"W"),m(E,"accountSql");
|
|
1
|
+
"use strict";var te=Object.defineProperty;var w=(e,t)=>te(e,"name",{value:t,configurable:!0});var se=Object.defineProperty,p=w((e,t)=>se(e,"name",{value:t,configurable:!0}),"p");export const DEFAULT_SEGMENT_OPTIONS={phaseGapMs:1500,burstGapMs:250,attachWindowMs:400,maxSegmentEvents:400,occurrenceSlackMs:10},FLOW_BOOKKEEPING_KINDS=new Set(["subscription-added","subscription-removed","hook-run","store-created","singleton-instance","visual-frame"]),SQL_ACCOUNT_KIND="db-request-account";const ne=new Set(["react","valtio","client-runtime","chrome","visual"]),x=p(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),b=p(e=>typeof e=="string"&&e!==""?e:void 0,"str"),M=p(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),T=new WeakMap;function A(e){let t=T.get(e);return t||(t=_(e),T.set(e,t)),t}w(A,"K"),p(A,"itemOf");function _(e){const t=x(e.raw)?e.raw:{},s=x(t.request)?t.request:{},o=x(t.span)?t.span:{},r=e.context??{},n=b(t.kind)??"",l=n===SQL_ACCOUNT_KIND,g=(l?M(t.lastEndedAt):void 0)??M(e.timestamp)??0,v=M(s.startedAt)??M(o.startTime)??M(t.startedAt)??(l?M(t.firstStartedAt):void 0),q=M(s.endedAt)??M(o.endTime)??(v!==void 0&&M(t.durationMs)!==void 0?v+t.durationMs:void 0),I=Math.min(g,v??g),$=Math.max(g,q??g),j=x(t.render)?t.render:{},a=x(t.update)?t.update:{},c=n==="render"?b(j.componentName):n==="state-update"?b(a.path)?.split(".").slice(0,2).join("."):void 0,d=b(t.queue),u=b(t.jobId),f=String(e.source),i=b(t.project)??b(r.projectName),m=n==="fetch-start"||n==="fetch-done"||n==="gateway-request";return{event:e,id:e.id,ts:g,from:I,to:$,kind:n,source:f,requestId:b(r.requestId),parentRequestId:b(r.parentRequestId),queueKey:d&&u?`${d}#${u}`:void 0,browser:ne.has(f)||f==="memory"&&i===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(n),project:i,subject:c,route:m?B(b(t.url)):n==="server-request"?b(s.route):void 0,method:m?b(t.method):n==="server-request"?b(s.method):void 0}}w(_,"C"),p(_,"readItem");function B(e){if(!e)return;const t=e.search(/[?#]/),s=t===-1?e:e.slice(0,t),o=/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$/i.exec(s);return o?o[1]??"/":s}w(B,"P"),p(B,"pathOnly");const oe=p(e=>e.split(".")[0],"rootOf"),U=p((e,t)=>e.reduce((s,o)=>Math.min(s,t(o)),1/0),"minOf"),D=p((e,t)=>e.reduce((s,o)=>Math.max(s,t(o)),-1/0),"maxOf"),K=p((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),O=p(e=>e.requestId&&!e.requestId.startsWith("job:")?oe(e.requestId):void 0,"directFamilyOf");function z(e){if(e.requestId?.startsWith("job:"))return e.requestId.slice(4);if(e.queueKey&&e.kind!=="queue-enqueued"&&!e.requestId)return e.queueKey}w(z,"Q"),p(z,"jobKeyOf");function C(e,t){const s=e.filter(n=>!n.parentRequestId&&(n.kind==="server-request"||n.kind==="gateway-request"||n.kind==="fetch-start"||n.kind==="fetch-done")).sort((n,l)=>n.from-l.from||K(n,l));if(s.length<2)return[e];const o=[];for(const n of s){const l=o[o.length-1];l&&n.from<=l.to+t?l.to=Math.max(l.to,n.to):o.push({from:n.from,to:n.to})}if(o.length<2)return[e];const r=o.map(()=>[]);for(const n of e)r[t>=0?P(o,n.ts,t):L(o,n.ts,t)].push(n);return r.filter(n=>n.length>0)}w(C,"V"),p(C,"occurrencesOf");function L(e,t,s){const o=e.findIndex(n=>t>=n.from-s&&t<=n.to+s);if(o!==-1)return o;let r=0;for(let n=0;n<e.length;n+=1)e[n].from<=t&&(r=n);return r}w(L,"X"),p(L,"spanScan");function P(e,t,s){let o=0,r=e.length;for(;o<r;){const n=o+r>>1;e[n].to+s<t?o=n+1:r=n}if(o<e.length&&t>=e[o].from-s)return o;for(o=0,r=e.length;o<r;){const n=o+r>>1;e[n].from<=t?o=n+1:r=n}return Math.max(0,o-1)}w(P,"Y"),p(P,"spanAt");const re=new Set(["server-request","gateway-request","fetch-done","fetch-error","queue-process"]),N="event-loop-stall";function E(e){let t=-1/0,s=!1;for(const r of e)re.has(r.kind)?t=Math.max(t,r.to):r.kind===N&&(s=!0);if(!s||!Number.isFinite(t))return;let o;for(const r of e)r.kind===N&&r.from>=t&&(o??=new Map).set(r,Math.round(r.from-t));return o}w(E,"_"),p(E,"lateStallsOf");export function stallsAfterResponse(e){const t=new Map;if(!e.some(o=>x(o.raw)&&o.raw.kind===N))return t;const s=new Map;for(const o of e){const r=A(o),n=r.requestId?.startsWith("job:")?r.requestId:O(r);if(n===void 0)continue;const l=s.get(n);l?l.push(r):s.set(n,[r])}for(const o of s.values())for(const[r,n]of E(o)??[])t.set(r.id,n);return t}w(stallsAfterResponse,"stallsAfterResponse"),p(stallsAfterResponse,"stallsAfterResponse");function W(e,t){if(!t)return e;const s=e.filter(o=>!t.has(o));return s.length?s:e}w(W,"T"),p(W,"timedItems");const Q={debug:0,info:1,warning:2,error:3,fatal:4};function F(e,t){const s=[];let o=[];for(const r of e){const n=o[o.length-1];n&&r.ts-n.ts>=t&&(s.push(o),o=[]),o.push(r)}return o.length&&s.push(o),s}w(F,"F"),p(F,"runs");export function segmentFlow(e,t={}){const s={...DEFAULT_SEGMENT_OPTIONS};for(const[i,m]of Object.entries(t))typeof m=="number"&&Number.isFinite(m)&&(s[i]=m);const o=new Set,r=[];for(const i of e)o.has(i.id)||(o.add(i.id),r.push(A(i)));r.sort(K);const n=b(r[0]?.event.context?.flowId)??b(r[0]?.event.raw?.flowId)??"",l=new Map;for(const i of r)i.kind==="queue-enqueued"&&i.queueKey&&i.requestId&&!i.requestId.startsWith("job:")&&!l.has(i.queueKey)&&l.set(i.queueKey,i);const g=new Map,v=new Map,q=[];for(const i of r){const m=z(i),h=O(i);if(m!==void 0){const k=v.get(m);k?k.push(i):v.set(m,[i])}else if(h!==void 0){const k=g.get(h);k?k.push(i):g.set(h,[i])}else q.push(i)}const I=[],$=new Map;for(const[i,m]of g)C(m,s.occurrenceSlackMs).forEach((h,k)=>{const S={id:`${n}~r:${i}${k===0?"":`@${k+1}`}`,kind:"request",items:h,requestId:i};if(I.push(S),l.size)for(const y of h)y.kind==="queue-enqueued"&&$.set(y,S)});for(const[i,m]of v){const h=l.get(i),k=h?$.get(h):void 0;k?k.items.push(...m):I.push({id:`${n}~r:job:${i}`,kind:"request",items:m,requestId:`job:${i}`})}const j=r.filter(i=>i.kind==="fetch-done"&&O(i)!==void 0),a=new Map;for(const i of I)i.requestId&&a.set(i.requestId,[...a.get(i.requestId)??[],i]);const c=p((i,m)=>{const h=a.get(i);if(h)return h.find(k=>k.items.some(S=>S.kind==="fetch-done"&&S.ts===m))??h[h.length-1]},"owningUnit"),d=q.filter(i=>i.browser);for(const i of F(d,s.burstGapMs)){const m=i[0].ts,h=j.filter(y=>y.ts<=m&&m-y.ts<=s.attachWindowMs),k=[...new Set(h.map(y=>O(y)))];if(k.length===1){const y=c(k[0],h[h.length-1].ts);if(y){y.items.push(...i);continue}}const S=i.some(y=>y.kind==="flow-origin");I.push({id:`${n}~${S?"o":"u"}:${i[0].id}`,kind:S?"origin":"ui",items:i,...k.length>1?{after:k.sort()}:{}})}for(const i of F(q.filter(m=>!m.browser),s.phaseGapMs))I.push({id:`${n}~a:${i[0].id}`,kind:"ambient",items:i});const u=H(n,r.length,I,s),f=G(r);return f?{...u,sql:f}:u}w(segmentFlow,"segmentFlow"),p(segmentFlow,"segmentFlow");function H(e,t,s,o){for(const a of s)a.items.sort(K);const r=new Map;for(const a of s){const c=a.kind==="request"?E(a.items):void 0;c&&r.set(a,c)}const n=s.map(a=>{const c=W(a.items,r.get(a));return{unit:a,from:U(c,d=>d.from),to:D(c,d=>d.to)}});n.sort((a,c)=>a.from-c.from||(a.unit.id<c.unit.id?-1:1));const l=new Map;let g=0,v=-1/0;for(const a of n)(g===0||a.from-v>=o.phaseGapMs)&&(g+=1),v=Math.max(v,a.to),l.set(a.unit,g);const q=[];for(const a of n){const c=J(a.unit.items,o.maxSegmentEvents),d=a.unit.kind==="request"?G(a.unit.items):void 0;c.forEach((u,f)=>{const i=V(e,a.unit,u,l.get(a.unit),c.length>1?{index:f+1,total:c.length}:void 0,r.get(a.unit));q.push(d&&f===0?{...i,sql:d}:i)})}const I={};for(const a of q)for(const c of a.eventIds)I[c]=a.id;const $=[];for(const a of q){let c=$[a.phase-1];c||(c={index:a.phase,start:a.start,end:a.end,segmentIds:[]},$[a.phase-1]=c),c.start=Math.min(c.start,a.start),c.end=Math.max(c.end,a.end),c.segmentIds.push(a.id)}const j=q.reduce((a,c)=>a+c.counts.signal,0);return{flowId:e,segments:q,phases:$.filter(Boolean),assignment:I,stats:{events:t,signal:j,bookkeeping:t-j,segments:q.length,phases:$.filter(Boolean).length,largestSegment:q.reduce((a,c)=>Math.max(a,c.counts.total),0)}}}w(H,"J"),p(H,"assemble");function J(e,t){if(e.filter(n=>!n.bookkeeping).length<=t)return[e];const s=[];let o=[],r=0;for(const n of e)!n.bookkeeping&&r===t&&(s.push(o),o=[],r=0),o.push(n),n.bookkeeping||(r+=1);return o.length&&s.push(o),s}w(J,"Z"),p(J,"chunk");function V(e,t,s,o,r,n){const l={total:s.length,signal:0,bookkeeping:0,errors:0,warnings:0},g=new Set;let v="debug";for(const u of s){u.bookkeeping?l.bookkeeping+=1:l.signal+=1;const f=String(u.event.severity);f==="error"||f==="fatal"?l.errors+=1:f==="warning"&&(l.warnings+=1),(Q[f]??1)>(Q[v]??0)&&(v=f),u.project&&g.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?Y(s):[],I=W(s,n),$=U(I,u=>u.from),j=D(I,u=>u.to),a=n?s.filter(u=>n.has(u)).length:0,c=X(t.items),d=t.id;return{id:r&&r.index>1?`${d}#${r.index}`:d,flowId:e,kind:t.kind,label:Z(t,s,c,r,q),phase:o,start:$,end:j,durationMs:j-$,eventIds:s.map(u=>u.id),counts:l,projects:[...g].sort(),...c.route?{route:c.route}:{},...c.method?{method:c.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...r?{part:r}:{},...a?{stallsAfterResponse:a}:{},worstSeverity:v}}w(V,"ee"),p(V,"toSegment");function X(e){const t=e.find(s=>s.kind==="fetch-start"&&s.route)??e.find(s=>s.kind==="server-request"&&!s.parentRequestId&&s.route)??e.find(s=>s.kind==="gateway-request"&&s.route)??e.find(s=>s.kind==="fetch-done"&&s.route);return{...t?.route?{route:t.route}:{},...t?.method?{method:t.method.toUpperCase()}:{}}}w(X,"te"),p(X,"routeOf");function Y(e){const t=new Map;for(const s of e)s.subject&&!s.bookkeeping&&t.set(s.subject,(t.get(s.subject)??0)+1);return[...t.entries()].sort((s,o)=>o[1]-s[1]||(s[0]<o[0]?-1:1)).slice(0,3).map(([s,o])=>o>1?`${s} \xD7${o}`:s)}w(Y,"ne"),p(Y,"hotOf");function Z(e,t,s,o,r){const n=o?` (part ${o.index}/${o.total})`:"";if(e.kind==="request"){if(s.route)return`${s.method?`${s.method} `:""}${s.route}${n}`;const l=t.find(g=>g.queueKey);return l?`job ${l.queueKey}${n}`:`request ${e.requestId??""}${n}`}return e.kind==="origin"?`${t.find(l=>l.kind==="flow-origin")?.event.title||"start"}${r.length?` \xB7 ${r.join(", ")}`:""}${n}`:e.kind==="ui"?`UI update${r.length?` \xB7 ${r.join(", ")}`:""}${n}`:`background${n}`}w(Z,"se"),p(Z,"labelOf");const ee=50;export function sqlAccountingOf(e){return R(e,!1)}w(sqlAccountingOf,"sqlAccountingOf"),p(sqlAccountingOf,"sqlAccountingOf");function G(e){return R(e.map(t=>t.event),!0)}w(G,"L"),p(G,"accountSqlOfItems");function R(e,t){const s=new Map,o=new Map,r=t?void 0:new Set;for(const d of e){if(r){if(r.has(d.id))continue;r.add(d.id)}const u=x(d.raw)?d.raw:{},f=b(u.kind),i=b(d.context?.requestId);if(!i)continue;const m=b(u.project)??b(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(i)??{count:0,workMs:0,...m?{project:m}:{}};h.count+=1,h.workMs+=M(u.durationMs)??0,o.set(i,h)}else if(f===SQL_ACCOUNT_KIND){const h=b(u.accountId)??d.id,k=M(u.seq)??0,S=s.get(h);if(S&&S.seq>=k)continue;s.set(h,{requestId:i,...m?{project:m}:{},seq:k,basis:u.basis==="end"?"end":"settled",statements:M(u.statements)??0,failed:M(u.failed)??0,workMs:M(u.workMs)??0,recorded:M(u.recorded)??0,suppressed:M(u.suppressed)??0,unwritten:M(u.unwritten)??0})}}const n=new Map;for(const d of s.values()){const u=n.get(d.requestId);if(!u){n.set(d.requestId,{...d});continue}d.basis==="settled"&&(u.basis="settled"),u.statements+=d.statements,u.failed+=d.failed,u.workMs+=d.workMs,u.recorded+=d.recorded,u.suppressed+=d.suppressed,u.unwritten+=d.unwritten}const l=[...new Set([...o.keys(),...n.keys()])].sort();if(l.length===0)return;const g={statements:0,failed:0,workMs:0,recorded:0,suppressed:0,unwritten:0},v={statements:0,workMs:0},q=[];for(const d of l){const u=o.get(d),f=n.get(d),i=u?.count??0;v.statements+=i,v.workMs+=u?.workMs??0;const m=!f||i>f.statements?"unverified":i===f.statements?"complete":"incomplete";f&&m!=="unverified"&&(g.statements+=f.statements,g.failed+=f.failed,g.workMs+=f.workMs,g.recorded+=f.recorded,g.suppressed+=f.suppressed,g.unwritten+=f.unwritten);const h=u?.project??f?.project;q.push({requestId:d,...h?{project:h}:{},status:m,observed:i,observedWorkMs:u?.workMs??0,...f?{basis:f.basis,statements:f.statements,failed:f.failed,workMs:f.workMs,recorded:f.recorded,suppressed:f.suppressed,unwritten:f.unwritten}:{}})}const I=p(d=>q.filter(u=>u.status===d).length,"tally"),$=I("unverified"),j=I("incomplete"),a=p(d=>(d.statements??0)-d.observed,"missing"),c=q.filter(d=>d.status!=="complete").sort((d,u)=>(d.status==="incomplete"?0:1)-(u.status==="incomplete"?0:1)||a(u)-a(d)||(d.requestId<u.requestId?-1:d.requestId>u.requestId?1:0));return{status:$>0?"unverified":j>0?"incomplete":"complete",requests:q.length,complete:I("complete"),incomplete:j,unverified:$,settled:q.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:v,accounted:g,gaps:c.slice(0,ee),gapsTruncated:c.length>ee}}w(R,"D"),p(R,"accountSql");
|
package/lib/flow-shape.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var jt=Object.defineProperty;var R=(i,f)=>jt(i,"name",{value:f,configurable:!0});var St=Object.defineProperty,k=R((i,f)=>St(i,"name",{value:f,configurable:!0}),"I");import{redactDeep as Bt,redactText as nt,redactUrlParams as At}from"./redact.js";import{templatisePath as ht}from"./route-template.js";import{SQL_ACCOUNT_KIND as Rt,sqlAccountingOf as Tt}from"./flow-segments.js";import{isServiceHopHost as $t}from"./service-hop.js";import{boundedClone as Ct}from"@lensmcp/protocol-types";export function areaOf(i){const{source:f,category:s,title:M,kind:l}=i;return f==="ai"?"ai":f==="perf"&&l==="event-loop-stall"?"services":l?.startsWith("memory")||l==="db-query"?"data":f==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":f==="db"||f==="redis"||f==="queue"||l==="redis-op"||l?.startsWith("queue-")||f==="fs"||l==="fs-ops"?"data":f==="exec"||l==="exec"||l==="egress"&&$t(i.host)?"services":f==="external"||l==="egress"?"network":f==="nestjs"||f==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(M)?"data":"services":f==="valtio"?"state":s==="network"?"network":"browser"}R(areaOf,"areaOf"),k(areaOf,"areaOf");const yt=240,Dt=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Pt=new Set(["tenantId","caller","userId","accountId","email","subject"]),Nt=8;function vt(i){const f=rt(i,0);return Ct(Bt({redacted:!0,...f}),{rawByteLimit:16*1024}).value}R(vt,"Ct"),k(vt,"aiProjection");function rt(i,f){if(typeof i=="string")return kt(i);if(i===null||typeof i!="object")return i;if(f>=Nt)return;if(Array.isArray(i))return i.slice(0,32).map(M=>rt(M,f+1));const s={};for(const[M,l]of Object.entries(i))if(!Pt.has(M)){if(Dt.has(M)){typeof l=="string"?s[`${M}Chars`]=l.length:Array.isArray(l)?s[`${M}Count`]=l.length:l!=null&&(s[`${M}Present`]=!0);continue}s[M]=rt(l,f+1)}return s}R(rt,"it"),k(rt,"projectAi");function kt(i){return i.length<=yt?nt(i):`${nt(i.slice(0,yt))}\u2026`}R(kt,"Et"),k(kt,"clipText");export function httpFacts(i,f){const s=k(I=>typeof I=="string"&&I.length>0?I:void 0,"str"),M=typeof f.status=="number"?f.status:void 0,l=k(I=>At(I.split("?")[0]??I)||"/","pathOf"),P=k((I,y,j={})=>({...I?{method:I.toUpperCase()}:{},...y?{rawPath:y,route:ht(y)}:{},...M!==void 0?{status:M}:{},...j}),"facts");if(i==="gateway-request"){const I=s(f.url);return P(s(f.method),I?l(I):void 0,{...s(f.host)?{host:s(f.host)}:{},...s(f.caller)?{caller:s(f.caller)}:{}})}if(i==="egress"){const I=s(f.path),y=s(f.exchangeId);return P(s(f.method)??"GET",I?l(I):void 0,{...s(f.host)?{host:s(f.host)}:{},...y?{exchangeId:y}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const I=s(f.href)??s(f.url);let y,j;if(I)try{const p=new URL(I,"http://relative.invalid");y=l(p.pathname),p.hostname!=="relative.invalid"&&(j=p.hostname)}catch{}return P(s(f.method)??"GET",y,j?{host:j}:{})}if(i==="ai-call")return{...M!==void 0?{status:M}:{},...f.stream===!0?{streamed:!0}:{}};const g=f.request;if(g&&typeof g=="object"){const I=g,y=s(I.route),j=s(I.method);if(!y&&!j)return{};const p=typeof I.status=="number"?I.status:void 0,T=y?l(y):void 0;return{...j?{method:j.toUpperCase()}:{},...T?{rawPath:T,route:T.includes(":")?T:ht(T)}:{},...p!==void 0?{status:p}:{}}}return{}}R(httpFacts,"httpFacts"),k(httpFacts,"httpFacts");export function trimFlowEvent(i,f={}){const s=i.raw??{},M=s.render??{},l=s.span??{},P=s.request??{},g=k(d=>typeof d=="number"?d:void 0,"num"),I=s.loop??{},y=s.effect??{},j=g(s.durationMs)??g(l.durationMs)??g(P.durationMs)??g(I.durationMs)??g(M.actualDurationMs)??g(y.durationMs),p=typeof s.kind=="string"?s.kind:void 0,T=p==="fetch-done"||p==="fetch-error",G=g(M.commitTime),H=p==="render"&&G!==void 0&&Math.abs(G-i.timestamp)<6e4,V=T?i.timestamp:H?G:g(s.startedAt)??g(l.startTime)??g(P.startedAt)??g(I.startedAt)??(j!==void 0?i.timestamp-j:i.timestamp);let b;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",m=typeof s.result=="string"?` \u2192 ${s.result}`:"";b=s.query+d+m}else if(typeof s.command=="string"){const d=typeof s.value=="string"?` \u2192 ${s.value}`:s.hit===!1?" \u2192 (miss)":"";b=s.command+d}else if(p==="state-update"){const d=s.update??{};let m="";try{m=JSON.stringify(d.preview)}catch{}b=`${d.storeId??""}.${d.path??""} = ${m}`}else if(p==="fs-ops"&&Array.isArray(s.paths))b=s.paths.slice(0,8).map(d=>{const m=d??{},B=typeof m.n=="number"&&m.n>1?` \xD7${m.n}`:"",h=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}${h}`}).join(" \xB7 ");else if(p==="exec"&&typeof s.cmd=="string")b=`${s.cmd} \u2192 ${s.code??s.signal??s.error??"?"}`;else if(p==="queue-completed"&&typeof s.returned=="string")b=`returned ${s.returned}`;else if(p==="queue-enqueued")b=`${s.job??"job"}#${s.jobId??"?"} \u2192 ${s.queue??""}${typeof s.data=="string"?" "+s.data:""}`;else if(p==="log"){const d=P.error??{},m=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;m&&m!==i.title&&(b=m)}let L,W,Y,U;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 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,W=nt([D,K].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){U=[...m!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const h=k(D=>D.length>wt?`${D.slice(0,wt)}\u2026`:D,"short");b=[m!==void 0?`args ${h(m)}`:"",B!==void 0?`returned ${h(B)}`:""].filter(Boolean).join(" \u2192 ")}}let _;if(p==="gateway-request")_=`${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??""));_=`${d.hostname}${d.pathname}`}catch{}let O;if(p==="gateway-request"&&Array.isArray(s.steps))O=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(" ")}),b=O.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")b=`${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 ${g(d.promptTokens)??"?"}\u2192${g(d.completionTokens)??"?"} tok`:"",B=s.status!==void 0?` \xB7 ${String(s.status)}`:s.error?" \xB7 failed":"",h=g(s.toolCallCount)?` \xB7 ${g(s.toolCallCount)} tool call${g(s.toolCallCount)===1?"":"s"}`:"",D=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";b=`${s.provider??""}/${s.model??"?"}${m}${B}${h}${D}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},m=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],h=`${g(m.promptTokens)??"?"}\u2192${g(m.completionTokens)??"?"} tok`,D=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",K=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";b=`${d.provider??""}/${d.model??""} \xB7 ${h}${D}${K}`}else if(p==="ai-turn-start"){const d=Array.isArray(s.tools)?s.tools:[];b=`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=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";b=`${d.name??"tool"} ${m.error!=null?"\u2717 "+String(m.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},m=g(s.rounds)!==void 0?` \xB7 ${g(s.rounds)} round${g(s.rounds)===1?"":"s"}`:"",B=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";b=`${s.ok===!1?"FAILED":"ok"} \xB7 ${g(d.promptTokens)??"?"}+${g(d.completionTokens)??"?"} tok${m}${B}`}}let C;p==="db-query"&&typeof s.query=="string"?C=s.query:p==="redis-op"?C=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?C=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?C=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?C=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?C=l.name:p==="memory-mutation"&&(C=i.title);const E=i.context??{},Z=M.commitId??y.commitId??s.commitId,z=Array.isArray(M.why)?M.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:V,...C?{sig:C}:{},..._?{urlKey:_}:{},...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${Y?` ${Y}`:""}${j!==void 0?` after ${j}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"&&$t(typeof s.host=="string"?s.host:void 0)?{hop:!0}:{},...p==="egress"&&typeof s.calleeRequestId=="string"?{calleeRequestId:s.calleeRequestId}:{},...L?{outcome:L}:{},...W?{error:W}:{},...U?{captured:U}:{},...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 E.requestId=="string"?{requestId:E.requestId}:{},...typeof E.parentRequestId=="string"?{parentRequestId:E.parentRequestId}:{},...typeof Z=="string"?{commitId:Z}:{},...typeof M.componentName=="string"?{component:M.componentName}:{},...typeof M.phase=="string"?{phase:M.phase}:{},...z.length?{why:z}:{},...p==="effect-run"&&typeof y.hookLogicalId=="string"?{hook:y.hookLogicalId}:{},...p==="effect-run"&&y.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:g(s.total),renderPublished:g(s.published),...g(s.walkStoppedAt)!==void 0?{renderWalkStoppedAt:g(s.walkStoppedAt)}:{}}:{},...typeof E.projectName=="string"?{project:E.projectName}:typeof s.project=="string"?{project:s.project}:{},...j!==void 0?{durationMs:j}:{},...T&&g(s.startedAt)!==void 0?{fetchStartedAt:g(s.startedAt)}:{},...i.source==="ai"?{ai:f.includeRaw?s:vt(s)}:{},...b?{detail:b}:{},...O?{steps:O}:{}}}R(trimFlowEvent,"trimFlowEvent"),k(trimFlowEvent,"trimFlowEvent");const wt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Ot=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),at=1;function Mt(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(Mt,"Nt"),k(Mt,"kindRank");function J(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:Mt(i.kind)}R(J,"Z"),k(J,"causalRank");export function buildFlowDetail(i,f={}){const s=Tt(i),M=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===Rt)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,f)),l=new Set;for(let t=M.length-1;t>=0;t--)l.has(M[t].id)?M.splice(t,1):l.add(M[t].id);const P=new Map;for(const t of M)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!P.has(t.requestId)&&P.set(t.requestId,t.start);const g=k(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&P.has(t.requestId)?P.get(t.requestId):t.start,"anchorOf");M.sort((t,r)=>g(t)-g(r)||t.start-r.start||J(t)-J(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const I=k(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),y=M;for(const t of y)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const j=new Map;for(const t of y)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=j.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),j.set(t.requestId,r)}const p=k((t,r)=>{const e=j.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=p(t.requestId,t.start);r&&(t.project=r)}const T=new Map;for(const t of y)t.spanId&&T.set(t.spanId,t);const G=k((t,r)=>{let e=t.parentSpanId?T.get(t.parentSpanId):void 0;for(let o=0;e&&o<64;o++){if(e===r)return!0;e=e.parentSpanId?T.get(e.parentSpanId):void 0}return!1},"inside"),H=new Map(y.map((t,r)=>[t,r])),V=new Map,b=k(t=>{let r=V.get(t.group);r||V.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)I(t)&&Number.isFinite(t.start)&&b(t).spans.push(t);for(const t of V.values())for(const r of t.values())r.spans.sort((e,o)=>e.start-o.start||H.get(e)-H.get(o));const L=k(t=>Number.isFinite(t.start)?t.start:1/0,"startOf");for(const t of y.slice().sort((r,e)=>L(r)-L(e))){const r=t.parentSpanId?T.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=b(t);for(;e.next<e.spans.length&&e.spans[e.next].start<=t.start+at;)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)-H.get($)):e.alive;let n;for(const a of o){if(a===t)continue;const $=a.project,w=t.project;if(a.kind!=="gateway-request"&&t.kind!=="gateway-request"&&$!==void 0&&w!==void 0&&$!==w)continue;const u=a.durationMs??0,c=t.durationMs??0,v=Math.abs(a.start-t.start)<=at,q=J(a),A=J(t),x=a.start<=t.start;if(!(a.start+u>t.start&&(x||v&&q<A)&&(!v||(q!==A?q<A:x&&u>c))))continue;const F=n?J(n):-1,N=n?Math.abs(a.start-n.start)<=at:!1,Q=n&&N&&q===F?G(a,n)?1:G(n,a)?-1:0:0;(!n||!N&&a.start>n.start||N&&q>F||Q>0||Q===0&&N&&q===F&&(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 w=$.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--)$.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 W=new Map;for(const t of y){if(!t.requestId)continue;const r=W.get(t.requestId);r?r.push(t):W.set(t.requestId,[t])}const Y=new Map(y.map(t=>[t.id,t])),U=new Map;for(const t of y)t.calleeRequestId&&!U.has(t.calleeRequestId)&&U.set(t.calleeRequestId,t);const _=k((t,r)=>{const e=(W.get(t)??[]).filter(o=>I(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?U.get(t.requestId):void 0,o=e&&e.start<=t.start?e:_(t.parentRequestId,t.start);o&&o!==t&&o.start<=t.start&&(t.parent=o.id)}const O=y,C=new Map;for(const t of O)t.kind==="gateway-request"&&t.requestId&&!C.has(t.requestId)&&C.set(t.requestId,t);for(const t of O)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=C.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const E=new Set,Z=new Set,z=[];for(const t of O){if(t.kind!=="gateway-request")continue;if(!t.requestId){z.push(t);continue}const r=W.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){z.push(t);continue}e&&(t.fetchStartId=e.id,E.add(e.id)),o&&(t.fetchDoneId=o.id,Z.add(o.id))}const d=new Map;for(const t of O){if(!t.urlKey)continue;const r=d.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?z.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?E.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 w=$?$.t:n.start;let u,c=1/0;for(const v of e){if(o.has(v.id))continue;const q=v.fetchStartedAt??v.start-(v.durationMs??0),A=Math.abs(q-w);A<c&&(c=A,u=v)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const m=new Map,B=new Map;for(const t of O)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&m.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&B.set(`${t.queue}#${t.jobId}`,t));for(const t of O){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=m.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||!Ot.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 "))}}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"),st=k(t=>K(t.map(r=>r.component).filter(r=>!!r)),"named"),qt=k(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),it=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"),It=k(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),ot=k(t=>`${It(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),dt=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"),ut=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 ct(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")),w=K($.flatMap(S=>(S.why??[]).filter(X=>X!=="parent-render"))),u=st($),c=e.filter(S=>S.phase==="mount"),v=e.filter(S=>S.phase!=="mount"&&!$.includes(S)),q=a[0]?.component??"view",A=e.length>0&&c.length===e.length,x=w.length?w.join(" + "):void 0,F=A?"mount":"update",N=u.length?`view update \xB7 ${qt(u)} \u2190 ${x}`:A?`view mount \xB7 ${q}`:`view update \xB7 ${q}`,Q=n?.renderTotal??e.length,xt=[c.length?`mounted ${it(c)}`:"",v.length?`re-rendered ${it(v)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${Q} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??e.length} recorded`:n?`${Q} 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(ot).join(", ")}`:""].filter(Boolean).join(" \xB7 "),gt=st(e);return ut({...r,...dt(t),kind:"view-update",title:N,detail:xt,commitId:r.commitId,viewPhase:F,...x?{cause:x}:{},causeComponents:u,components:gt,mounted:st(c),renderCount:Q,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:o.length,effectHooks:o.map(ot),memberIds:t.map(S=>S.id),sig:`commit:${F}:${x??"-"}:${u.join(",")}:${gt.slice().sort().join(",")}`,severity:t.some(S=>S.severity==="error")?"error":r.severity})}R(ct,"It"),k(ct,"viewUpdateNode");function lt(t){const r=t[0],e=t.map(ot);return ut({...r,...dt(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(lt,"kt"),k(lt,"effectsNode");const bt=k(t=>K(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function pt(t,r){const e=t[0],o=t[t.length-1],n=t.length,a=e.detail,$=Math.min(...t.map(v=>v.start)),w=Math.max(...t.map(v=>v.start+(v.durationMs??0))),u=Math.round(t.reduce((v,q)=>v+(q.durationMs??0),0)/n*10)/10,c=Math.round((w-$)*10)/10;e.count=n,e.avgMs=u,e.wallMs=c,e.durationMs=w-$,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 ${bt(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(pt,"qt"),k(pt,"collapseRepeat");const tt=[],et=new Map,ft=new Set;for(let t=0;t<h.length;t++){if(ft.has(t))continue;const r=h[t];if(!D(r)){tt.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)ft.add(a);const o=e.map(a=>h[a]),n=o.some(a=>a.kind!=="effect-run")?ct(o):lt(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")){h=tt;for(const t of h)for(;t.parent&&et.has(t.parent);)t.parent=et.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 q=0;q<v;q++)if(o[u+q]!==o[c+q])return!1;return!0},"sameBlock"),a=k(u=>o[u].split("|")[0],"kindAt"),$=k(u=>{let c=0,v=1;for(let q=1;q<=4&&u+q<=o.length;q++){let A=1;for(;u+(A+1)*q<=o.length&&n(u,u+A*q,q);)A+=1;A>=3&&q*A>c*v&&(c=q,v=A)}return{k:c,r:v}},"bestBlockAt"),w=new Map;for(let u=0;u<o.length;){const{k:c,r:v}=$(u);if(c===0){u+=1;continue}const q=[...Array(c).keys()].find(x=>t.has(a(u+x)));if(q!==void 0&&q>0){const x=$(u+q);if(x.k===c&&x.r>=3&&x.r>=v-1){u+=q;continue}}const A=o.slice(u,u+c).map(x=>x.split("|")[0]).filter(x=>t.has(x));for(let x=0;x<c;x++){const F=[];for(let N=0;N<v;N++)F.push(h[r[u+x+N*c]]);pt(F,A);for(const N of F.slice(1))w.set(N.id,F[0].id)}u+=c*v}if(w.size>0){h=h.filter(u=>!w.has(u.id));for(const u of h)for(;u.parent&&w.has(u.parent);)u.parent=w.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 mt=k(t=>{const r=new Map;for(const o of h){if(!o.sig||I(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,w=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=w-$,n.durationMs=w-$,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");mt(!0),mt(!1);for(const t of h){if(!I(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=h.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 $=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");
|
|
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");
|
package/lib/resource-store.d.ts
CHANGED
|
@@ -29,6 +29,11 @@ export interface ResourceStoreOptions {
|
|
|
29
29
|
costFactor?: number;
|
|
30
30
|
/** The most cost spacing may hold a resource back (default 30 s). */
|
|
31
31
|
maxGapMs?: number;
|
|
32
|
+
/**
|
|
33
|
+
* Names each recompute in the process's work log while it runs (the session's `serverWork`): a held event loop then
|
|
34
|
+
* says which resource it was rebuilding (issues/closed/overseer-12). Begin a span; call what it returns at the end.
|
|
35
|
+
*/
|
|
36
|
+
work?: (what: string) => () => void;
|
|
32
37
|
}
|
|
33
38
|
/**
|
|
34
39
|
* The resource store. URIs are registered once; reading is cheap; the
|
|
@@ -46,6 +51,7 @@ export declare class ResourceStore {
|
|
|
46
51
|
private readonly lastRun;
|
|
47
52
|
/** What the last recompute of each URI took (produce + serialise), in ms. */
|
|
48
53
|
private readonly lastCost;
|
|
54
|
+
private readonly work;
|
|
49
55
|
constructor(opts?: ResourceStoreOptions);
|
|
50
56
|
register(uri: string, produce: ResourceProducer): Unsubscribe;
|
|
51
57
|
read(uri: string): Promise<ResourceValue>;
|
package/lib/resource-store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var l=Object.defineProperty;var a=(o,e)=>l(o,"name",{value:e,configurable:!0});var d=Object.defineProperty,u=a((o,e)=>d(o,"name",{value:e,configurable:!0}),"a");export class ResourceStore{static{a(this,"ResourceStore")}static{u(this,"ResourceStore")}constructor(e={}){this.entries=new Map,this.subs=new Map,this.queued=new Map,this.lastRun=new Map,this.lastCost=new Map,this.coalesceMs=Math.max(0,e.coalesceMs??0),this.costFactor=Math.max(0,e.costFactor??0),this.maxGapMs=Math.max(0,e.maxGapMs??3e4),this.work=e.work}register(e,s){if(this.entries.has(e))throw new Error(`Resource already registered: ${e}`);return this.entries.set(e,{uri:e,produce:s,revision:0}),()=>{this.entries.delete(e),this.subs.delete(e),this.lastRun.delete(e),this.lastCost.delete(e)}}async read(e){const s=this.entries.get(e);if(!s)throw new Error(`Unknown resource: ${e}`);const t=await s.produce();return s.produced={at:Date.now(),value:t},t}async readRecent(e,s){const t=this.entries.get(e);if(!t)throw new Error(`Unknown resource: ${e}`);return t.produced&&Date.now()-t.produced.at<=s?t.produced.value:this.read(e)}list(){return[...this.entries.keys()]}markDirty(e){if(this.coalesceMs===0&&this.costFactor===0)return this.recompute(e);if(!this.entries.has(e))return Promise.resolve();const s=this.queued.get(e);if(s)return s;const t=Math.max(0,(this.lastRun.get(e)??Number.NEGATIVE_INFINITY)+this.gapFor(e)-Date.now()),n=new Promise(r=>{const i=u(()=>{this.queued.delete(e),this.lastRun.set(e,Date.now()),this.recompute(e).then(r,()=>r())},"go");t===0?setImmediate(i):setTimeout(i,t).unref?.()});return this.queued.set(e,n),n}gapFor(e){const s=this.lastCost.get(e)??0;return Math.max(this.coalesceMs,Math.min(this.maxGapMs,this.costFactor*s))}cost(e){return this.lastCost.get(e)}async recompute(e){const s=this.entries.get(e);if(!s)return;const t=performance.now(),n=this.work?.(`recompute ${e}`);let r,i;try{r=await s.produce(),s.produced={at:Date.now(),value:r},i=JSON.stringify(r)}finally{n?.()}if(this.lastCost.set(e,performance.now()-t),i===s.lastJson)return;s.lastJson=i,s.revision+=1;const c=this.subs.get(e);if(c)for(const h of c)try{h(e,s.revision)}catch{}}revision(e){return this.entries.get(e)?.revision}subscribe(e,s){let t=this.subs.get(e);return t||(t=new Set,this.subs.set(e,t)),t.add(s),()=>{t?.delete(s)}}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/core",
|
|
3
|
-
"version": "1.25.
|
|
3
|
+
"version": "1.25.54",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"module": "./index.js",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
}
|
|
95
95
|
},
|
|
96
96
|
"dependencies": {
|
|
97
|
-
"@lensmcp/protocol-types": "1.25.
|
|
97
|
+
"@lensmcp/protocol-types": "1.25.54",
|
|
98
98
|
"tslib": "^2.3.0"
|
|
99
99
|
},
|
|
100
100
|
"license": "Apache-2.0",
|