@lunora/observability 1.0.0-alpha.11 → 1.0.0-alpha.12

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-C2V-DiGu.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-BXNmqy0o.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-DBs7wDeF.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as p,FUNCTION_METRICS_BUCKET_MS as d,FUNCTION_METRICS_BUCKET_RETENTION as f,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 D,recordFunctionMetric as K}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BB8kcFBe.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as h,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-xF11R4vX.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as k,upsertIssueState as P}from"./packem_shared/ISSUE_SEVERITIES-Js6lGUG5.mjs";import{LogBuffer as V}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{M as j}from"./packem_shared/metric-buffer-CdgXal7w.mjs";import{readMetricHistory as J,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-CVcUgQEL.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-DN07YcQy.mjs";import{d as Te,k as oe,K as ae,w as se,m as Ee,C as _e,W as ce,U as Se,c as Ie}from"./packem_shared/request-log-BwFic6VV.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-T-zuwRVR.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-BR6Ff0M-.mjs";import{findDanglingReferences as pe}from"./packem_shared/findDanglingReferences-D-x9LvY0.mjs";import{r as fe}from"./packem_shared/trace-context-DrdF960P.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,h as DEFAULT_EXPLAIN_ISSUE_MODEL,p as FUNCTION_METRICS_BUCKETS_TABLE,d as FUNCTION_METRICS_BUCKET_MS,f 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,k as ISSUE_STATUSES,V as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,j 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,pe 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,D as readFunctionMetricsTotals,J as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,K as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,fe as resolveTraceAnchor,P 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-DpVJl1bU.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-1k6z1bld.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-_X8tMObq.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as U,FUNCTION_METRICS_BUCKET_MS as d,FUNCTION_METRICS_BUCKET_RETENTION as f,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 h,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BXPeggfa.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as b,explainIssue as v,parseExplainIssueArgs as q}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-xF11R4vX.mjs";import{ISSUE_SEVERITIES as X,ISSUE_STATE_TABLE as G,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-E91cPcjt.mjs";import{LogBuffer as V}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{M as z}from"./packem_shared/metric-buffer-CdgXal7w.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-BdC01ptv.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-BprtfEp-.mjs";import{d as Te,v as oe,K as ae,w as se,h as Ee,F as _e,X as ce,C as Se,c as Ie}from"./packem_shared/request-log-CHl9HlyL.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-T-zuwRVR.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-BR6Ff0M-.mjs";import{findDanglingReferences as Ue}from"./packem_shared/findDanglingReferences-D-x9LvY0.mjs";import{r as fe}from"./packem_shared/trace-context-DrdF960P.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,b as DEFAULT_EXPLAIN_ISSUE_MODEL,U as FUNCTION_METRICS_BUCKETS_TABLE,d as FUNCTION_METRICS_BUCKET_MS,f 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,X as ISSUE_SEVERITIES,G as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,V 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,v as explainIssue,Ue as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,q as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,h 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,fe as resolveTraceAnchor,k as upsertIssueState};
@@ -0,0 +1,22 @@
1
+ import{e as E}from"./run-sql-BP8BI9zV.mjs";const r="__lunora_auth_metrics",T="__lunora_auth_metrics_buckets",m="app",_=6e4,N=1440,R=s=>Math.floor(s/_)*_,i=s=>{E(s,`CREATE TABLE IF NOT EXISTS "${r}" (
2
+ key TEXT PRIMARY KEY,
3
+ attempts INTEGER NOT NULL DEFAULT 0,
4
+ failures INTEGER NOT NULL DEFAULT 0,
5
+ since_ms INTEGER NOT NULL DEFAULT 0
6
+ )`),E(s,`CREATE TABLE IF NOT EXISTS "${T}" (
7
+ bucket_ms INTEGER PRIMARY KEY,
8
+ attempts INTEGER NOT NULL DEFAULT 0,
9
+ failures INTEGER NOT NULL DEFAULT 0
10
+ )`)},l=(s,e)=>{i(s);const t=e.outcome==="fail"?1:0;E(s,`INSERT INTO "${r}" (key, attempts, failures, since_ms)
11
+ VALUES (?, 1, ?, ?)
12
+ ON CONFLICT(key) DO UPDATE SET
13
+ attempts = attempts + 1,
14
+ failures = failures + excluded.failures,
15
+ since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,m,t,e.ts);const a=R(e.ts);E(s,`INSERT INTO "${T}" (bucket_ms, attempts, failures)
16
+ VALUES (?, 1, ?)
17
+ ON CONFLICT(bucket_ms) DO UPDATE SET
18
+ attempts = attempts + 1,
19
+ failures = failures + excluded.failures`,a,t),E(s,`DELETE FROM "${T}"
20
+ WHERE bucket_ms <= (
21
+ SELECT MAX(bucket_ms) - ? FROM "${T}"
22
+ )`,N*_)},I=s=>{i(s);const e=E(s,`SELECT attempts, failures, since_ms FROM "${r}" WHERE key = ?`,m).toArray()[0],t=e?.attempts??0,a=e?.failures??0,c=e?.since_ms??0,A=E(s,`SELECT bucket_ms, attempts, failures FROM "${T}" ORDER BY bucket_ms ASC`).toArray().map(u=>({attempts:u.attempts,bucketMs:u.bucket_ms,failures:u.failures}));return{attempts:t,failureRate:t===0?0:a/t,failures:a,history:A,sinceMs:c}};export{T as AUTH_METRICS_BUCKETS_TABLE,_ as AUTH_METRICS_BUCKET_MS,N as AUTH_METRICS_BUCKET_RETENTION,m as AUTH_METRICS_ROW_KEY,r as AUTH_METRICS_TABLE,i as ensureAuthMetricsTables,I as readAuthMetrics,l as recordAuthEvent};
@@ -0,0 +1,56 @@
1
+ import{e as r}from"./run-sql-BP8BI9zV.mjs";const E="__lunora_metrics",l="__lunora_metrics_buckets",N="__lunora_metrics_scans",L="__lunora_metrics_index",d=6e4,O=1440,m=5e3,_=1e3,C=e=>Math.floor(e/d)*d,M=e=>{const a=new Map;for(const s of e)a.set(`${s.table}\0${s.index}`,{index:s.index,table:s.table});return[...a.values()]},i=new WeakSet,o=e=>{if(!i.has(e)){r(e,`CREATE TABLE IF NOT EXISTS "${E}" (
2
+ path TEXT PRIMARY KEY,
3
+ calls INTEGER NOT NULL DEFAULT 0,
4
+ errors INTEGER NOT NULL DEFAULT 0,
5
+ conflicts INTEGER NOT NULL DEFAULT 0,
6
+ scans INTEGER NOT NULL DEFAULT 0,
7
+ total_duration_ms REAL NOT NULL DEFAULT 0,
8
+ min_duration_ms REAL,
9
+ max_duration_ms REAL NOT NULL DEFAULT 0,
10
+ last_called_at REAL NOT NULL DEFAULT 0,
11
+ last_error_at REAL,
12
+ last_error_message TEXT
13
+ )`);for(const a of["scans","conflicts"])try{r(e,`ALTER TABLE "${E}" ADD COLUMN ${a} INTEGER NOT NULL DEFAULT 0`)}catch{}r(e,`CREATE TABLE IF NOT EXISTS "${l}" (
14
+ path TEXT NOT NULL,
15
+ bucket_ms INTEGER NOT NULL,
16
+ calls INTEGER NOT NULL DEFAULT 0,
17
+ errors INTEGER NOT NULL DEFAULT 0,
18
+ PRIMARY KEY (path, bucket_ms)
19
+ )`),r(e,`CREATE TABLE IF NOT EXISTS "${N}" (
20
+ path TEXT NOT NULL,
21
+ table_name TEXT NOT NULL,
22
+ scans INTEGER NOT NULL DEFAULT 0,
23
+ PRIMARY KEY (path, table_name)
24
+ )`),r(e,`CREATE TABLE IF NOT EXISTS "${L}" (
25
+ table_name TEXT NOT NULL,
26
+ index_name TEXT NOT NULL,
27
+ reads INTEGER NOT NULL DEFAULT 0,
28
+ PRIMARY KEY (table_name, index_name)
29
+ )`),i.add(e)}},u=new WeakMap,U=e=>{let a=u.get(e);return a===void 0&&(a=new Set,u.set(e,a)),a},p=(e,a)=>{const s=U(e);return s.has(a)?!0:r(e,`SELECT 1 AS c FROM "${E}" WHERE path = ? LIMIT 1`,a).toArray().length>0?(s.add(a),!0):r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=m?!1:(s.add(a),!0)},h=(e,a)=>{if(o(e),!p(e,a.path))return;const s=a.scannedTables?[...new Set(a.scannedTables)]:[],t=s.length,n=M(a.indexHits??[]),T=a.errored?1:0,S=a.conflicted?1:0,A=a.errored?a.ts:null,I=a.errored?a.errorMessage??null:null;r(e,`INSERT INTO "${E}"
30
+ (path, calls, errors, conflicts, scans, total_duration_ms, min_duration_ms, max_duration_ms, last_called_at, last_error_at, last_error_message)
31
+ VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)
32
+ ON CONFLICT(path) DO UPDATE SET
33
+ calls = calls + 1,
34
+ errors = errors + excluded.errors,
35
+ conflicts = conflicts + excluded.conflicts,
36
+ scans = scans + excluded.scans,
37
+ total_duration_ms = total_duration_ms + excluded.total_duration_ms,
38
+ min_duration_ms = MIN(COALESCE(min_duration_ms, excluded.min_duration_ms), excluded.min_duration_ms),
39
+ max_duration_ms = MAX(max_duration_ms, excluded.max_duration_ms),
40
+ last_called_at = excluded.last_called_at,
41
+ last_error_at = CASE WHEN excluded.last_error_at IS NULL THEN last_error_at ELSE excluded.last_error_at END,
42
+ last_error_message = CASE WHEN excluded.last_error_at IS NULL THEN last_error_message ELSE excluded.last_error_message END`,a.path,T,S,t,a.durationMs,a.durationMs,a.durationMs,a.ts,A,I);const R=C(a.ts);r(e,`INSERT INTO "${l}" (path, bucket_ms, calls, errors)
43
+ VALUES (?, ?, 1, ?)
44
+ ON CONFLICT(path, bucket_ms) DO UPDATE SET
45
+ calls = calls + 1,
46
+ errors = errors + excluded.errors`,a.path,R,T),r(e,`DELETE FROM "${l}"
47
+ WHERE path = ?
48
+ AND bucket_ms <= (
49
+ SELECT MAX(bucket_ms) - ? FROM "${l}" WHERE path = ?
50
+ )`,a.path,O*d,a.path);for(const c of s)r(e,`INSERT INTO "${N}" (path, table_name, scans)
51
+ VALUES (?, ?, 1)
52
+ ON CONFLICT(path, table_name) DO UPDATE SET
53
+ scans = scans + 1`,a.path,c);for(const c of n)r(e,`INSERT INTO "${L}" (table_name, index_name, reads)
54
+ VALUES (?, ?, 1)
55
+ ON CONFLICT(table_name, index_name) DO UPDATE SET
56
+ reads = reads + 1`,c.table,c.index)},F=e=>{o(e);const a=r(e,`SELECT path, table_name, scans FROM "${N}" ORDER BY scans DESC, path ASC, table_name ASC LIMIT ${String(_)}`).toArray(),s=new Map;for(const t of a){const n=s.get(t.path),T={scans:t.scans,table:t.table_name};n===void 0?s.set(t.path,[T]):n.push(T)}return s},D=e=>(o(e),r(e,`SELECT table_name, index_name, reads FROM "${L}" ORDER BY table_name ASC, index_name ASC LIMIT ${String(_)}`).toArray().map(a=>({index:a.index_name,reads:a.reads,table:a.table_name}))),x=(e,a)=>{for(const s of a){const t=e.find(n=>n.table===s);t===void 0?e.push({scans:1,table:s}):t.scans+=1}return e.sort((s,t)=>t.scans-s.scans||s.table.localeCompare(t.table)),e},f=e=>{o(e);const a=F(e);return r(e,`SELECT * FROM "${E}" ORDER BY last_called_at DESC LIMIT ${String(_)}`).toArray().map(s=>({calls:s.calls,conflicts:s.conflicts,errors:s.errors,lastCalledAt:s.last_called_at,lastErrorAt:s.last_error_at,lastErrorMessage:s.last_error_message,maxDurationMs:s.max_duration_ms,path:s.path,scannedTables:a.get(s.path)??[],scans:s.scans,totalDurationMs:s.total_duration_ms}))},g=(e,a)=>{o(e);const s=a===void 0?r(e,`SELECT path, bucket_ms, calls, errors FROM "${l}" ORDER BY bucket_ms DESC, path ASC LIMIT ${String(_+1)}`).toArray():r(e,`SELECT path, bucket_ms, calls, errors FROM "${l}" WHERE path = ? ORDER BY bucket_ms DESC LIMIT ${String(_+1)}`,a).toArray(),t=s.length>_;return{buckets:(t?s.slice(0,_):s).toReversed().map(n=>({bucketMs:n.bucket_ms,calls:n.calls,errors:n.errors,path:n.path})),truncated:t}},B=e=>{o(e);const a=r(e,`SELECT SUM(calls) AS requests, SUM(errors) AS errors FROM "${E}"`).one();return{capped:r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=m,errors:a.errors??0,requests:a.requests??0}};export{l as FUNCTION_METRICS_BUCKETS_TABLE,d as FUNCTION_METRICS_BUCKET_MS,O as FUNCTION_METRICS_BUCKET_RETENTION,L as FUNCTION_METRICS_INDEX_TABLE,m as FUNCTION_METRICS_MAX_PATHS,_ as FUNCTION_METRICS_READ_LIMIT,N as FUNCTION_METRICS_SCANS_TABLE,E as FUNCTION_METRICS_TABLE,o as ensureFunctionMetricsTables,x as mergeScanAttribution,g as readFunctionMetricBuckets,D as readFunctionMetricIndexHits,F as readFunctionMetricScans,f as readFunctionMetrics,B as readFunctionMetricsTotals,h as recordFunctionMetric};
@@ -0,0 +1,15 @@
1
+ import{e as i}from"./run-sql-BP8BI9zV.mjs";const S="__lunora_issue_state__",L=100,N=["ignored","open","resolved"],g=["critical","high","low","medium"],A=null,T=s=>s??A,o=s=>{i(s,`CREATE TABLE IF NOT EXISTS "${S}" (
2
+ hash TEXT PRIMARY KEY,
3
+ status TEXT NOT NULL DEFAULT 'open',
4
+ assignee TEXT,
5
+ severity TEXT,
6
+ updated_at REAL NOT NULL,
7
+ updated_by TEXT
8
+ )`)},y=s=>({...s.assignee===null?{}:{assignee:s.assignee},hash:s.hash,...s.severity===null?{}:{severity:s.severity},status:s.status,updatedAt:s.updated_at,...s.updated_by===null?{}:{updatedBy:s.updated_by}}),C=(s,t,a={})=>{const u=a.hashQueryBatch??L,E=new Map;if(t.length===0)return E;o(s);for(let e=0;e<t.length;e+=u){const d=t.slice(e,e+u),h=d.map(()=>"?").join(", "),n=i(s,`SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${S}" WHERE hash IN (${h})`,...d).toArray();for(const r of n)E.set(r.hash,y(r))}return E},I=(s,t,a,u,E)=>{o(s);const e=T(a.status),d=T(a.assignee),h=a.assignee===null?1:0,n=T(a.severity),r=a.severity===null?1:0,p=T(E);i(s,`INSERT INTO "${S}" (hash, status, assignee, severity, updated_at, updated_by)
9
+ VALUES (?, COALESCE(?, 'open'), ?, ?, ?, ?)
10
+ ON CONFLICT(hash) DO UPDATE SET
11
+ status = COALESCE(?, status),
12
+ assignee = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, assignee) END,
13
+ severity = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, severity) END,
14
+ updated_at = ?,
15
+ updated_by = ?`,t,e,d,n,u,p,e,h,d,r,n,u,p);const[_]=i(s,`SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${S}" WHERE hash = ?`,t).toArray();return _===void 0?{hash:t,status:e??"open",updatedAt:u,...E===void 0?{}:{updatedBy:E}}:y(_)};export{L as DEFAULT_HASH_QUERY_BATCH,g as ISSUE_SEVERITIES,S as ISSUE_STATE_TABLE,N as ISSUE_STATUSES,o as ensureIssueStateTable,C as readIssueStates,I as upsertIssueState};
@@ -0,0 +1 @@
1
+ import"@lunora/fingerprint";import"@visulima/redact";import{E,d as g,v as L,K as p,w as m,h as R,F as d,X as i,C as n,c as u,I as T}from"./request-log-CHl9HlyL.mjs";import"./ISSUE_SEVERITIES-E91cPcjt.mjs";import"./run-sql-BP8BI9zV.mjs";export{E as REQUEST_LOG_RETENTION,g as REQUEST_LOG_TABLE,L as appendRequestLogEntry,p as emitLogEvent,m as emitRequestLogEvent,R as ensureRequestLogTable,d as parseLogArgs,i as readErrorIssues,n as readRequestLog,u as redactArgs,T as renderLogMessage};
@@ -1 +1 @@
1
- import{O as h,t as m}from"./trace-context-DrdF960P.mjs";import{c as b}from"./request-log-BwFic6VV.mjs";const M=100,w=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"]),k=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),O=(t,r)=>{if(!k.has(t))return;const e=r[0];return typeof e=="string"&&e.length>0?e:void 0},T=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),I=t=>{const{deps:r,durationMs:e,failure:n,operation:s,startTs:a,table:o}=t;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:e,...n===void 0?{}:{error:{message:b(T(n),r.captureRaw),type:m(n)}},functionPath:r.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:n===void 0,parentSpanId:r.anchor.rootSpanId,shardKey:r.shardKey,spanId:h(8),startTs:a,traceId:r.anchor.traceId,userId:r.userId()}},S=(t,r)=>{if(r.mode==="off")return t;const{tally:e}=r,n=new Map;return new Proxy(t,{get(s,a,o){const d=Reflect.get(s,a,o);if(typeof a!="string"||typeof d!="function"||!w.has(a))return d;const p=n.get(a);if(p!==void 0)return p;const y=d,u=async(...f)=>{const l=Date.now(),g=O(a,f);let c;try{return await y.apply(s,f)}catch(i){throw c=i,i}finally{const i=Date.now()-l;e.calls+=1,e.durationMs+=i,e.perOperation[a]=(e.perOperation[a]??0)+1,c!==void 0&&(e.errors+=1);try{r.mode==="spans"&&(e.spansEmitted>=M?e.spansTruncated=!0:(e.spansEmitted+=1,r.record(I({deps:r,durationMs:i,failure:c,operation:a,startTs:l,table:g}))))}catch{}}};return n.set(a,u),u}})},E=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),B=t=>{const r={"db.calls":t.calls,"db.duration_ms":t.durationMs};t.errors>0&&(r["db.errors"]=t.errors),t.spansTruncated&&(r["db.spans_truncated"]=!0);for(const[e,n]of Object.entries(t.perOperation))r[`db.op.${e}`]=n;return r};export{E as createDatabaseTally,B as formatTally,S as instrumentDatabase};
1
+ import{O as h,t as m}from"./trace-context-DrdF960P.mjs";import{c as b}from"./request-log-CHl9HlyL.mjs";const M=100,w=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"]),k=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),O=(t,r)=>{if(!k.has(t))return;const e=r[0];return typeof e=="string"&&e.length>0?e:void 0},T=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),I=t=>{const{deps:r,durationMs:e,failure:n,operation:s,startTs:a,table:o}=t;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:e,...n===void 0?{}:{error:{message:b(T(n),r.captureRaw),type:m(n)}},functionPath:r.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:n===void 0,parentSpanId:r.anchor.rootSpanId,shardKey:r.shardKey,spanId:h(8),startTs:a,traceId:r.anchor.traceId,userId:r.userId()}},S=(t,r)=>{if(r.mode==="off")return t;const{tally:e}=r,n=new Map;return new Proxy(t,{get(s,a,o){const d=Reflect.get(s,a,o);if(typeof a!="string"||typeof d!="function"||!w.has(a))return d;const p=n.get(a);if(p!==void 0)return p;const y=d,u=async(...f)=>{const l=Date.now(),g=O(a,f);let c;try{return await y.apply(s,f)}catch(i){throw c=i,i}finally{const i=Date.now()-l;e.calls+=1,e.durationMs+=i,e.perOperation[a]=(e.perOperation[a]??0)+1,c!==void 0&&(e.errors+=1);try{r.mode==="spans"&&(e.spansEmitted>=M?e.spansTruncated=!0:(e.spansEmitted+=1,r.record(I({deps:r,durationMs:i,failure:c,operation:a,startTs:l,table:g}))))}catch{}}};return n.set(a,u),u}})},E=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),B=t=>{const r={"db.calls":t.calls,"db.duration_ms":t.durationMs};t.errors>0&&(r["db.errors"]=t.errors),t.spansTruncated&&(r["db.spans_truncated"]=!0);for(const[e,n]of Object.entries(t.perOperation))r[`db.op.${e}`]=n;return r};export{E as createDatabaseTally,B as formatTally,S as instrumentDatabase};
@@ -1 +1 @@
1
- import{c as K,n as g}from"./request-log-BwFic6VV.mjs";import{w as b,O as M,m as R,t as T}from"./trace-context-DrdF960P.mjs";const x=/[\w.-]/u,D=t=>{let e="";for(const r of t)e+=x.test(r)?r:"_";return e},L=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=D(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},_=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},F=128,H=128,U=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},q=t=>{try{return new URL(t).host}catch{return t}},C=(t,e)=>{try{return t(new URL(e))}catch{return!1}},N=t=>t===void 0?{}:_(t)?t:{attributes:t},z=(t,e)=>{if(t.isTraced){t.setAttribute(b.functionPath,e.functionPath),t.setAttribute(b.ok,e.ok),t.setAttribute(b.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(b.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(b.userId,e.userId),e.error!==void 0&&(t.setAttribute(b.errorType,e.error.type),t.setAttribute(b.errorMessage,e.error.message));for(const[r,s]of Object.entries(e.attributes))(typeof s=="boolean"||typeof s=="number"||typeof s=="string")&&t.setAttribute(`lunora.attr.${r}`,s)}},B=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},s={spanContext:()=>t,addEvent:(n,a)=>{if(r.events.length>=F)return;const o=g(a);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=H)return;const a=g(n.attributes);r.links.push({...a===void 0?{}:{attributes:a},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(r.attributes,g(L(n)))},recordException:n=>{const a=n instanceof Error?n.message:String(n);s.addEvent("exception",{"exception.message":K(a,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":T(n)})},setAttribute:(n,a)=>{Object.assign(r.attributes,g({[n]:a}))},setAttributes:n=>{Object.assign(r.attributes,g(n))}};return{collected:r,handle:s}},Q=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:s,functionPath:n,record:a,resolveHostTracing:o,shardKey:i,userId:h}=t,u=p=>async(m,d,f)=>{const y=M(8),c=Date.now(),I=N(f),j=g(I.attributes),{collected:w,handle:O}=B({spanId:y,traceId:e.traceId},r),P=async v=>{let k=!0,S;try{return await d(u(y),O)}catch(l){k=!1;const E=l instanceof Error?l.message:String(l);throw S={message:K(E,r),type:T(l)},l}finally{const l=Date.now()-c,E=h(),A={...j,...w.attributes},$=[...I.links??[],...w.links];try{a({...Object.keys(A).length===0?{}:{attributes:A},durationMs:l,...w.events.length===0?{}:{events:w.events},...S===void 0?{}:{error:S},functionPath:n,...I.kind===void 0||I.kind==="internal"?{}:{kind:I.kind},...$.length===0?{}:{links:$},name:m,ok:k,parentSpanId:p,shardKey:i,spanId:y,startTs:c,traceId:e.traceId,userId:E})}catch{}if(v!==void 0)try{z(v,{attributes:A,durationMs:l,error:S,functionPath:n,ok:k,shardKey:i,userId:E})}catch{}}};if(s===!0&&o!==void 0){const v=await o();if(v!==void 0&&typeof v.enterSpan=="function")return await v.enterSpan(m,k=>P(k))}return await P()};return u(e.rootSpanId)},V=(t,e)=>{const{anchor:r,functionPath:s,propagate:n=!0,record:a,shardKey:o,userId:i}=t;return async(h,u)=>{const p=M(8),m=Date.now(),d=new Request(h,u);(typeof n=="function"?C(n,d.url):n)&&d.headers.set("traceparent",R(r.traceId,p,r.sampled??!0));let f,y;try{const c=await e(d);return y=c.status,c.ok||(f={message:`HTTP ${String(c.status)}`,type:`HTTP_${String(c.status)}`}),c}catch(c){throw f={message:c instanceof Error?c.message:String(c),type:T(c)},c}finally{try{a({attributes:{"http.request.method":d.method,...y===void 0?{}:{"http.response.status_code":y},"url.full":U(d.url)},durationMs:Date.now()-m,...f===void 0?{}:{error:f},functionPath:s,kind:"client",name:`${d.method} ${q(d.url)}`,ok:f===void 0,parentSpanId:r.rootSpanId,shardKey:o,spanId:p,startTs:m,traceId:r.traceId,userId:i()})}catch{}}}},W=t=>{const{functionPath:e,record:r,shardKey:s}=t,n=(a,o,i,h)=>{if(!Number.isFinite(i))return;const u=g(h);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:a,name:o,shardKey:s,ts:Date.now(),value:i})}catch{}};return{count:(a,o=1,i)=>{n("counter",a,o,i)},gauge:(a,o,i)=>{n("gauge",a,o,i)},record:(a,o,i)=>{n("histogram",a,o,i)}}},X=t=>{const{anchor:e,captureRaw:r=!1,collected:s,durationMs:n,failure:a,functionPath:o,shardKey:i,startTs:h,userId:u}=t,p=s?.attributes??{};return{...Object.keys(p).length===0?{}:{attributes:p},dispatch:!0,durationMs:n,...s===void 0||s.events.length===0?{}:{events:s.events},...a===void 0?{}:{error:{message:K(a.thrown instanceof Error?a.thrown.message:String(a.thrown),r),type:T(a.thrown)}},functionPath:o,...s===void 0||s.links.length===0?{}:{links:s.links},name:o,ok:a===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:h,traceId:e.traceId,userId:u}};export{z as applyHostSpanAttributes,W as createMetrics,B as createSpanCollector,V as createTracedFetch,Q as createTracer,X as dispatchRootSpan};
1
+ import{c as K,n as g}from"./request-log-CHl9HlyL.mjs";import{w as b,O as M,m as R,t as T}from"./trace-context-DrdF960P.mjs";const x=/[\w.-]/u,D=t=>{let e="";for(const r of t)e+=x.test(r)?r:"_";return e},L=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=D(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},_=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},F=128,H=128,U=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},q=t=>{try{return new URL(t).host}catch{return t}},C=(t,e)=>{try{return t(new URL(e))}catch{return!1}},N=t=>t===void 0?{}:_(t)?t:{attributes:t},z=(t,e)=>{if(t.isTraced){t.setAttribute(b.functionPath,e.functionPath),t.setAttribute(b.ok,e.ok),t.setAttribute(b.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(b.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(b.userId,e.userId),e.error!==void 0&&(t.setAttribute(b.errorType,e.error.type),t.setAttribute(b.errorMessage,e.error.message));for(const[r,s]of Object.entries(e.attributes))(typeof s=="boolean"||typeof s=="number"||typeof s=="string")&&t.setAttribute(`lunora.attr.${r}`,s)}},B=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},s={spanContext:()=>t,addEvent:(n,a)=>{if(r.events.length>=F)return;const o=g(a);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=H)return;const a=g(n.attributes);r.links.push({...a===void 0?{}:{attributes:a},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(r.attributes,g(L(n)))},recordException:n=>{const a=n instanceof Error?n.message:String(n);s.addEvent("exception",{"exception.message":K(a,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":T(n)})},setAttribute:(n,a)=>{Object.assign(r.attributes,g({[n]:a}))},setAttributes:n=>{Object.assign(r.attributes,g(n))}};return{collected:r,handle:s}},Q=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:s,functionPath:n,record:a,resolveHostTracing:o,shardKey:i,userId:h}=t,u=p=>async(m,d,f)=>{const y=M(8),c=Date.now(),I=N(f),j=g(I.attributes),{collected:w,handle:O}=B({spanId:y,traceId:e.traceId},r),P=async v=>{let k=!0,S;try{return await d(u(y),O)}catch(l){k=!1;const E=l instanceof Error?l.message:String(l);throw S={message:K(E,r),type:T(l)},l}finally{const l=Date.now()-c,E=h(),A={...j,...w.attributes},$=[...I.links??[],...w.links];try{a({...Object.keys(A).length===0?{}:{attributes:A},durationMs:l,...w.events.length===0?{}:{events:w.events},...S===void 0?{}:{error:S},functionPath:n,...I.kind===void 0||I.kind==="internal"?{}:{kind:I.kind},...$.length===0?{}:{links:$},name:m,ok:k,parentSpanId:p,shardKey:i,spanId:y,startTs:c,traceId:e.traceId,userId:E})}catch{}if(v!==void 0)try{z(v,{attributes:A,durationMs:l,error:S,functionPath:n,ok:k,shardKey:i,userId:E})}catch{}}};if(s===!0&&o!==void 0){const v=await o();if(v!==void 0&&typeof v.enterSpan=="function")return await v.enterSpan(m,k=>P(k))}return await P()};return u(e.rootSpanId)},V=(t,e)=>{const{anchor:r,functionPath:s,propagate:n=!0,record:a,shardKey:o,userId:i}=t;return async(h,u)=>{const p=M(8),m=Date.now(),d=new Request(h,u);(typeof n=="function"?C(n,d.url):n)&&d.headers.set("traceparent",R(r.traceId,p,r.sampled??!0));let f,y;try{const c=await e(d);return y=c.status,c.ok||(f={message:`HTTP ${String(c.status)}`,type:`HTTP_${String(c.status)}`}),c}catch(c){throw f={message:c instanceof Error?c.message:String(c),type:T(c)},c}finally{try{a({attributes:{"http.request.method":d.method,...y===void 0?{}:{"http.response.status_code":y},"url.full":U(d.url)},durationMs:Date.now()-m,...f===void 0?{}:{error:f},functionPath:s,kind:"client",name:`${d.method} ${q(d.url)}`,ok:f===void 0,parentSpanId:r.rootSpanId,shardKey:o,spanId:p,startTs:m,traceId:r.traceId,userId:i()})}catch{}}}},W=t=>{const{functionPath:e,record:r,shardKey:s}=t,n=(a,o,i,h)=>{if(!Number.isFinite(i))return;const u=g(h);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:a,name:o,shardKey:s,ts:Date.now(),value:i})}catch{}};return{count:(a,o=1,i)=>{n("counter",a,o,i)},gauge:(a,o,i)=>{n("gauge",a,o,i)},record:(a,o,i)=>{n("histogram",a,o,i)}}},X=t=>{const{anchor:e,captureRaw:r=!1,collected:s,durationMs:n,failure:a,functionPath:o,shardKey:i,startTs:h,userId:u}=t,p=s?.attributes??{};return{...Object.keys(p).length===0?{}:{attributes:p},dispatch:!0,durationMs:n,...s===void 0||s.events.length===0?{}:{events:s.events},...a===void 0?{}:{error:{message:K(a.thrown instanceof Error?a.thrown.message:String(a.thrown),r),type:T(a.thrown)}},functionPath:o,...s===void 0||s.links.length===0?{}:{links:s.links},name:o,ok:a===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:h,traceId:e.traceId,userId:u}};export{z as applyHostSpanAttributes,W as createMetrics,B as createSpanCollector,V as createTracedFetch,Q as createTracer,X as dispatchRootSpan};
@@ -1,4 +1,4 @@
1
- import{m as O,e as S}from"./metric-buffer-CdgXal7w.mjs";const a="__lunora_metric_history",o=6e4,x=1440,d=1e3,l=5e3,n=(e,s,...T)=>e.exec.call(e,s,...T),y=e=>Math.floor(e/o)*o,_=new WeakSet,k=e=>{_.has(e)||(n(e,`CREATE TABLE IF NOT EXISTS "${a}" (
1
+ import{m as O,e as S}from"./metric-buffer-CdgXal7w.mjs";import{e as n}from"./run-sql-BP8BI9zV.mjs";const a="__lunora_metric_history",L=6e4,R=1440,d=1e3,l=5e3,y=e=>Math.floor(e/L)*L,_=new WeakSet,k=e=>{_.has(e)||(n(e,`CREATE TABLE IF NOT EXISTS "${a}" (
2
2
  series_key TEXT NOT NULL,
3
3
  bucket_ms INTEGER NOT NULL,
4
4
  name TEXT NOT NULL,
@@ -14,7 +14,7 @@ import{m as O,e as S}from"./metric-buffer-CdgXal7w.mjs";const a="__lunora_metric
14
14
  last_ts REAL NOT NULL DEFAULT 0,
15
15
  exemplar_trace TEXT,
16
16
  PRIMARY KEY (series_key, bucket_ms)
17
- )`),_.add(e))},R=4096,N=new WeakMap,M=e=>{let s=N.get(e);return s===void 0&&(s=new Set,N.set(e,s)),s},p=(e,s)=>n(e,`SELECT COUNT(DISTINCT series_key) AS n FROM "${a}"`).one().n<s,h=(e,s,T,i={})=>{const c=i.maxSeries??d,t=i.retentionBuckets??x;k(e);const r=O(s),E=y(s.ts),u=M(e),L=`${r}\0${E.toString()}`,m=u.has(L)||n(e,`SELECT 1 AS c FROM "${a}" WHERE series_key = ? AND bucket_ms = ? LIMIT 1`,r,E).toArray().length>0;if(!m&&!(n(e,`SELECT 1 AS c FROM "${a}" WHERE series_key = ? LIMIT 1`,r).toArray().length>0)&&!p(e,c))return;const A=T??null;n(e,`INSERT INTO "${a}"
17
+ )`),_.add(e))},x=4096,N=new WeakMap,M=e=>{let s=N.get(e);return s===void 0&&(s=new Set,N.set(e,s)),s},p=(e,s)=>n(e,`SELECT COUNT(DISTINCT series_key) AS n FROM "${a}"`).one().n<s,D=(e,s,u,i={})=>{const T=i.maxSeries??d,t=i.retentionBuckets??R;k(e);const r=O(s),E=y(s.ts),c=M(e),o=`${r}\0${E.toString()}`,m=c.has(o)||n(e,`SELECT 1 AS c FROM "${a}" WHERE series_key = ? AND bucket_ms = ? LIMIT 1`,r,E).toArray().length>0;if(!m&&!(n(e,`SELECT 1 AS c FROM "${a}" WHERE series_key = ? LIMIT 1`,r).toArray().length>0)&&!p(e,T))return;const A=u??null;n(e,`INSERT INTO "${a}"
18
18
  (series_key, bucket_ms, name, kind, attrs, function_path, shard_key, count, sum, min, max, last, last_ts, exemplar_trace)
19
19
  VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)
20
20
  ON CONFLICT(series_key, bucket_ms) DO UPDATE SET
@@ -28,4 +28,4 @@ import{m as O,e as S}from"./metric-buffer-CdgXal7w.mjs";const a="__lunora_metric
28
28
  WHERE series_key = ?
29
29
  AND bucket_ms <= (
30
30
  SELECT MAX(bucket_ms) - ? FROM "${a}" WHERE series_key = ?
31
- )`,r,t*o,r),m&&!u.has(L)&&(u.size>=R&&u.clear(),u.add(L))},U=e=>{if(!(e===""||e==="{}"))try{const s=JSON.parse(e);return s!==null&&typeof s=="object"?s:void 0}catch{return}},D=(e,s={})=>{k(e);const T=s.maxSeries??d,i=s.sinceMs===void 0?n(e,`SELECT * FROM "${a}" ORDER BY bucket_ms DESC LIMIT ?`,l).toArray():n(e,`SELECT * FROM "${a}" WHERE bucket_ms >= ? ORDER BY bucket_ms DESC LIMIT ?`,s.sinceMs,l).toArray(),c=new Map;for(const t of i){let r=c.get(t.series_key);if(r===void 0){const E=U(t.attrs);r={...E===void 0?{}:{attributes:E},functionPath:t.function_path,kind:t.kind,name:t.name,points:[],...t.shard_key===null?{}:{shardKey:t.shard_key}},c.set(t.series_key,r)}r.points.push({bucketMs:t.bucket_ms,count:t.count,...t.exemplar_trace===null?{}:{exemplarTraceId:t.exemplar_trace},last:t.last,max:t.max,min:t.min,sum:t.sum})}for(const t of c.values())t.points.sort((r,E)=>r.bucketMs-E.bucketMs);return{capped:n(e,`SELECT COUNT(DISTINCT series_key) AS n FROM "${a}"`).one().n>=T,series:[...c.values()]}};export{D as readMetricHistory,h as recordMetricHistory};
31
+ )`,r,t*L,r),m&&!c.has(o)&&(c.size>=x&&c.clear(),c.add(o))},U=e=>{if(!(e===""||e==="{}"))try{const s=JSON.parse(e);return s!==null&&typeof s=="object"?s:void 0}catch{return}},F=(e,s={})=>{k(e);const u=s.maxSeries??d,i=s.sinceMs===void 0?n(e,`SELECT * FROM "${a}" ORDER BY bucket_ms DESC LIMIT ?`,l).toArray():n(e,`SELECT * FROM "${a}" WHERE bucket_ms >= ? ORDER BY bucket_ms DESC LIMIT ?`,s.sinceMs,l).toArray(),T=new Map;for(const t of i){let r=T.get(t.series_key);if(r===void 0){const E=U(t.attrs);r={...E===void 0?{}:{attributes:E},functionPath:t.function_path,kind:t.kind,name:t.name,points:[],...t.shard_key===null?{}:{shardKey:t.shard_key}},T.set(t.series_key,r)}r.points.push({bucketMs:t.bucket_ms,count:t.count,...t.exemplar_trace===null?{}:{exemplarTraceId:t.exemplar_trace},last:t.last,max:t.max,min:t.min,sum:t.sum})}for(const t of T.values())t.points.sort((r,E)=>r.bucketMs-E.bucketMs);return{capped:n(e,`SELECT COUNT(DISTINCT series_key) AS n FROM "${a}"`).one().n>=u,series:[...T.values()]}};export{F as readMetricHistory,D as recordMetricHistory};
@@ -0,0 +1,32 @@
1
+ import{e as a}from"./run-sql-BP8BI9zV.mjs";const i="__lunora_metrics_queries",m="__lunora_metrics_queries_buckets",N=6e4,k=90,E=[1,2,5,10,25,50,100,250,500,1e3,5e3],U=512,C=500,q=e=>{let t=e.replaceAll(/'(?:[^']|'')*'/g,"?").replaceAll(/\b0x[\da-f]+\b/gi,"?").replaceAll(/(?<=[=,([\s])\d+(?:\.\d+)?/g,"?").replaceAll(/\s+/g," ").trim();return t.length>U&&(t=`${t.slice(0,U-1)}…`),t},M=new WeakSet,A=e=>{M.has(e)||(a(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ normalized_sql TEXT PRIMARY KEY,
3
+ exec_count INTEGER NOT NULL DEFAULT 0,
4
+ total_duration_ms REAL NOT NULL DEFAULT 0,
5
+ rows_read INTEGER NOT NULL DEFAULT 0,
6
+ rows_written INTEGER NOT NULL DEFAULT 0
7
+ )`),M.add(e))},h=new WeakMap,w=e=>Math.floor(e/N)*N,D=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.codePointAt(r)??0,t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},F=e=>{const t=E.findIndex(r=>e<=r);return t===-1?E.length:t},T=e=>`lat_${String(e)}`,x=new WeakSet,b=e=>{if(x.has(e))return;const t=Array.from({length:E.length+1},(r,n)=>`${T(n)} INTEGER NOT NULL DEFAULT 0`).join(", ");a(e,`CREATE TABLE IF NOT EXISTS "${m}" (
8
+ sql_hash TEXT NOT NULL,
9
+ bucket_ms INTEGER NOT NULL,
10
+ exec_count INTEGER NOT NULL DEFAULT 0,
11
+ total_duration_ms REAL NOT NULL DEFAULT 0,
12
+ rows_read INTEGER NOT NULL DEFAULT 0,
13
+ rows_written INTEGER NOT NULL DEFAULT 0,
14
+ ${t},
15
+ PRIMARY KEY (sql_hash, bucket_ms)
16
+ )`),x.add(e)},p=(e,t)=>{a(e,`DELETE FROM "${m}" WHERE bucket_ms < ?`,w(t)-k*N)},$=(e,t,r,n,u,_,s=1)=>{try{b(e);const c=s>0?r/s:r,l=T(F(c)),S=`INSERT INTO "${m}" (sql_hash, bucket_ms, exec_count, total_duration_ms, rows_read, rows_written, ${l})
17
+ VALUES (?, ?, ?, ?, ?, ?, ?)
18
+ ON CONFLICT(sql_hash, bucket_ms) DO UPDATE SET
19
+ exec_count = exec_count + excluded.exec_count,
20
+ total_duration_ms = total_duration_ms + excluded.total_duration_ms,
21
+ rows_read = rows_read + excluded.rows_read,
22
+ rows_written = rows_written + excluded.rows_written,
23
+ ${l} = ${l} + excluded.${l}`;a(e,S,D(t),w(_),s,r,n,u,s);const o=w(_);h.get(e)!==o&&(h.set(e,o),p(e,_))}catch{}},O=(e,t)=>{const r=e.reduce((_,s)=>_+s,0);if(r===0)return 0;const n=r*t;let u=0;for(const[_,s]of e.entries())if(u+=s,u>=n)return E[_]??E.at(-1)??0;return E.at(-1)??0},Q=(e,t,r=Date.now())=>{try{A(e),b(e)}catch{return{buckets:[],capped:!1,entries:[],trackedStatements:0}}const n=w(r-t),u=Array.from({length:E.length+1},(o,d)=>`SUM(${T(d)}) AS ${T(d)}`).join(", "),_=a(e,`SELECT sql_hash, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms,
24
+ SUM(rows_read) AS rows_read, SUM(rows_written) AS rows_written, ${u}
25
+ FROM "${m}" WHERE bucket_ms >= ? GROUP BY sql_hash`,n).toArray(),s=new Map;for(const o of a(e,`SELECT normalized_sql FROM "${i}"`))s.set(D(o.normalized_sql),o.normalized_sql);const c=_.map(o=>{const d=Array.from({length:E.length+1},(B,g)=>Number(o[T(g)]??0)),L=Number(o.exec_count??0),R=Number(o.total_duration_ms??0);return{avgDurationMs:L>0?R/L:0,execCount:L,normalizedSql:s.get(String(o.sql_hash))??String(o.sql_hash),p50DurationMs:O(d,.5),p95DurationMs:O(d,.95),rowsRead:Number(o.rows_read??0),rowsWritten:Number(o.rows_written??0),totalDurationMs:R}});c.sort((o,d)=>d.totalDurationMs-o.totalDurationMs);const l=a(e,`SELECT bucket_ms, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms
26
+ FROM "${m}" WHERE bucket_ms >= ? GROUP BY bucket_ms ORDER BY bucket_ms ASC`,n).toArray().map(o=>({avgDurationMs:o.exec_count>0?o.total_duration_ms/o.exec_count:0,bucketMs:o.bucket_ms,execCount:o.exec_count})),S=a(e,`SELECT COUNT(*) AS n FROM "${i}"`).one().n;return{buckets:l,capped:S>=C,entries:c,trackedStatements:S}},I=new WeakMap,f=e=>{let t=I.get(e);return t===void 0&&(t=new Set,I.set(e,t)),t},y=(e,t)=>{const r=f(e);return r.has(t)?!0:a(e,`SELECT 1 AS c FROM "${i}" WHERE normalized_sql = ? LIMIT 1`,t).toArray().length>0?(r.add(t),!0):a(e,`SELECT COUNT(*) AS n FROM "${i}"`).one().n>=C?!1:(r.add(t),!0)},z=(e,t,r,n,u,_=Date.now(),s=1)=>{const c=q(t);if(c.length===0||(A(e),!y(e,c)))return;const l=`INSERT INTO "${i}" (normalized_sql, exec_count, total_duration_ms, rows_read, rows_written)
27
+ VALUES (?, ?, ?, ?, ?)
28
+ ON CONFLICT(normalized_sql) DO UPDATE SET
29
+ exec_count = exec_count + excluded.exec_count,
30
+ total_duration_ms = total_duration_ms + excluded.total_duration_ms,
31
+ rows_read = rows_read + excluded.rows_read,
32
+ rows_written = rows_written + excluded.rows_written`;a(e,l,c,s,r,n,u),$(e,c,r,n,u,_,s)},G=e=>(A(e),a(e,`SELECT normalized_sql, exec_count, total_duration_ms, rows_read, rows_written FROM "${i}" ORDER BY total_duration_ms DESC`).toArray().map(t=>({execCount:t.exec_count,normalizedSql:t.normalized_sql,rowsRead:t.rows_read,rowsWritten:t.rows_written,totalDurationMs:t.total_duration_ms})));export{E as LATENCY_BUCKET_EDGES,m as QUERY_BUCKETS_TABLE,N as QUERY_BUCKET_MS,k as QUERY_BUCKET_RETENTION,U as QUERY_METRICS_MAX_SQL_LEN,C as QUERY_METRICS_MAX_STATEMENTS,i as QUERY_METRICS_TABLE,b as ensureQueryBucketsTable,A as ensureQueryMetricsTable,D as hashStatement,F as latencyBucketIndex,q as normalizeSql,O as percentileFrom,p as pruneQueryBuckets,Q as readQueryInsights,G as readQueryMetrics,$ as recordQueryBucket,z as recordQueryMetric};
@@ -0,0 +1,21 @@
1
+ import{fingerprintError as N}from"@lunora/fingerprint";import{redact as I,standardRules as M}from"@visulima/redact";import{readIssueStates as P}from"./ISSUE_SEVERITIES-E91cPcjt.mjs";import{e as f}from"./run-sql-BP8BI9zV.mjs";const w=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},m=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:w(e),T=(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]=m(r);if(e!==void 0)for(const[i,r]of Object.entries(e))s[i]=m(r);return Object.keys(s).length===0?void 0:s},d="__lunora_reqlog__",p=1e3,b="lunora",c=(e,t=!1)=>t||e===null||e===void 0?e:I(e,M),E=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
+ duration_ms REAL NOT NULL,
13
+ tables_read TEXT NOT NULL DEFAULT '[]',
14
+ tables_written TEXT NOT NULL DEFAULT '[]',
15
+ cache_hit INTEGER,
16
+ subscriptions_rerun INTEGER NOT NULL DEFAULT 0
17
+ )`);try{f(e,`ALTER TABLE "${d}" ADD COLUMN error_fingerprint TEXT`)}catch{}},S=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),U=e=>e===void 0?null:e?1:0,k=(e,t,s={})=>{E(e);const i=s.captureRaw??!1,r=s.retention??p,o=t.outcome==="error"&&t.errorMessage!==void 0?N({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;f(e,`INSERT INTO "${d}"
18
+ (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(c(t.identity,i)),t.redactedArgs===void 0?null:JSON.stringify(c(t.redactedArgs,i)),t.outcome,t.errorMessage===void 0?null:c(t.errorMessage,i),o??null,t.durationMs,S(t.tablesRead),S(t.tablesWritten),U(t.cacheHit),t.subscriptionsReRun??0),f(e,`DELETE FROM "${d}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${d}")`,r)},x=(e,t={})=>{const s=t.captureRaw??!1,i={args:e.redactedArgs===void 0?void 0:c(e.redactedArgs,s),cacheHit:e.cacheHit,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:c(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:c(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:b,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],ts:e.ts,type:"request",userId:e.userId},r=JSON.stringify(i);e.outcome==="error"?console.error(r):console.log(r)},X="log",q=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),C=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"&&C(e[1])?{fields:T(e[1],t),message:e[0]}:{fields:T(void 0,t),message:q(e)},H=(e,t={})=>{const s=t.captureRaw??!1,i={fields:e.fields===void 0?void 0:c(e.fields,s),function:e.functionPath,level:e.level,message:e.message,shard:e.shardKey,source:b,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)},O=e=>e.replaceAll(/[\\%_]/g,t=>`\\${t}`),A=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(String.raw`function_path LIKE ? ESCAPE '\'`),t.push(`${O(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))},v=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},$=(e,t={})=>{E(e);const s=Math.max(1,Math.min(t.limit??p,1e4)),i=["seq > ?"],r=[t.sinceSeq??0];if(A(i,r,t),t.outcome!==void 0&&(i.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=`%${O(JSON.stringify(t.tableTouched))}%`;i.push(String.raw`(tables_read LIKE ? ESCAPE '\' OR tables_written LIKE ? ESCAPE '\')`),r.push(o,o)}return r.push(s),f(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
20
+ FROM "${d}" 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:v(o.tables_read),tablesWritten:v(o.tables_written),ts:o.ts};return o.shard_key!==null&&(n.shardKey=o.shard_key),o.user_id!==null&&(n.userId=o.user_id),o.identity!==null&&(n.identity=JSON.parse(o.identity)),o.args!==null&&(n.redactedArgs=JSON.parse(o.args)),o.error_message!==null&&(n.errorMessage=o.error_message),o.cache_hit!==null&&(n.cacheHit=o.cache_hit===1),n})},F=(e,t)=>{const s=P(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)}},Y=(e,t={})=>{E(e);const s=Math.max(1,Math.min(t.limit??p,1e4)),i=["outcome = 'error'"],r=[];A(i,r,t),r.push(s);const o=f(e,`SELECT function_path, error_message, error_fingerprint, ts
21
+ FROM "${d}" WHERE ${i.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),n=new Map,g=new Map;for(const a of o){const h=a.error_message??"",{culprit:L,hash:R,title:_}=N({functionPath:a.function_path,message:h}),l=a.error_fingerprint??R,u=n.get(l);if(u===void 0){n.set(l,{count:1,culprit:L,firstSeen:a.ts,hash:l,lastSeen:a.ts,sampleMessage:h,status:"open",title:_}),g.set(l,a.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,a.ts),u.lastSeen=Math.max(u.lastSeen,a.ts),a.ts>(g.get(l)??Number.NEGATIVE_INFINITY)&&(g.set(l,a.ts),u.sampleMessage=h,u.title=_)}F(e,n);const y=[...n.values()];return(t.status===void 0?y:y.filter(a=>a.status===t.status)).toSorted((a,h)=>h.lastSeen-a.lastSeen)};export{$ as C,p as E,W as F,q as I,H as K,Y as X,c,d,E as h,T as n,k as v,x as w};
@@ -0,0 +1 @@
1
+ const o=(e,c,...l)=>e.exec.call(e,c,...l);export{o as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.11",
3
+ "version": "1.0.0-alpha.12",
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",
@@ -43,9 +43,9 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@lunora/errors": "1.0.0-alpha.14",
46
+ "@lunora/errors": "1.0.0-alpha.15",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.6",
48
- "@lunora/shard-engine": "1.0.0-alpha.12",
48
+ "@lunora/shard-engine": "1.0.0-alpha.13",
49
49
  "@visulima/redact": "3.0.0"
50
50
  },
51
51
  "engines": {
@@ -1,22 +0,0 @@
1
- const _="__lunora_auth_metrics",T="__lunora_auth_metrics_buckets",A="app",N=6e4,R=1440,E=(s,t,...e)=>s.exec.call(s,t,...e),c=s=>Math.floor(s/6e4)*6e4,r=s=>{E(s,`CREATE TABLE IF NOT EXISTS "${_}" (
2
- key TEXT PRIMARY KEY,
3
- attempts INTEGER NOT NULL DEFAULT 0,
4
- failures INTEGER NOT NULL DEFAULT 0,
5
- since_ms INTEGER NOT NULL DEFAULT 0
6
- )`),E(s,`CREATE TABLE IF NOT EXISTS "${T}" (
7
- bucket_ms INTEGER PRIMARY KEY,
8
- attempts INTEGER NOT NULL DEFAULT 0,
9
- failures INTEGER NOT NULL DEFAULT 0
10
- )`)},l=(s,t)=>{r(s);const e=t.outcome==="fail"?1:0;E(s,`INSERT INTO "${_}" (key, attempts, failures, since_ms)
11
- VALUES (?, 1, ?, ?)
12
- ON CONFLICT(key) DO UPDATE SET
13
- attempts = attempts + 1,
14
- failures = failures + excluded.failures,
15
- since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,"app",e,t.ts);const a=c(t.ts);E(s,`INSERT INTO "${T}" (bucket_ms, attempts, failures)
16
- VALUES (?, 1, ?)
17
- ON CONFLICT(bucket_ms) DO UPDATE SET
18
- attempts = attempts + 1,
19
- failures = failures + excluded.failures`,a,e),E(s,`DELETE FROM "${T}"
20
- WHERE bucket_ms <= (
21
- SELECT MAX(bucket_ms) - ? FROM "${T}"
22
- )`,864e5)},L=s=>{r(s);const t=E(s,`SELECT attempts, failures, since_ms FROM "${_}" WHERE key = ?`,"app").toArray()[0],e=t?.attempts??0,a=t?.failures??0,m=t?.since_ms??0,i=E(s,`SELECT bucket_ms, attempts, failures FROM "${T}" ORDER BY bucket_ms ASC`).toArray().map(u=>({attempts:u.attempts,bucketMs:u.bucket_ms,failures:u.failures}));return{attempts:e,failureRate:e===0?0:a/e,failures:a,history:i,sinceMs:m}};export{T as AUTH_METRICS_BUCKETS_TABLE,N as AUTH_METRICS_BUCKET_MS,R as AUTH_METRICS_BUCKET_RETENTION,A as AUTH_METRICS_ROW_KEY,_ as AUTH_METRICS_TABLE,r as ensureAuthMetricsTables,L as readAuthMetrics,l as recordAuthEvent};
@@ -1,56 +0,0 @@
1
- const E="__lunora_metrics",l="__lunora_metrics_buckets",c="__lunora_metrics_scans",d="__lunora_metrics_index",M=6e4,U=1440,F=5e3,p=1e3,r=(e,a,...s)=>e.exec.call(e,a,...s),A=e=>Math.floor(e/6e4)*6e4,I=e=>{const a=new Map;for(const s of e)a.set(`${s.table}\0${s.index}`,{index:s.index,table:s.table});return[...a.values()]},N=new WeakSet,_=e=>{if(!N.has(e)){r(e,`CREATE TABLE IF NOT EXISTS "${E}" (
2
- path TEXT PRIMARY KEY,
3
- calls INTEGER NOT NULL DEFAULT 0,
4
- errors INTEGER NOT NULL DEFAULT 0,
5
- conflicts INTEGER NOT NULL DEFAULT 0,
6
- scans INTEGER NOT NULL DEFAULT 0,
7
- total_duration_ms REAL NOT NULL DEFAULT 0,
8
- min_duration_ms REAL,
9
- max_duration_ms REAL NOT NULL DEFAULT 0,
10
- last_called_at REAL NOT NULL DEFAULT 0,
11
- last_error_at REAL,
12
- last_error_message TEXT
13
- )`);for(const a of["scans","conflicts"])try{r(e,`ALTER TABLE "${E}" ADD COLUMN ${a} INTEGER NOT NULL DEFAULT 0`)}catch{}r(e,`CREATE TABLE IF NOT EXISTS "${l}" (
14
- path TEXT NOT NULL,
15
- bucket_ms INTEGER NOT NULL,
16
- calls INTEGER NOT NULL DEFAULT 0,
17
- errors INTEGER NOT NULL DEFAULT 0,
18
- PRIMARY KEY (path, bucket_ms)
19
- )`),r(e,`CREATE TABLE IF NOT EXISTS "${c}" (
20
- path TEXT NOT NULL,
21
- table_name TEXT NOT NULL,
22
- scans INTEGER NOT NULL DEFAULT 0,
23
- PRIMARY KEY (path, table_name)
24
- )`),r(e,`CREATE TABLE IF NOT EXISTS "${d}" (
25
- table_name TEXT NOT NULL,
26
- index_name TEXT NOT NULL,
27
- reads INTEGER NOT NULL DEFAULT 0,
28
- PRIMARY KEY (table_name, index_name)
29
- )`),N.add(e)}},L=new WeakMap,R=e=>{let a=L.get(e);return a===void 0&&(a=new Set,L.set(e,a)),a},O=(e,a)=>{const s=R(e);return s.has(a)?!0:r(e,`SELECT 1 AS c FROM "${E}" WHERE path = ? LIMIT 1`,a).toArray().length>0?(s.add(a),!0):r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=5e3?!1:(s.add(a),!0)},b=(e,a)=>{if(_(e),!O(e,a.path))return;const s=a.scannedTables?[...new Set(a.scannedTables)]:[],t=s.length,n=I(a.indexHits??[]),T=a.errored?1:0,i=a.conflicted?1:0,u=a.errored?a.ts:null,m=a.errored?a.errorMessage??null:null;r(e,`INSERT INTO "${E}"
30
- (path, calls, errors, conflicts, scans, total_duration_ms, min_duration_ms, max_duration_ms, last_called_at, last_error_at, last_error_message)
31
- VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)
32
- ON CONFLICT(path) DO UPDATE SET
33
- calls = calls + 1,
34
- errors = errors + excluded.errors,
35
- conflicts = conflicts + excluded.conflicts,
36
- scans = scans + excluded.scans,
37
- total_duration_ms = total_duration_ms + excluded.total_duration_ms,
38
- min_duration_ms = MIN(COALESCE(min_duration_ms, excluded.min_duration_ms), excluded.min_duration_ms),
39
- max_duration_ms = MAX(max_duration_ms, excluded.max_duration_ms),
40
- last_called_at = excluded.last_called_at,
41
- last_error_at = CASE WHEN excluded.last_error_at IS NULL THEN last_error_at ELSE excluded.last_error_at END,
42
- last_error_message = CASE WHEN excluded.last_error_at IS NULL THEN last_error_message ELSE excluded.last_error_message END`,a.path,T,i,t,a.durationMs,a.durationMs,a.durationMs,a.ts,u,m);const S=A(a.ts);r(e,`INSERT INTO "${l}" (path, bucket_ms, calls, errors)
43
- VALUES (?, ?, 1, ?)
44
- ON CONFLICT(path, bucket_ms) DO UPDATE SET
45
- calls = calls + 1,
46
- errors = errors + excluded.errors`,a.path,S,T),r(e,`DELETE FROM "${l}"
47
- WHERE path = ?
48
- AND bucket_ms <= (
49
- SELECT MAX(bucket_ms) - ? FROM "${l}" WHERE path = ?
50
- )`,a.path,1440*6e4,a.path);for(const o of s)r(e,`INSERT INTO "${c}" (path, table_name, scans)
51
- VALUES (?, ?, 1)
52
- ON CONFLICT(path, table_name) DO UPDATE SET
53
- scans = scans + 1`,a.path,o);for(const o of n)r(e,`INSERT INTO "${d}" (table_name, index_name, reads)
54
- VALUES (?, ?, 1)
55
- ON CONFLICT(table_name, index_name) DO UPDATE SET
56
- reads = reads + 1`,o.table,o.index)},C=e=>{_(e);const a=r(e,`SELECT path, table_name, scans FROM "${c}" ORDER BY scans DESC, path ASC, table_name ASC LIMIT ${String(1e3)}`).toArray(),s=new Map;for(const t of a){const n=s.get(t.path),T={scans:t.scans,table:t.table_name};n===void 0?s.set(t.path,[T]):n.push(T)}return s},h=e=>(_(e),r(e,`SELECT table_name, index_name, reads FROM "${d}" ORDER BY table_name ASC, index_name ASC LIMIT ${String(1e3)}`).toArray().map(a=>({index:a.index_name,reads:a.reads,table:a.table_name}))),D=(e,a)=>{for(const s of a){const t=e.find(n=>n.table===s);t===void 0?e.push({scans:1,table:s}):t.scans+=1}return e.sort((s,t)=>t.scans-s.scans||s.table.localeCompare(t.table)),e},x=e=>{_(e);const a=C(e);return r(e,`SELECT * FROM "${E}" ORDER BY last_called_at DESC LIMIT ${String(1e3)}`).toArray().map(s=>({calls:s.calls,conflicts:s.conflicts,errors:s.errors,lastCalledAt:s.last_called_at,lastErrorAt:s.last_error_at,lastErrorMessage:s.last_error_message,maxDurationMs:s.max_duration_ms,path:s.path,scannedTables:a.get(s.path)??[],scans:s.scans,totalDurationMs:s.total_duration_ms}))},$=(e,a)=>{_(e);const s=a===void 0?r(e,`SELECT path, bucket_ms, calls, errors FROM "${l}" ORDER BY bucket_ms DESC, path ASC LIMIT ${String(1001)}`).toArray():r(e,`SELECT path, bucket_ms, calls, errors FROM "${l}" WHERE path = ? ORDER BY bucket_ms DESC LIMIT ${String(1001)}`,a).toArray(),t=s.length>1e3;return{buckets:(t?s.slice(0,1e3):s).toReversed().map(n=>({bucketMs:n.bucket_ms,calls:n.calls,errors:n.errors,path:n.path})),truncated:t}},f=e=>{_(e);const a=r(e,`SELECT SUM(calls) AS requests, SUM(errors) AS errors FROM "${E}"`).one();return{capped:r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=5e3,errors:a.errors??0,requests:a.requests??0}};export{l as FUNCTION_METRICS_BUCKETS_TABLE,M as FUNCTION_METRICS_BUCKET_MS,U as FUNCTION_METRICS_BUCKET_RETENTION,d as FUNCTION_METRICS_INDEX_TABLE,F as FUNCTION_METRICS_MAX_PATHS,p as FUNCTION_METRICS_READ_LIMIT,c as FUNCTION_METRICS_SCANS_TABLE,E as FUNCTION_METRICS_TABLE,_ as ensureFunctionMetricsTables,D as mergeScanAttribution,$ as readFunctionMetricBuckets,h as readFunctionMetricIndexHits,C as readFunctionMetricScans,x as readFunctionMetrics,f as readFunctionMetricsTotals,b as recordFunctionMetric};
@@ -1,15 +0,0 @@
1
- const r="__lunora_issue_state__",y=100,L=["ignored","open","resolved"],A=["critical","high","low","medium"],S=(s,e,...t)=>s.exec.call(s,e,...t),i=s=>s??null,p=s=>{S(s,`CREATE TABLE IF NOT EXISTS "${r}" (
2
- hash TEXT PRIMARY KEY,
3
- status TEXT NOT NULL DEFAULT 'open',
4
- assignee TEXT,
5
- severity TEXT,
6
- updated_at REAL NOT NULL,
7
- updated_by TEXT
8
- )`)},l=s=>({...s.assignee===null?{}:{assignee:s.assignee},hash:s.hash,...s.severity===null?{}:{severity:s.severity},status:s.status,updatedAt:s.updated_at,...s.updated_by===null?{}:{updatedBy:s.updated_by}}),N=(s,e,t={})=>{const u=t.hashQueryBatch??100,E=new Map;if(e.length===0)return E;p(s);for(let a=0;a<e.length;a+=u){const d=e.slice(a,a+u),h=d.map(()=>"?").join(", "),n=S(s,`SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${r}" WHERE hash IN (${h})`,...d).toArray();for(const T of n)E.set(T.hash,l(T))}return E},g=(s,e,t,u,E)=>{p(s);const a=i(t.status),d=i(t.assignee),h=t.assignee===null?1:0,n=i(t.severity),T=t.severity===null?1:0,_=i(E);S(s,`INSERT INTO "${r}" (hash, status, assignee, severity, updated_at, updated_by)
9
- VALUES (?, COALESCE(?, 'open'), ?, ?, ?, ?)
10
- ON CONFLICT(hash) DO UPDATE SET
11
- status = COALESCE(?, status),
12
- assignee = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, assignee) END,
13
- severity = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, severity) END,
14
- updated_at = ?,
15
- updated_by = ?`,e,a,d,n,u,_,a,h,d,T,n,u,_);const[o]=S(s,`SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${r}" WHERE hash = ?`,e).toArray();return o===void 0?{hash:e,status:a??"open",updatedAt:u,...E===void 0?{}:{updatedBy:E}}:l(o)};export{y as DEFAULT_HASH_QUERY_BATCH,A as ISSUE_SEVERITIES,r as ISSUE_STATE_TABLE,L as ISSUE_STATUSES,p as ensureIssueStateTable,N as readIssueStates,g as upsertIssueState};
@@ -1 +0,0 @@
1
- import"@lunora/fingerprint";import"@visulima/redact";import{E as o,d as E,k as g,K as L,w as m,m as p,C as R,W as d,U as n,c as u,y as T}from"./request-log-BwFic6VV.mjs";import"./ISSUE_SEVERITIES-Js6lGUG5.mjs";export{o as REQUEST_LOG_RETENTION,E as REQUEST_LOG_TABLE,g as appendRequestLogEntry,L as emitLogEvent,m as emitRequestLogEvent,p as ensureRequestLogTable,R as parseLogArgs,d as readErrorIssues,n as readRequestLog,u as redactArgs,T as renderLogMessage};
@@ -1,32 +0,0 @@
1
- const i="__lunora_metrics_queries",m="__lunora_metrics_queries_buckets",f=6e4,B=90,E=[1,2,5,10,25,50,100,250,500,1e3,5e3],R=512,I=500,o=(e,t,...r)=>e.exec.call(e,t,...r),k=e=>{let t=e.replaceAll(/'(?:[^']|'')*'/g,"?").replaceAll(/\b0x[\da-f]+\b/gi,"?").replaceAll(/(?<=[=,([\s])\d+(?:\.\d+)?/g,"?").replaceAll(/\s+/g," ").trim();return t.length>R&&(t=`${t.slice(0,R-1)}…`),t},U=new WeakSet,N=e=>{U.has(e)||(o(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
- normalized_sql TEXT PRIMARY KEY,
3
- exec_count INTEGER NOT NULL DEFAULT 0,
4
- total_duration_ms REAL NOT NULL DEFAULT 0,
5
- rows_read INTEGER NOT NULL DEFAULT 0,
6
- rows_written INTEGER NOT NULL DEFAULT 0
7
- )`),U.add(e))},M=new WeakMap,w=e=>Math.floor(e/6e4)*6e4,C=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.codePointAt(r)??0,t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},b=e=>{const t=E.findIndex(r=>e<=r);return t===-1?E.length:t},T=e=>`lat_${String(e)}`,h=new WeakSet,D=e=>{if(h.has(e))return;const t=Array.from({length:E.length+1},(r,n)=>`${T(n)} INTEGER NOT NULL DEFAULT 0`).join(", ");o(e,`CREATE TABLE IF NOT EXISTS "${m}" (
8
- sql_hash TEXT NOT NULL,
9
- bucket_ms INTEGER NOT NULL,
10
- exec_count INTEGER NOT NULL DEFAULT 0,
11
- total_duration_ms REAL NOT NULL DEFAULT 0,
12
- rows_read INTEGER NOT NULL DEFAULT 0,
13
- rows_written INTEGER NOT NULL DEFAULT 0,
14
- ${t},
15
- PRIMARY KEY (sql_hash, bucket_ms)
16
- )`),h.add(e)},$=(e,t)=>{o(e,`DELETE FROM "${m}" WHERE bucket_ms < ?`,w(t)-90*6e4)},q=(e,t,r,n,u,_,s=1)=>{try{D(e);const c=s>0?r/s:r,l=T(b(c)),S=`INSERT INTO "${m}" (sql_hash, bucket_ms, exec_count, total_duration_ms, rows_read, rows_written, ${l})
17
- VALUES (?, ?, ?, ?, ?, ?, ?)
18
- ON CONFLICT(sql_hash, bucket_ms) DO UPDATE SET
19
- exec_count = exec_count + excluded.exec_count,
20
- total_duration_ms = total_duration_ms + excluded.total_duration_ms,
21
- rows_read = rows_read + excluded.rows_read,
22
- rows_written = rows_written + excluded.rows_written,
23
- ${l} = ${l} + excluded.${l}`;o(e,S,C(t),w(_),s,r,n,u,s);const a=w(_);M.get(e)!==a&&(M.set(e,a),$(e,_))}catch{}},x=(e,t)=>{const r=e.reduce((_,s)=>_+s,0);if(r===0)return 0;const n=r*t;let u=0;for(const[_,s]of e.entries())if(u+=s,u>=n)return E[_]??E.at(-1)??0;return E.at(-1)??0},Y=(e,t,r=Date.now())=>{try{N(e),D(e)}catch{return{buckets:[],capped:!1,entries:[],trackedStatements:0}}const n=w(r-t),u=Array.from({length:E.length+1},(a,d)=>`SUM(${T(d)}) AS ${T(d)}`).join(", "),_=o(e,`SELECT sql_hash, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms,
24
- SUM(rows_read) AS rows_read, SUM(rows_written) AS rows_written, ${u}
25
- FROM "${m}" WHERE bucket_ms >= ? GROUP BY sql_hash`,n).toArray(),s=new Map;for(const a of o(e,`SELECT normalized_sql FROM "${i}"`))s.set(C(a.normalized_sql),a.normalized_sql);const c=_.map(a=>{const d=Array.from({length:E.length+1},(y,g)=>Number(a[T(g)]??0)),L=Number(a.exec_count??0),A=Number(a.total_duration_ms??0);return{avgDurationMs:L>0?A/L:0,execCount:L,normalizedSql:s.get(String(a.sql_hash))??String(a.sql_hash),p50DurationMs:x(d,.5),p95DurationMs:x(d,.95),rowsRead:Number(a.rows_read??0),rowsWritten:Number(a.rows_written??0),totalDurationMs:A}});c.sort((a,d)=>d.totalDurationMs-a.totalDurationMs);const l=o(e,`SELECT bucket_ms, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms
26
- FROM "${m}" WHERE bucket_ms >= ? GROUP BY bucket_ms ORDER BY bucket_ms ASC`,n).toArray().map(a=>({avgDurationMs:a.exec_count>0?a.total_duration_ms/a.exec_count:0,bucketMs:a.bucket_ms,execCount:a.exec_count})),S=o(e,`SELECT COUNT(*) AS n FROM "${i}"`).one().n;return{buckets:l,capped:S>=I,entries:c,trackedStatements:S}},O=new WeakMap,F=e=>{let t=O.get(e);return t===void 0&&(t=new Set,O.set(e,t)),t},p=(e,t)=>{const r=F(e);return r.has(t)?!0:o(e,`SELECT 1 AS c FROM "${i}" WHERE normalized_sql = ? LIMIT 1`,t).toArray().length>0?(r.add(t),!0):o(e,`SELECT COUNT(*) AS n FROM "${i}"`).one().n>=I?!1:(r.add(t),!0)},Q=(e,t,r,n,u,_=Date.now(),s=1)=>{const c=k(t);if(c.length===0||(N(e),!p(e,c)))return;const l=`INSERT INTO "${i}" (normalized_sql, exec_count, total_duration_ms, rows_read, rows_written)
27
- VALUES (?, ?, ?, ?, ?)
28
- ON CONFLICT(normalized_sql) DO UPDATE SET
29
- exec_count = exec_count + excluded.exec_count,
30
- total_duration_ms = total_duration_ms + excluded.total_duration_ms,
31
- rows_read = rows_read + excluded.rows_read,
32
- rows_written = rows_written + excluded.rows_written`;o(e,l,c,s,r,n,u),q(e,c,r,n,u,_,s)},z=e=>(N(e),o(e,`SELECT normalized_sql, exec_count, total_duration_ms, rows_read, rows_written FROM "${i}" ORDER BY total_duration_ms DESC`).toArray().map(t=>({execCount:t.exec_count,normalizedSql:t.normalized_sql,rowsRead:t.rows_read,rowsWritten:t.rows_written,totalDurationMs:t.total_duration_ms})));export{E as LATENCY_BUCKET_EDGES,m as QUERY_BUCKETS_TABLE,f as QUERY_BUCKET_MS,B as QUERY_BUCKET_RETENTION,R as QUERY_METRICS_MAX_SQL_LEN,I as QUERY_METRICS_MAX_STATEMENTS,i as QUERY_METRICS_TABLE,D as ensureQueryBucketsTable,N as ensureQueryMetricsTable,C as hashStatement,b as latencyBucketIndex,k as normalizeSql,x as percentileFrom,$ as pruneQueryBuckets,Y as readQueryInsights,z as readQueryMetrics,q as recordQueryBucket,Q as recordQueryMetric};
@@ -1,21 +0,0 @@
1
- import{fingerprintError as I}from"@lunora/fingerprint";import{redact as L,standardRules as R}from"@visulima/redact";import{readIssueStates as M}from"./ISSUE_SEVERITIES-Js6lGUG5.mjs";const P=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},m=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:P(e),v=(e,r)=>{if(e===void 0&&r===void 0)return;const o={};if(r!==void 0)for(const[t,s]of Object.entries(r))o[t]=m(s);if(e!==void 0)for(const[t,s]of Object.entries(e))o[t]=m(s);return Object.keys(o).length===0?void 0:o},d="__lunora_reqlog__",E=1e3,b="lunora",h=(e,r,...o)=>e.exec.call(e,r,...o),c=(e,r=!1)=>r||e===null||e===void 0?e:L(e,R),y=e=>{h(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
- duration_ms REAL NOT NULL,
13
- tables_read TEXT NOT NULL DEFAULT '[]',
14
- tables_written TEXT NOT NULL DEFAULT '[]',
15
- cache_hit INTEGER,
16
- subscriptions_rerun INTEGER NOT NULL DEFAULT 0
17
- )`);try{h(e,`ALTER TABLE "${d}" ADD COLUMN error_fingerprint TEXT`)}catch{}},S=e=>JSON.stringify([...new Set(e)].toSorted((r,o)=>r.localeCompare(o))),w=e=>e===void 0?null:e?1:0,x=(e,r,o={})=>{y(e);const t=o.captureRaw??!1,s=o.retention??E,i=r.outcome==="error"&&r.errorMessage!==void 0?I({functionPath:r.functionPath,message:r.errorMessage}).hash:void 0;h(e,`INSERT INTO "${d}"
18
- (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
19
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,r.ts,r.functionPath,r.shardKey??null,r.userId??null,r.identity===void 0?null:JSON.stringify(c(r.identity,t)),r.redactedArgs===void 0?null:JSON.stringify(c(r.redactedArgs,t)),r.outcome,r.errorMessage===void 0?null:c(r.errorMessage,t),i??null,r.durationMs,S(r.tablesRead),S(r.tablesWritten),w(r.cacheHit),r.subscriptionsReRun??0),h(e,`DELETE FROM "${d}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${d}")`,s)},D=(e,r={})=>{const o=r.captureRaw??!1,t={args:e.redactedArgs===void 0?void 0:c(e.redactedArgs,o),cacheHit:e.cacheHit,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:c(e.errorMessage,o),function:e.functionPath,identity:e.identity===void 0?void 0:c(e.identity,o),outcome:e.outcome,shard:e.shardKey,source:b,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],ts:e.ts,type:"request",userId:e.userId},s=JSON.stringify(t);e.outcome==="error"?console.error(s):console.log(s)},K="log",U=e=>e.map(r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}}).join(" "),C=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=Object.getPrototypeOf(e);return r===Object.prototype||r===null},J=(e,r)=>e.length===2&&typeof e[0]=="string"&&C(e[1])?{fields:v(e[1],r),message:e[0]}:{fields:v(void 0,r),message:U(e)},k=(e,r={})=>{const o=r.captureRaw??!1,t={fields:e.fields===void 0?void 0:c(e.fields,o),function:e.functionPath,level:e.level,message:e.message,shard:e.shardKey,source:b,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:K,userId:e.userId};let s;try{s=JSON.stringify(t)}catch{s=JSON.stringify({...t,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(s):e.level==="warn"?console.warn(s):console.log(s)},g=e=>e.replaceAll(/[\\%_]/g,r=>`\\${r}`),N=e=>{try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):[]}catch{return[]}},j=(e,r={})=>{y(e);const o=Math.max(1,Math.min(r.limit??E,1e4)),t=["seq > ?"],s=[r.sinceSeq??0];if(r.functionPathPrefix!==void 0&&r.functionPathPrefix!==""&&(t.push(String.raw`function_path LIKE ? ESCAPE '\'`),s.push(`${g(r.functionPathPrefix)}%`)),r.userId!==void 0&&r.userId!==""&&(t.push("user_id = ?"),s.push(r.userId)),r.shardKey!==void 0&&r.shardKey!==""&&(t.push("shard_key = ?"),s.push(r.shardKey)),r.outcome!==void 0&&(t.push("outcome = ?"),s.push(r.outcome)),r.tableTouched!==void 0&&r.tableTouched!==""){const i=`%${g(JSON.stringify(r.tableTouched))}%`;t.push(String.raw`(tables_read LIKE ? ESCAPE '\' OR tables_written LIKE ? ESCAPE '\')`),s.push(i,i)}return s.push(o),h(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
20
- FROM "${d}" WHERE ${t.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...s).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),n})},q=(e,r)=>{const o=M(e,[...r.keys()]);for(const t of r.values()){const s=o.get(t.hash);s!==void 0&&(t.stateUpdatedAt=s.updatedAt,s.assignee!==void 0&&(t.assignee=s.assignee),s.severity!==void 0&&(t.severity=s.severity),t.status=s.status==="resolved"&&t.lastSeen>s.updatedAt?"open":s.status)}},W=(e,r={})=>{y(e);const o=Math.max(1,Math.min(r.limit??E,1e4)),t=["outcome = 'error'"],s=[];r.functionPathPrefix!==void 0&&r.functionPathPrefix!==""&&(t.push(String.raw`function_path LIKE ? ESCAPE '\'`),s.push(`${g(r.functionPathPrefix)}%`)),r.userId!==void 0&&r.userId!==""&&(t.push("user_id = ?"),s.push(r.userId)),r.shardKey!==void 0&&r.shardKey!==""&&(t.push("shard_key = ?"),s.push(r.shardKey)),s.push(o);const i=h(e,`SELECT function_path, error_message, error_fingerprint, ts
21
- FROM "${d}" WHERE ${t.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...s).toArray(),n=new Map,p=new Map;for(const a of i){const f=a.error_message??"",{culprit:O,hash:A,title:T}=I({functionPath:a.function_path,message:f}),l=a.error_fingerprint??A,u=n.get(l);if(u===void 0){n.set(l,{count:1,culprit:O,firstSeen:a.ts,hash:l,lastSeen:a.ts,sampleMessage:f,status:"open",title:T}),p.set(l,a.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,a.ts),u.lastSeen=Math.max(u.lastSeen,a.ts),a.ts>(p.get(l)??Number.NEGATIVE_INFINITY)&&(p.set(l,a.ts),u.sampleMessage=f,u.title=T)}q(e,n);const _=[...n.values()];return(r.status===void 0?_:_.filter(a=>a.status===r.status)).toSorted((a,f)=>f.lastSeen-a.lastSeen)};export{J as C,E,k as K,j as U,W,c,d,x as k,y as m,v as n,D as w,U as y};