@lunora/observability 1.0.0-alpha.30 → 1.0.0-alpha.31

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/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-DGMchLuo.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-CTHH5h5E.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-B3Cl-VMH.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,FUNCTION_METRICS_INDEX_TABLE as R,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as m,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as l,readFunctionMetricBuckets as g,readFunctionMetricIndexHits as O,readFunctionMetricScans as H,readFunctionMetrics as y,readFunctionMetricsTotals as b,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-SKpGN7hQ.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as K,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BGGX6k5D.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{LogBuffer as j}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{M as z}from"./packem_shared/metric-buffer-BGdHQs8k.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-CbWL3Qhh.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-Ev3XWiWk.mjs";import{R as Te,a as oe,e as ae,b as se,c as Ee,p as _e,r as ce,d as Se,f as Ie}from"./packem_shared/request-log-Dp7JeJec.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-CidkqOQ1.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-zjqCAuGp.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-Dxl42LBT.mjs";import{r as de}from"./packem_shared/trace-context-CpFltS-q.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,T as AUTH_METRICS_BUCKET_MS,o as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,K as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d as FUNCTION_METRICS_BUCKET_RETENTION,R as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,m as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,G as ISSUE_SEVERITIES,X as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,j as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,z as MetricBuffer,Te as REQUEST_LOG_TABLE,Ce as SpanBuffer,oe as appendRequestLogEntry,ue as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,ae as emitLogEvent,se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Ee as ensureRequestLogTable,q as explainIssue,fe as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,v as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,b as readFunctionMetricsTotals,W as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,de as resolveTraceAnchor,k as upsertIssueState};
1
+ import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-DGMchLuo.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-z5hLfR2P.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-DWEtTj-a.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,FUNCTION_METRICS_INDEX_TABLE as R,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as m,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as l,readFunctionMetricBuckets as g,readFunctionMetricIndexHits as O,readFunctionMetricScans as H,readFunctionMetrics as y,readFunctionMetricsTotals as b,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-SKpGN7hQ.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as K,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BGGX6k5D.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{LogBuffer as j}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{M as z}from"./packem_shared/metric-buffer-QGsa8K4_.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-dka8wnH-.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-Ev3XWiWk.mjs";import{R as Te,a as oe,e as ae,b as se,c as Ee,p as _e,r as ce,d as Se,f as Ie}from"./packem_shared/request-log-COB2xhns.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-CidkqOQ1.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-zjqCAuGp.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-Dxl42LBT.mjs";import{r as de}from"./packem_shared/trace-context-CpFltS-q.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,T as AUTH_METRICS_BUCKET_MS,o as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,K as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d as FUNCTION_METRICS_BUCKET_RETENTION,R as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,m as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,G as ISSUE_SEVERITIES,X as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,j as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,z as MetricBuffer,Te as REQUEST_LOG_TABLE,Ce as SpanBuffer,oe as appendRequestLogEntry,ue as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,ae as emitLogEvent,se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Ee as ensureRequestLogTable,q as explainIssue,fe as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,v as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,b as readFunctionMetricsTotals,W as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,de as resolveTraceAnchor,k as upsertIssueState};
@@ -0,0 +1 @@
1
+ import{M as f,m as i}from"./metric-buffer-QGsa8K4_.mjs";export{f as MetricBuffer,i as metricSeriesKey};
@@ -1 +1 @@
1
- import{g as t,R as o,a as g,e as E,b as L,c as R,p,r as d,d as n,f as u,h as T}from"./request-log-Dp7JeJec.mjs";import"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,p as parseLogArgs,d as readErrorIssues,n as readRequestLog,u as redactArgs,T as renderLogMessage};
1
+ import{g as t,R as o,a as g,e as E,b as L,c as R,p,r as d,d as n,f as u,h as T}from"./request-log-COB2xhns.mjs";import"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,p as parseLogArgs,d as readErrorIssues,n as readRequestLog,u as redactArgs,T as renderLogMessage};
@@ -1 +1 @@
1
- import{o as m,t as b}from"./trace-context-CpFltS-q.mjs";import{f as M}from"./request-log-Dp7JeJec.mjs";const y=100,T=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),S=(e,t)=>{if(!w.has(e))return;const n=t[0];return typeof n=="string"&&n.length>0?n:void 0},k=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),E=e=>{const{deps:t,durationMs:n,failure:a,operation:s,startTs:r,table:o}=e;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:n,...a===void 0?{}:{error:{message:M(k(a),t.captureRaw),type:b(a)}},functionPath:t.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:a===void 0,parentSpanId:t.anchor.rootSpanId,shardKey:t.shardKey,spanId:m(8),startTs:r,traceId:t.anchor.traceId,userId:t.userId()}},v=(e,t)=>{if(t.mode==="off")return e;const{tally:n}=t,a=new Map;return new Proxy(e,{get(s,r,o){const c=Reflect.get(s,r,o);if(typeof r!="string"||typeof c!="function"||!T.has(r))return c;const f=a.get(r);if(f!==void 0)return f;const g=c,u=async(...p)=>{const l=Date.now(),h=S(r,p);let d;try{return await g.apply(s,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;n.calls+=1,n.durationMs+=i,n.perOperation[r]=(n.perOperation[r]??0)+1,d!==void 0&&(n.errors+=1);try{t.mode==="spans"&&(n.spansEmitted>=y?n.spansTruncated=!0:(n.spansEmitted+=1,t.record(E({deps:t,durationMs:i,failure:d,operation:r,startTs:l,table:h}))))}catch{}}};return a.set(r,u),u}})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),P=e=>{const t={"db.calls":e.calls,"db.duration_ms":e.durationMs};e.errors>0&&(t["db.errors"]=e.errors),e.spansTruncated&&(t["db.spans_truncated"]=!0);for(const[n,a]of Object.entries(e.perOperation))t[`db.op.${n}`]=a;return t};export{D as createDatabaseTally,P as formatTally,v as instrumentDatabase};
1
+ import{o as m,t as b}from"./trace-context-CpFltS-q.mjs";import{f as M}from"./request-log-COB2xhns.mjs";const y=100,T=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),S=(e,t)=>{if(!w.has(e))return;const n=t[0];return typeof n=="string"&&n.length>0?n:void 0},k=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),E=e=>{const{deps:t,durationMs:n,failure:a,operation:s,startTs:r,table:o}=e;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:n,...a===void 0?{}:{error:{message:M(k(a),t.captureRaw),type:b(a)}},functionPath:t.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:a===void 0,parentSpanId:t.anchor.rootSpanId,shardKey:t.shardKey,spanId:m(8),startTs:r,traceId:t.anchor.traceId,userId:t.userId()}},v=(e,t)=>{if(t.mode==="off")return e;const{tally:n}=t,a=new Map;return new Proxy(e,{get(s,r,o){const c=Reflect.get(s,r,o);if(typeof r!="string"||typeof c!="function"||!T.has(r))return c;const f=a.get(r);if(f!==void 0)return f;const g=c,u=async(...p)=>{const l=Date.now(),h=S(r,p);let d;try{return await g.apply(s,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;n.calls+=1,n.durationMs+=i,n.perOperation[r]=(n.perOperation[r]??0)+1,d!==void 0&&(n.errors+=1);try{t.mode==="spans"&&(n.spansEmitted>=y?n.spansTruncated=!0:(n.spansEmitted+=1,t.record(E({deps:t,durationMs:i,failure:d,operation:r,startTs:l,table:h}))))}catch{}}};return a.set(r,u),u}})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),P=e=>{const t={"db.calls":e.calls,"db.duration_ms":e.durationMs};e.errors>0&&(t["db.errors"]=e.errors),e.spansTruncated&&(t["db.spans_truncated"]=!0);for(const[n,a]of Object.entries(e.perOperation))t[`db.op.${n}`]=a;return t};export{D as createDatabaseTally,P as formatTally,v as instrumentDatabase};
@@ -0,0 +1 @@
1
+ import{f as E,n as b}from"./request-log-COB2xhns.mjs";import{L as g,o as R,b as H,t as A}from"./trace-context-CpFltS-q.mjs";const N=/[\w.-]/u,x=t=>{let e="";for(const r of t)e+=N.test(r)?r:"_";return e},K=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=x(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},L=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},j=128,z=128,D=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},F=t=>{try{return new URL(t).host}catch{return t}},U=(t,e)=>{try{return t(new URL(e))}catch{return!1}},q=t=>t===void 0?{}:L(t)?t:{attributes:t},C=(t,e)=>{if(t.isTraced){t.setAttribute(g.functionPath,e.functionPath),t.setAttribute(g.ok,e.ok),t.setAttribute(g.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(g.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(g.userId,e.userId),e.error!==void 0&&(t.setAttribute(g.errorType,e.error.type),t.setAttribute(g.errorMessage,e.error.message));for(const[r,o]of Object.entries(e.attributes))(typeof o=="boolean"||typeof o=="number"||typeof o=="string")&&t.setAttribute(`lunora.attr.${r}`,o)}},X=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},o={spanContext:()=>t,addEvent:(s,n)=>{if(r.events.length>=j)return;const a=b(n);r.events.push({...a===void 0?{}:{attributes:a},name:s,ts:Date.now()})},addLink:s=>{if(r.links.length>=z)return;const n=b(s.attributes);r.links.push({...n===void 0?{}:{attributes:n},spanId:s.spanId,traceId:s.traceId})},recordEvaluation:s=>{Object.assign(r.attributes,b(K(s)))},recordException:s=>{const n=s instanceof Error?s.message:String(s);o.addEvent("exception",{"exception.message":E(n,e),...e&&s instanceof Error&&typeof s.stack=="string"?{"exception.stacktrace":s.stack}:{},"exception.type":A(s)})},setAttribute:(s,n)=>{Object.assign(r.attributes,b({[s]:n}))},setAttributes:s=>{Object.assign(r.attributes,b(s))}};return{collected:r,handle:o}},G=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:o,functionPath:s,record:n,resolveHostTracing:a,shardKey:i,userId:f}=t,u=p=>async(I,d,_)=>{const l=R(8),y=Date.now(),c=q(_),O=b(c.attributes),{collected:k,handle:$}=X({spanId:l,traceId:e.traceId},r),P=async v=>{let m=!0,w;try{return await d(u(l),$)}catch(h){m=!1;const S=h instanceof Error?h.message:String(h);throw w={message:E(S,r),type:A(h)},h}finally{const h=Date.now()-y,S=f(),T={...O,...k.attributes},M=[...c.links??[],...k.links];try{n({...Object.keys(T).length===0?{}:{attributes:T},durationMs:h,...k.events.length===0?{}:{events:k.events},...w===void 0?{}:{error:w},functionPath:s,...c.kind===void 0||c.kind==="internal"?{}:{kind:c.kind},...M.length===0?{}:{links:M},name:I,ok:m,parentSpanId:p,shardKey:i,spanId:l,startTs:y,traceId:e.traceId,userId:S})}catch{}if(v!==void 0)try{C(v,{attributes:T,durationMs:h,error:w,functionPath:s,ok:m,shardKey:i,userId:S})}catch{}}};if(o===!0&&a!==void 0){const v=await a();if(v!==void 0&&typeof v.enterSpan=="function")return await v.enterSpan(I,m=>P(m))}return await P()};return u(e.rootSpanId)},J=(t,e)=>{const{anchor:r,functionPath:o,propagate:s=!0,record:n,shardKey:a,userId:i}=t;return async(f,u)=>{const p=R(8),I=Date.now(),d=new Request(f,u);(typeof s=="function"?U(s,d.url):s)&&d.headers.set("traceparent",H(r.traceId,p,r.sampled??!0));let l,y;try{const c=await e(d);return y=c.status,c.ok||(l={message:`HTTP ${String(c.status)}`,type:`HTTP_${String(c.status)}`}),c}catch(c){throw l={message:c instanceof Error?c.message:String(c),type:A(c)},c}finally{try{n({attributes:{"http.request.method":d.method,...y===void 0?{}:{"http.response.status_code":y},"url.full":D(d.url)},durationMs:Date.now()-I,...l===void 0?{}:{error:l},functionPath:o,kind:"client",name:`${d.method} ${F(d.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:a,spanId:p,startTs:I,traceId:r.traceId,userId:i()})}catch{}}}},Q=t=>{const{functionPath:e,record:r,shardKey:o}=t,s=(n,a,i,f)=>{if(!Number.isFinite(i))return;const u=b(f);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:n,name:a,shardKey:o,ts:Date.now(),value:i})}catch{}};return{count:(n,a=1,i)=>{s("counter",n,a,i)},gauge:(n,a,i)=>{s("gauge",n,a,i)},record:(n,a,i)=>{s("histogram",n,a,i)}}},W=t=>{const{anchor:e,captureRaw:r=!1,collected:o,durationMs:s,failure:n,functionPath:a,shardKey:i,startTs:f,userId:u}=t,p=o?.attributes??{};return{...Object.keys(p).length===0?{}:{attributes:p},dispatch:!0,durationMs:s,...o===void 0||o.events.length===0?{}:{events:o.events},...n===void 0?{}:{error:{message:E(n.thrown instanceof Error?n.thrown.message:String(n.thrown),r),type:A(n.thrown)}},functionPath:a,...o===void 0||o.links.length===0?{}:{links:o.links},name:a,ok:n===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:f,traceId:e.traceId,userId:u}};export{C as applyHostSpanAttributes,Q as createMetrics,X as createSpanCollector,J as createTracedFetch,G as createTracer,W as dispatchRootSpan};
@@ -0,0 +1 @@
1
+ const c=(t,s)=>t<s?-1:t>s?1:0,n=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e=>n(e)).join(",")}]`;const s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){const e=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${e} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const r=t,i=Object.keys(r).toSorted(c),a=[];for(const e of i){const o=r[e];o!==void 0&&a.push(`${JSON.stringify(e)}:${n(o)}`)}return`{${a.join(",")}}`};const u=t=>`${t.kind}${t.name}${n(t.attributes??{})}`;class f{capacity;series=new Map;constructor(s=256){this.capacity=s>0?Math.trunc(s):256}get size(){return this.series.size}clear(){this.series.clear()}entries(){return[...this.series.values()].toReversed().map(s=>({...s}))}push(s){const r=u(s),i=this.series.get(r);if(i===void 0){if(this.series.size>=this.capacity){const a=this.series.keys().next().value;a!==void 0&&this.series.delete(a)}this.series.set(r,{...s.attributes===void 0?{}:{attributes:s.attributes},count:1,...s.traceId===void 0?{}:{exemplarTraceId:s.traceId},firstTs:s.ts,functionPath:s.functionPath,kind:s.kind,last:s.value,lastTs:s.ts,max:s.value,min:s.value,name:s.name,...s.shardKey===void 0?{}:{shardKey:s.shardKey},sum:s.value});return}this.series.delete(r),i.count+=1,i.sum+=s.value,i.min=Math.min(i.min,s.value),i.max=Math.max(i.max,s.value),i.last=s.value,i.lastTs=s.ts,i.functionPath=s.functionPath,s.traceId!==void 0&&(i.exemplarTraceId=s.traceId),this.series.set(r,i)}}export{f as M,u as m,n as s};
@@ -1,4 +1,4 @@
1
- import{m as l,s as I}from"./metric-buffer-BGdHQs8k.mjs";import{r as a}from"./run-sql-0aPgJkIw.mjs";const n="__lunora_metric_history",_=6e4,O=1440,d=1e3,L=5e3,A=e=>Math.floor(e/_)*_,k=new WeakSet,R=e=>{k.has(e)||(a(e,`CREATE TABLE IF NOT EXISTS "${n}" (
1
+ import{m as l,s as I}from"./metric-buffer-QGsa8K4_.mjs";import{r as a}from"./run-sql-0aPgJkIw.mjs";const n="__lunora_metric_history",_=6e4,O=1440,d=1e3,L=5e3,A=e=>Math.floor(e/_)*_,k=new WeakSet,R=e=>{k.has(e)||(a(e,`CREATE TABLE IF NOT EXISTS "${n}" (
2
2
  series_key TEXT NOT NULL,
3
3
  bucket_ms INTEGER NOT NULL,
4
4
  name TEXT NOT NULL,
@@ -0,0 +1,22 @@
1
+ import{fingerprintError as L}from"@lunora/fingerprint";import{redact as A,standardRules as y}from"@visulima/redact";import{readIssueStates as M}from"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{r as h}from"./run-sql-0aPgJkIw.mjs";const U=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},p=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:U(e),R=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[i,r]of Object.entries(t))s[i]=p(r);if(e!==void 0)for(const[i,r]of Object.entries(e))s[i]=p(r);return Object.keys(s).length===0?void 0:s},u="__lunora_reqlog__",_=1e3,O="lunora",P=["error_fingerprint TEXT","trace_id TEXT"],l=(e,t=!1)=>t||e===null||e===void 0?e:A(e,y),T=e=>{h(e,`CREATE TABLE IF NOT EXISTS "${u}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ function_path TEXT NOT NULL,
5
+ shard_key TEXT,
6
+ user_id TEXT,
7
+ identity TEXT,
8
+ args TEXT,
9
+ outcome TEXT NOT NULL,
10
+ error_message TEXT,
11
+ error_fingerprint TEXT,
12
+ trace_id TEXT,
13
+ duration_ms REAL NOT NULL,
14
+ tables_read TEXT NOT NULL DEFAULT '[]',
15
+ tables_written TEXT NOT NULL DEFAULT '[]',
16
+ cache_hit INTEGER,
17
+ subscriptions_rerun INTEGER NOT NULL DEFAULT 0
18
+ )`);for(const t of P)try{h(e,`ALTER TABLE "${u}" ADD COLUMN ${t}`)}catch{}},S=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),D=e=>e===void 0?null:e?1:0,W=(e,t,s={})=>{T(e);const i=s.captureRaw??!1,r=s.retention??_,E=t.outcome==="error"&&t.errorMessage!==void 0?L({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;h(e,`INSERT INTO "${u}"
19
+ (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(l(t.identity,i)),t.redactedArgs===void 0?null:JSON.stringify(l(t.redactedArgs,i)),t.outcome,t.errorMessage===void 0?null:l(t.errorMessage,i),E??null,t.traceId??null,t.durationMs,S(t.tablesRead),S(t.tablesWritten),D(t.cacheHit),t.subscriptionsReRun??0),h(e,`DELETE FROM "${u}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${u}")`,r)},V=(e,t={})=>{const s=t.captureRaw??!1,i={args:e.redactedArgs===void 0?void 0:l(e.redactedArgs,s),cacheHit:e.cacheHit,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:l(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:l(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:O,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId},r=JSON.stringify(i);e.outcome==="error"?console.error(r):console.log(r)},X="log",F=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),j=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Y=(e,t)=>e.length===2&&typeof e[0]=="string"&&j(e[1])?{fields:R(e[1],t),message:e[0]}:{fields:R(void 0,t),message:F(e)},w=(e,t={})=>{const s=t.captureRaw??!1,i={fields:e.fields===void 0?void 0:l(e.fields,s),function:e.functionPath,level:e.level,message:e.message,shard:e.shardKey,source:O,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:X,userId:e.userId};let r;try{r=JSON.stringify(i)}catch{r=JSON.stringify({...i,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(r):e.level==="warn"?console.warn(r):console.log(r)},J=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,b=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(J("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},N=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},k=e=>{try{return JSON.parse(e)}catch{return}},B=(e,t={})=>{T(e);const s=Math.max(1,Math.min(t.limit??_,1e4)),i=["seq > ?"],r=[t.sinceSeq??0];if(b(i,r,t),t.outcome!==void 0&&(i.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);i.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),r.push(o,o)}return r.push(s),h(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
21
+ FROM "${u}" WHERE ${i.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray().map(o=>{const n={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:N(o.tables_read),tablesWritten:N(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(n.shardKey=o.shard_key),o.user_id!==null&&(n.userId=o.user_id),o.identity!==null){const c=$(o.identity);c!==void 0&&(n.identity=c)}if(o.args!==null){const c=k(o.args);c!==void 0&&(n.redactedArgs=c)}return o.error_message!==null&&(n.errorMessage=o.error_message),o.cache_hit!==null&&(n.cacheHit=o.cache_hit===1),o.trace_id!==null&&(n.traceId=o.trace_id),n})},q=(e,t)=>{const s=M(e,[...t.keys()]);for(const i of t.values()){const r=s.get(i.hash);r!==void 0&&(i.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(i.assignee=r.assignee),r.severity!==void 0&&(i.severity=r.severity),i.status=r.status==="resolved"&&i.lastSeen>r.updatedAt?"open":r.status)}},Q=(e,t={})=>{T(e);const s=Math.max(1,Math.min(t.limit??_,1e4)),i=["outcome = 'error'"],r=[];b(i,r,t),r.push(s);const E=h(e,`SELECT function_path, error_message, error_fingerprint, ts
22
+ FROM "${u}" WHERE ${i.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),o=new Map,n=new Map;for(const a of E){const g=a.error_message??"",{culprit:I,hash:v,title:m}=L({functionPath:a.function_path,message:g}),f=a.error_fingerprint??v,d=o.get(f);if(d===void 0){o.set(f,{count:1,culprit:I,firstSeen:a.ts,hash:f,lastSeen:a.ts,sampleMessage:g,status:"open",title:m}),n.set(f,a.ts);continue}d.count+=1,d.firstSeen=Math.min(d.firstSeen,a.ts),d.lastSeen=Math.max(d.lastSeen,a.ts),a.ts>(n.get(f)??Number.NEGATIVE_INFINITY)&&(n.set(f,a.ts),d.sampleMessage=g,d.title=m)}q(e,o);const c=[...o.values()];return(t.status===void 0?c:c.filter(a=>a.status===t.status)).toSorted((a,g)=>g.lastSeen-a.lastSeen)};export{u as R,W as a,V as b,T as c,B as d,w as e,l as f,_ as g,F as h,R as n,Y as p,Q as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.30",
3
+ "version": "1.0.0-alpha.31",
4
4
  "description": "Host-neutral telemetry storage and read models for Lunora, backing the Studio's Logs, Traces, Metrics and Issues views",
5
5
  "keywords": [
6
6
  "lunora",
@@ -45,7 +45,7 @@
45
45
  "dependencies": {
46
46
  "@lunora/errors": "1.0.0-alpha.22",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.7",
48
- "@lunora/shard-engine": "1.0.0-alpha.30",
48
+ "@lunora/shard-engine": "1.0.0-alpha.31",
49
49
  "@visulima/redact": "4.0.0"
50
50
  },
51
51
  "engines": {
@@ -1 +0,0 @@
1
- import{M as f,m as i}from"./metric-buffer-BGdHQs8k.mjs";export{f as MetricBuffer,i as metricSeriesKey};
@@ -1 +0,0 @@
1
- import{f as T,n as b}from"./request-log-Dp7JeJec.mjs";import{L as g,o as R,b as H,t as A}from"./trace-context-CpFltS-q.mjs";const N=/[\w.-]/u,x=t=>{let e="";for(const r of t)e+=N.test(r)?r:"_";return e},K=t=>{if(typeof t.name!="string"||t.name.length===0)throw new Error("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new Error("recordEvaluation `score` must be a finite number");const e=x(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},L=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},j=128,z=128,D=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},F=t=>{try{return new URL(t).host}catch{return t}},U=(t,e)=>{try{return t(new URL(e))}catch{return!1}},q=t=>t===void 0?{}:L(t)?t:{attributes:t},C=(t,e)=>{if(t.isTraced){t.setAttribute(g.functionPath,e.functionPath),t.setAttribute(g.ok,e.ok),t.setAttribute(g.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(g.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(g.userId,e.userId),e.error!==void 0&&(t.setAttribute(g.errorType,e.error.type),t.setAttribute(g.errorMessage,e.error.message));for(const[r,o]of Object.entries(e.attributes))(typeof o=="boolean"||typeof o=="number"||typeof o=="string")&&t.setAttribute(`lunora.attr.${r}`,o)}},X=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},o={spanContext:()=>t,addEvent:(s,n)=>{if(r.events.length>=j)return;const a=b(n);r.events.push({...a===void 0?{}:{attributes:a},name:s,ts:Date.now()})},addLink:s=>{if(r.links.length>=z)return;const n=b(s.attributes);r.links.push({...n===void 0?{}:{attributes:n},spanId:s.spanId,traceId:s.traceId})},recordEvaluation:s=>{Object.assign(r.attributes,b(K(s)))},recordException:s=>{const n=s instanceof Error?s.message:String(s);o.addEvent("exception",{"exception.message":T(n,e),...e&&s instanceof Error&&typeof s.stack=="string"?{"exception.stacktrace":s.stack}:{},"exception.type":A(s)})},setAttribute:(s,n)=>{Object.assign(r.attributes,b({[s]:n}))},setAttributes:s=>{Object.assign(r.attributes,b(s))}};return{collected:r,handle:o}},G=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:o,functionPath:s,record:n,resolveHostTracing:a,shardKey:i,userId:f}=t,u=p=>async(I,d,_)=>{const l=R(8),y=Date.now(),c=q(_),O=b(c.attributes),{collected:k,handle:$}=X({spanId:l,traceId:e.traceId},r),P=async v=>{let m=!0,w;try{return await d(u(l),$)}catch(h){m=!1;const S=h instanceof Error?h.message:String(h);throw w={message:T(S,r),type:A(h)},h}finally{const h=Date.now()-y,S=f(),E={...O,...k.attributes},M=[...c.links??[],...k.links];try{n({...Object.keys(E).length===0?{}:{attributes:E},durationMs:h,...k.events.length===0?{}:{events:k.events},...w===void 0?{}:{error:w},functionPath:s,...c.kind===void 0||c.kind==="internal"?{}:{kind:c.kind},...M.length===0?{}:{links:M},name:I,ok:m,parentSpanId:p,shardKey:i,spanId:l,startTs:y,traceId:e.traceId,userId:S})}catch{}if(v!==void 0)try{C(v,{attributes:E,durationMs:h,error:w,functionPath:s,ok:m,shardKey:i,userId:S})}catch{}}};if(o===!0&&a!==void 0){const v=await a();if(v!==void 0&&typeof v.enterSpan=="function")return await v.enterSpan(I,m=>P(m))}return await P()};return u(e.rootSpanId)},J=(t,e)=>{const{anchor:r,functionPath:o,propagate:s=!0,record:n,shardKey:a,userId:i}=t;return async(f,u)=>{const p=R(8),I=Date.now(),d=new Request(f,u);(typeof s=="function"?U(s,d.url):s)&&d.headers.set("traceparent",H(r.traceId,p,r.sampled??!0));let l,y;try{const c=await e(d);return y=c.status,c.ok||(l={message:`HTTP ${String(c.status)}`,type:`HTTP_${String(c.status)}`}),c}catch(c){throw l={message:c instanceof Error?c.message:String(c),type:A(c)},c}finally{try{n({attributes:{"http.request.method":d.method,...y===void 0?{}:{"http.response.status_code":y},"url.full":D(d.url)},durationMs:Date.now()-I,...l===void 0?{}:{error:l},functionPath:o,kind:"client",name:`${d.method} ${F(d.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:a,spanId:p,startTs:I,traceId:r.traceId,userId:i()})}catch{}}}},Q=t=>{const{functionPath:e,record:r,shardKey:o}=t,s=(n,a,i,f)=>{if(!Number.isFinite(i))return;const u=b(f);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:n,name:a,shardKey:o,ts:Date.now(),value:i})}catch{}};return{count:(n,a=1,i)=>{s("counter",n,a,i)},gauge:(n,a,i)=>{s("gauge",n,a,i)},record:(n,a,i)=>{s("histogram",n,a,i)}}},W=t=>{const{anchor:e,captureRaw:r=!1,collected:o,durationMs:s,failure:n,functionPath:a,shardKey:i,startTs:f,userId:u}=t,p=o?.attributes??{};return{...Object.keys(p).length===0?{}:{attributes:p},dispatch:!0,durationMs:s,...o===void 0||o.events.length===0?{}:{events:o.events},...n===void 0?{}:{error:{message:T(n.thrown instanceof Error?n.thrown.message:String(n.thrown),r),type:A(n.thrown)}},functionPath:a,...o===void 0||o.links.length===0?{}:{links:o.links},name:a,ok:n===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:f,traceId:e.traceId,userId:u}};export{C as applyHostSpanAttributes,Q as createMetrics,X as createSpanCollector,J as createTracedFetch,G as createTracer,W as dispatchRootSpan};
@@ -1 +0,0 @@
1
- const n=(t,s)=>t<s?-1:t>s?1:0,o=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e=>o(e)).join(",")}]`;const s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){const e=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${e} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const r=t,i=Object.keys(r).toSorted(n),a=[];for(const e of i){const c=r[e];c!==void 0&&a.push(`${JSON.stringify(e)}:${o(c)}`)}return`{${a.join(",")}}`};const u=t=>`${t.kind}${t.name}${o(t.attributes??{})}`;class y{capacity;series=new Map;constructor(s=256){this.capacity=s>0?Math.trunc(s):256}get size(){return this.series.size}clear(){this.series.clear()}entries(){return[...this.series.values()].toReversed().map(s=>({...s}))}push(s){const r=u(s),i=this.series.get(r);if(i===void 0){if(this.series.size>=this.capacity){const a=this.series.keys().next().value;a!==void 0&&this.series.delete(a)}this.series.set(r,{...s.attributes===void 0?{}:{attributes:s.attributes},count:1,...s.traceId===void 0?{}:{exemplarTraceId:s.traceId},firstTs:s.ts,functionPath:s.functionPath,kind:s.kind,last:s.value,lastTs:s.ts,max:s.value,min:s.value,name:s.name,...s.shardKey===void 0?{}:{shardKey:s.shardKey},sum:s.value});return}this.series.delete(r),i.count+=1,i.sum+=s.value,i.min=Math.min(i.min,s.value),i.max=Math.max(i.max,s.value),i.last=s.value,i.lastTs=s.ts,i.functionPath=s.functionPath,s.traceId!==void 0&&(i.exemplarTraceId=s.traceId),this.series.set(r,i)}}export{y as M,u as m,o as s};
@@ -1,22 +0,0 @@
1
- import{fingerprintError as L}from"@lunora/fingerprint";import{redact as M,standardRules as v}from"@visulima/redact";import{readIssueStates as y}from"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{r as f}from"./run-sql-0aPgJkIw.mjs";const U=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},p=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:U(e),R=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[o,r]of Object.entries(t))s[o]=p(r);if(e!==void 0)for(const[o,r]of Object.entries(e))s[o]=p(r);return Object.keys(s).length===0?void 0:s},d="__lunora_reqlog__",E=1e3,O="lunora",P=["error_fingerprint TEXT","trace_id TEXT"],u=(e,t=!1)=>t||e===null||e===void 0?e:M(e,v),_=e=>{f(e,`CREATE TABLE IF NOT EXISTS "${d}" (
2
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
- ts REAL NOT NULL,
4
- function_path TEXT NOT NULL,
5
- shard_key TEXT,
6
- user_id TEXT,
7
- identity TEXT,
8
- args TEXT,
9
- outcome TEXT NOT NULL,
10
- error_message TEXT,
11
- error_fingerprint TEXT,
12
- trace_id TEXT,
13
- duration_ms REAL NOT NULL,
14
- tables_read TEXT NOT NULL DEFAULT '[]',
15
- tables_written TEXT NOT NULL DEFAULT '[]',
16
- cache_hit INTEGER,
17
- subscriptions_rerun INTEGER NOT NULL DEFAULT 0
18
- )`);for(const t of P)try{f(e,`ALTER TABLE "${d}" ADD COLUMN ${t}`)}catch{}},S=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),D=e=>e===void 0?null:e?1:0,H=(e,t,s={})=>{_(e);const o=s.captureRaw??!1,r=s.retention??E,g=t.outcome==="error"&&t.errorMessage!==void 0?L({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;f(e,`INSERT INTO "${d}"
19
- (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
20
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(u(t.identity,o)),t.redactedArgs===void 0?null:JSON.stringify(u(t.redactedArgs,o)),t.outcome,t.errorMessage===void 0?null:u(t.errorMessage,o),g??null,t.traceId??null,t.durationMs,S(t.tablesRead),S(t.tablesWritten),D(t.cacheHit),t.subscriptionsReRun??0),f(e,`DELETE FROM "${d}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${d}")`,r)},K=(e,t={})=>{const s=t.captureRaw??!1,o={args:e.redactedArgs===void 0?void 0:u(e.redactedArgs,s),cacheHit:e.cacheHit,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:u(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:u(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:O,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId},r=JSON.stringify(o);e.outcome==="error"?console.error(r):console.log(r)},X="log",F=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),J=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},W=(e,t)=>e.length===2&&typeof e[0]=="string"&&J(e[1])?{fields:R(e[1],t),message:e[0]}:{fields:R(void 0,t),message:F(e)},V=(e,t={})=>{const s=t.captureRaw??!1,o={fields:e.fields===void 0?void 0:u(e.fields,s),function:e.functionPath,level:e.level,message:e.message,shard:e.shardKey,source:O,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:X,userId:e.userId};let r;try{r=JSON.stringify(o)}catch{r=JSON.stringify({...o,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(r):e.level==="warn"?console.warn(r):console.log(r)},$=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,b=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push($("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},N=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},Y=(e,t={})=>{_(e);const s=Math.max(1,Math.min(t.limit??E,1e4)),o=["seq > ?"],r=[t.sinceSeq??0];if(b(o,r,t),t.outcome!==void 0&&(o.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const i=JSON.stringify(t.tableTouched);o.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),r.push(i,i)}return r.push(s),f(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
21
- FROM "${d}" WHERE ${o.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray().map(i=>{const n={durationMs:i.duration_ms,functionPath:i.function_path,outcome:i.outcome==="error"?"error":"ok",seq:i.seq,subscriptionsReRun:i.subscriptions_rerun,tablesRead:N(i.tables_read),tablesWritten:N(i.tables_written),ts:i.ts};return i.shard_key!==null&&(n.shardKey=i.shard_key),i.user_id!==null&&(n.userId=i.user_id),i.identity!==null&&(n.identity=JSON.parse(i.identity)),i.args!==null&&(n.redactedArgs=JSON.parse(i.args)),i.error_message!==null&&(n.errorMessage=i.error_message),i.cache_hit!==null&&(n.cacheHit=i.cache_hit===1),i.trace_id!==null&&(n.traceId=i.trace_id),n})},j=(e,t)=>{const s=y(e,[...t.keys()]);for(const o of t.values()){const r=s.get(o.hash);r!==void 0&&(o.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(o.assignee=r.assignee),r.severity!==void 0&&(o.severity=r.severity),o.status=r.status==="resolved"&&o.lastSeen>r.updatedAt?"open":r.status)}},w=(e,t={})=>{_(e);const s=Math.max(1,Math.min(t.limit??E,1e4)),o=["outcome = 'error'"],r=[];b(o,r,t),r.push(s);const g=f(e,`SELECT function_path, error_message, error_fingerprint, ts
22
- FROM "${d}" WHERE ${o.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),i=new Map,n=new Map;for(const a of g){const h=a.error_message??"",{culprit:I,hash:A,title:m}=L({functionPath:a.function_path,message:h}),l=a.error_fingerprint??A,c=i.get(l);if(c===void 0){i.set(l,{count:1,culprit:I,firstSeen:a.ts,hash:l,lastSeen:a.ts,sampleMessage:h,status:"open",title:m}),n.set(l,a.ts);continue}c.count+=1,c.firstSeen=Math.min(c.firstSeen,a.ts),c.lastSeen=Math.max(c.lastSeen,a.ts),a.ts>(n.get(l)??Number.NEGATIVE_INFINITY)&&(n.set(l,a.ts),c.sampleMessage=h,c.title=m)}j(e,i);const T=[...i.values()];return(t.status===void 0?T:T.filter(a=>a.status===t.status)).toSorted((a,h)=>h.lastSeen-a.lastSeen)};export{d as R,H as a,K as b,_ as c,Y as d,V as e,u as f,E as g,F as h,R as n,W as p,w as r};