@webority/server-timing 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{createHash as X,timingSafeEqual as Y}from"node:crypto";var Q=/^[0-9a-f]{64}$/,Z=/^[a-z][a-z0-9-]{0,19}$/,J=/^[a-z0-9][a-z0-9.-]*$/,ee=/^(?:\d+(?:\.\d+)?|\.\d+)$/,te=40,ne=2048,re=500,k="private, no-store",se=new Set(["server-timing","traceparent","traceresponse","timing-allow-origin"]);function b(e){return{ok:!1,setting:e}}function c(e){return Math.round(Math.round(e*1e9)/1e9*10)/10}var l=e=>e!=null;function v(e){let n=l(e.busyMs)?e.busyMs:(e.dbMs??0)+(e.cacheMs??0)+(e.extMs??0)+(e.modelMs??0)+(e.renderMs??0);return Math.max(0,e.totalMs-n)}var oe=/'(?:[^'\\]|\\.|'')*'/g,ie=/"(?:[^"\\]|\\.)*"/g,ae=/(?<![A-Za-z0-9_$])-?(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g,ue=/\b(IN)(\s*)\(\s*\?(?:\s*,\s*\?)*\s*\)/gi;function M(e){return e.replace(oe,"?").replace(ie,"?").replace(ae,"?").replace(ue,"$1$2(?)")}function nt(e){let n="WEBORITY_TIMING_TOKEN_SHA256",t=(e[n]??"").split(",");if(t.length>2||!t.every(p=>Q.test(p)))return b(n);let r=e.WEBORITY_TIMING_SERVICE??"";if(!Z.test(r))return b("WEBORITY_TIMING_SERVICE");let s="WEBORITY_TIMING_FORWARD_HOSTS",o=e[s],i;if(o==="none")i=[];else if(i=(o??"").split(",").map(p=>p.trim().toLowerCase()),!i.every(p=>J.test(p)))return b(s);let a=e.APPLICATIONINSIGHTS_CONNECTION_STRING??"";if(a.trim()==="")return b("APPLICATIONINSIGHTS_CONNECTION_STRING");let u="WEBORITY_TRACE_SAMPLE_RATIO",d=e[u]??"";if(!ee.test(d)||Number(d)>1)return b(u);let m={tokenFingerprints:t,service:r,forwardHosts:i,sampleRatio:Number(d),connectionString:a};return Object.defineProperty(m,"connectionString",{value:a,enumerable:!1,writable:!1,configurable:!1}),{ok:!0,config:m}}function N(e,n){if(!n)return!1;let t=Buffer.from(X("sha256").update(n,"utf8").digest("hex"));return e.some(r=>{let s=Buffer.from(r);return s.length===t.length&&Y(s,t)})}function O(e,n){return!e||!n?null:n}function w(e,n,t){return(t??[]).slice(0,3).map((r,s)=>`${e}.${n}${s+1};dur=${c(r.ms)};desc="${r.desc}"`)}function q(e,n){let t=n,r=[`${e}.total;dur=${c(t.totalMs)}`,`${e}.app;dur=${c(v(t))}`,`${e}.db;dur=${c(t.dbMs??0)};desc="${t.dbCount??0} queries"`,...w(e,"db",t.dbTop)];if(l(t.cacheMs)){let o=t.cacheResult?`;desc="${t.cacheResult}"`:"";r.push(`${e}.cache;dur=${c(t.cacheMs)}${o}`)}r.push(`${e}.ext;dur=${c(t.extMs??0)};desc="${t.extCount??0} calls"`,...w(e,"ext",t.extTop)),l(t.modelMs)&&r.push(`${e}.model;dur=${c(t.modelMs)};desc="${t.modelCount??0} calls"`),r.push(`${e}.render;dur=${c(t.renderMs??0)}`,...w(e,"render",t.renderTop)),l(t.preMs)&&r.push(`${e}.pre;dur=${c(t.preMs)}`),l(t.endpointMs)&&r.push(`${e}.endpoint;dur=${c(t.endpointMs)}`),t.queueMs!==void 0&&r.push(`${e}.queue;dur=${c(t.queueMs)}`),t.bootMs!==void 0&&r.push(`${e}.boot;dur=${c(t.bootMs)}`),t.pluginsMs!==void 0&&r.push(`${e}.plugins;dur=${c(t.pluginsMs)};desc="${t.pluginCount} plugins"`);let s=Object.entries(t.runtime??{}).sort(([o],[i])=>o<i?-1:o>i?1:0);if(s.length>0){let o=s.map(([i,a])=>`${i}=${c(a)}`).join(" ");r.push(`${e}.runtime;desc="${o}"`)}return r.push(`trace;desc="${t.traceId}"`),r.join(", ")}function L(e){let n=new Map,t=null;for(let o of e){let i=M(o.sql);n.set(i,(n.get(i)??0)+1),l(o.rows)&&(t===null||o.rows>t)&&(t=o.rows)}let r=0,s=null;for(let[o,i]of n)i>r&&(r=i,s=o);return{dbCount:e.length,dbRepeatMax:r,dbRepeatSql:s===null?null:s.slice(0,re),dbRowsMax:t}}function de(e,n){return e||n>=1||n<=0?1:Math.round(1e4/n)/1e4}function P(e,n,t){let r=e,s={"webority.timing.authorised":n,"webority.sample_rate":de(n,t),"webority.timing.total_ms":c(r.totalMs),"webority.timing.app_ms":c(v(r))},o={db_ms:r.dbMs,cache_ms:r.cacheMs,ext_ms:r.extMs,model_ms:r.modelMs,render_ms:r.renderMs,queue_ms:r.queueMs,boot_ms:r.bootMs,plugins_ms:r.pluginsMs};for(let[a,u]of Object.entries(o))l(u)&&(s[`webority.timing.${a}`]=c(u));let i={db_count:r.dbCount,ext_count:r.extCount,model_count:r.modelCount,plugin_count:r.pluginCount,db_repeat_max:r.dbRepeatMax,db_repeat_sql:r.dbRepeatSql,db_rows_max:r.dbRowsMax,cache_result:r.cacheResult};for(let[a,u]of Object.entries(i))l(u)&&(s[`webority.timing.${a}`]=u);l(r.memPeakKb)&&(s["webority.mem.peak_kb"]=r.memPeakKb),l(r.cpuMs)&&(s["webority.cpu_ms"]=c(r.cpuMs));for(let[a,u]of Object.entries(r.runtime??{}))s[`webority.runtime.${a}`]=c(u);return s}function A(e){let n=[],t="",r=!1;for(let s of e)s==='"'&&(r=!r),s===","&&!r?(n.push(t.trim()),t=""):t+=s;return n.push(t.trim()),n.filter(s=>s.length>0)}var C=e=>e.startsWith("trace;");function D(e,n){let t=A(e),r=t.filter(C),s=t.filter(u=>!C(u)),o=n.flatMap(A).filter(u=>!C(u)),i=()=>[...s,...o,...r],a=i();for(;o.length>0&&(a.length>te||a.join(", ").length>ne);)o.pop(),a=i();return a.join(", ")}var ce=["api.anthropic.com","api.openai.com",".openai.azure.com",".services.ai.azure.com","generativelanguage.googleapis.com"];function G(e){if(!e)return!1;let n=e.toLowerCase().replace(/:\d+$/,"");return ce.some(t=>n===t||t.startsWith(".")&&n.endsWith(t))}function W(e,n,t){if(!n||!t)return!1;let r=String(t).toLowerCase().replace(/:\d+$/,"");return e.includes(r)}function B(e,n){if(!n)return e.filter(([s])=>!se.has(s.toLowerCase()));let t=[],r=!1;for(let[s,o]of e)s.toLowerCase()!=="cache-control"?t.push([s,o]):r||(t.push(["Cache-Control",k]),r=!0);return r||t.push(["Cache-Control",k]),t}import{createRequire as me,syncBuiltinESMExports as le}from"node:module";import{NodeSDK as fe}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as ge,TraceIdRatioBasedSampler as be,SamplingDecision as he}from"@opentelemetry/sdk-trace-base";import{resourceFromAttributes as Se}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as Me}from"@opentelemetry/semantic-conventions";import{SpanKind as F,trace as Re}from"@opentelemetry/api";import{ClientRequest as K,IncomingMessage as we}from"node:http";import{HttpInstrumentation as Ce}from"@opentelemetry/instrumentation-http";import{MongoDBInstrumentation as xe}from"@opentelemetry/instrumentation-mongodb";import{IORedisInstrumentation as Te}from"@opentelemetry/instrumentation-ioredis";import{RedisInstrumentation as ye}from"@opentelemetry/instrumentation-redis";import{MySQL2Instrumentation as _e}from"@opentelemetry/instrumentation-mysql2";import{PgInstrumentation as He}from"@opentelemetry/instrumentation-pg";import{UndiciInstrumentation as Ee}from"@opentelemetry/instrumentation-undici";import{AzureMonitorTraceExporter as Ie}from"@azure/monitor-opentelemetry-exporter";import{AsyncLocalStorage as pe}from"node:async_hooks";var h=new pe,g=()=>h.getStore();var j="Webority-Timing-Token",$e=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,T=["db.statement","db.query.text"],ke="db.response.returned_rows",x=500,U=new WeakMap,f=([e,n])=>e*1e3+n/1e6,y=class{inject(){}extract(n,t,r){let s=r.get(t,"traceparent"),o=Array.isArray(s)?s[0]:s,i=typeof o=="string"?$e.exec(o):null;if(!i)return n;let[,a,u,d]=i;return a===void 0||u===void 0||d===void 0||!/[1-9a-f]/.test(a)||!/[1-9a-f]/.test(u)?n:Re.setSpanContext(n,{traceId:a,spanId:u,traceFlags:parseInt(d,16),isRemote:!0})}fields(){return["traceparent"]}},_=class{attributes;span;constructor(n,t){this.span=n,this.attributes=t,n.parentSpanContext!==void 0&&(this.parentSpanContext=n.parentSpanContext)}get name(){return this.span.name}get kind(){return this.span.kind}spanContext(){return this.span.spanContext()}get startTime(){return this.span.startTime}get endTime(){return this.span.endTime}get status(){return this.span.status}get links(){return this.span.links}get events(){return this.span.events}get duration(){return this.span.duration}get ended(){return this.span.ended}get resource(){return this.span.resource}get instrumentationScope(){return this.span.instrumentationScope}get droppedAttributesCount(){return this.span.droppedAttributesCount}get droppedEventsCount(){return this.span.droppedEventsCount}get droppedLinksCount(){return this.span.droppedLinksCount}};function Ae(e){if(!T.some(t=>typeof e.attributes[t]=="string"))return e;let n={...e.attributes};for(let t of T){let r=n[t];typeof r=="string"&&(n[t]=M(r))}return new _(e,n)}function ve(e){for(let n of T){let t=e.attributes[n];if(typeof t=="string")return t}return e.name}var H=class{constructor(n){this.inner=n}export(n,t){this.inner.export(n.map(Ae),t)}shutdown(){return this.inner.shutdown()}forceFlush(){return this.inner.forceFlush?.()??Promise.resolve()}};function Ne(e){for(let n of["server.address","net.peer.name","http.host"]){let t=e.attributes[n];if(typeof t=="string")return t}}var E=class{onStart(n){let t=h.getStore();t&&(n.kind===F.SERVER&&!t.serverSpan&&(t.serverSpan=n,n.setAttribute("webority.timing.authorised",t.authorised)),U.set(n,t))}onEnd(n){let t=U.get(n);if(!t)return;let r=n.instrumentationScope.name;if(r.includes("mongodb")||r.includes("mysql2")||r.includes("pg")){t.dbMs+=f(n.duration),t.intervals.length<x&&t.intervals.push([f(n.startTime),f(n.endTime)]);let s={sql:M(ve(n))},o=n.attributes[ke];typeof o=="number"&&(s.rows=o),t.statements.push(s)}else r.includes("ioredis")||r.includes("redis")?(t.cacheMs+=f(n.duration),t.cacheCount+=1,t.intervals.length<x&&t.intervals.push([f(n.startTime),f(n.endTime)])):n.kind===F.CLIENT&&(r.includes("instrumentation-http")||r.includes("instrumentation-undici"))&&(G(Ne(n))?(t.modelMs+=f(n.duration),t.modelCount+=1):(t.extMs+=f(n.duration),t.extCount+=1),t.intervals.length<x&&t.intervals.push([f(n.startTime),f(n.endTime)]))}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function Oe(e){let n=new be(e);return{shouldSample(t,r,s,o,i,a){return g()?.authorised?{decision:he.RECORD_AND_SAMPLED}:n.shouldSample(t,r,s,o,i,a)},toString(){return"WeborityTimingSampler"}}}function qe(e){return e instanceof we&&(!("req"in e)||e.req===void 0||e.req instanceof K)}function z(e){let{traceId:n,spanId:t,traceFlags:r}=e.spanContext();return`00-${n}-${t}-${r.toString(16).padStart(2,"0")}`}function xt(e){let n=s=>W(e.forwardHosts,!!g()?.authorised,s),t=new fe({resource:Se({[Me]:e.service}),sampler:Oe(e.sampleRatio),spanProcessors:[new ge(new H(new Ie({connectionString:e.connectionString}))),new E],textMapPropagator:new y,instrumentations:[new Ce({requestHook(s,o){let i=g()?.token;!(o instanceof K)||i===void 0||!n(o.host)||(o.setHeader(j,i),o.setHeader("traceparent",z(s)))},responseHook(s,o){let i=g();if(!qe(o))return;let a=o.headers["server-timing"];a&&i&&n(o.req?.host)&&i.inner.push(String(a))}}),new Ee({requestHook(s,o){let i=g()?.token;i===void 0||!n(new URL(o.origin).hostname)||(o.addHeader(j,i),o.addHeader("traceparent",z(s)))},responseHook(s,{request:o,response:i}){let a=g();if(!a||!n(new URL(o.origin).hostname))return;let u=i.headers;for(let d=0;d+1<u.length;d+=2){let m=u[d],p=u[d+1];m&&p&&m.toString("latin1").toLowerCase()==="server-timing"&&a.inner.push(p.toString("latin1"))}}}),new xe({enhancedDatabaseReporting:!1}),new Te,new ye,new _e,new He({enhancedDatabaseReporting:!1})]});t.start();let r=me(import.meta.url);return r("node:http"),r("node:https"),le(),t}import $ from"node:http";import Le from"node:https";import{getHeapStatistics as Pe}from"node:v8";import{monitorEventLoopDelay as De}from"node:perf_hooks";var I=1024*1024,Ge=6e4,We=/^t=(\d+\.\d+)$/,Be=/^t=(\d+)$/,R;function Fe(e,n){if(typeof e!="string")return;let t=We.exec(e),r=Be.exec(e),s;if(t)s=Number(t[1])*1e3;else if(r)s=Number(r[1])/1e3;else return;let o=n-s;return o<0||o>Ge?void 0:o}function je(e,n,t){let r={authorised:e,queueMs:t,startNs:process.hrtime.bigint(),dbMs:0,cacheMs:0,cacheCount:0,extMs:0,extCount:0,modelMs:0,modelCount:0,statements:[],intervals:[],inner:[],serverSpan:void 0};return e&&Object.defineProperty(r,"token",{value:n,enumerable:!1}),r}function Ue(){let e=Pe();if(R===void 0)throw new TypeError("Webority server timing: the event loop monitor is not installed");return{eventloop_p99_ms:R.percentile(99)/1e6,heap_used_mb:e.used_heap_size/I,heap_limit_mb:e.heap_size_limit/I,rss_mb:process.memoryUsage.rss()/I}}function ze(e){let n=0,t=-1/0;for(let[r,s]of[...e].sort((o,i)=>o[0]-i[0])){let o=Math.max(r,t);s>o&&(n+=s-o),t=Math.max(t,s)}return n}function Ke(e,n){let t=L(e.statements),r={totalMs:Number(process.hrtime.bigint()-e.startNs)/1e6,dbMs:e.dbMs,dbCount:t.dbCount,dbRepeatMax:t.dbRepeatMax,dbRepeatSql:t.dbRepeatSql,dbRowsMax:t.dbRowsMax,extMs:e.extMs,extCount:e.extCount,runtime:Ue(),traceId:n};return e.modelCount>0&&(r.modelMs=e.modelMs,r.modelCount=e.modelCount),e.cacheCount>0&&(r.cacheMs=e.cacheMs),e.intervals.length>0&&(r.busyMs=ze(e.intervals)),e.queueMs!==void 0&&(r.queueMs=e.queueMs),r}function Ve(e){let n=e.route?.path;return typeof n=="string"?`${e.baseUrl??""}${n}`:void 0}function Xe(e){let n=[];for(let t=0;t<e.length;t+=2)n.push([String(e[t]),e[t+1]]);return n}function Ye(e,n){let t=e.getRawHeaderNames().map(o=>[o,e.getHeader(o)]);if(!n)return t;let r=Array.isArray(n)?Xe(n):Object.entries(n),s=new Set(r.map(([o])=>o.toLowerCase()));return[...t.filter(([o])=>!s.has(o.toLowerCase())),...r]}function V(e,n){if(n===void 0)throw new TypeError(`Webority server timing: header ${e} has no value`);return n}function Qe(e,n){let t=new Map;for(let[r,s]of n){let o=r.toLowerCase(),i=t.get(o)??{name:r,values:[]};i.values.push(...Array.isArray(s)?s:[s]),t.set(o,i)}for(let r of e.getRawHeaderNames())e.removeHeader(r);for(let{name:r,values:s}of t.values())s.length===1?e.setHeader(r,V(r,s[0])):e.setHeader(r,s.map(o=>String(V(r,o))))}function Ze(e,n,t,r){let s=n.serverSpan;if(!s){if(n.authorised)throw new Error("Webority server timing: an authorised request has no server span");return r}let o=Ke(n,s.spanContext().traceId),i=Ve(e),a=e.method;if(a===void 0)throw new TypeError("Webority server timing: a request has no method");if(s.updateName(i===void 0?a:`${a} ${i}`),s.setAttribute("http.route",i??"unmatched"),s.setAttributes(P(o,n.authorised,t.sampleRatio)),!n.authorised)return r;let u=D(q(t.service,o),n.inner),d=O(n.authorised,e.headers.origin),p=[...r.filter(([S])=>!["server-timing","timing-allow-origin"].includes(S.toLowerCase())),["Server-Timing",u]];return d!==null&&p.push(["Timing-Allow-Origin",d]),p}function Je(e){return e instanceof $.ServerResponse&&"getRawHeaderNames"in e&&typeof e.getRawHeaderNames=="function"}function et(e,n,t,r){let s=n.writeHead;n.writeHead=function(o,...i){let[a,u]=i,d=typeof a=="string"?a:void 0,m=typeof a=="string"?u:a;if(n.headersSent)return s.call(this,o,d,m);let p=B(Ye(n,m),t.authorised);return o>=200&&(p=Ze(e,t,r,p)),Qe(n,p),s.call(this,o,d)}}function kt(e){if(R)return;let n=De({resolution:20});R=n,n.enable(),setInterval(()=>n.reset(),1e4).unref();for(let t of[$.Server,Le.Server]){let r=t.prototype.emit;t.prototype.emit=function(o,...i){if(o!=="request")return r.call(this,o,...i);let[a,u]=i;if(!(a instanceof $.IncomingMessage)||!Je(u))throw new TypeError("Webority server timing: a request event carries no request and response");let d=a.headers["webority-timing-token"],m=typeof d=="string"?d:void 0,p=N(e.tokenFingerprints,m),S=je(p,m,Fe(a.headers["x-request-start"],Date.now()));return et(a,u,S,e),h.run(S,()=>r.call(this,o,...i))}}}export{M as a,nt as b,N as c,q as d,D as e,W as f,B as g,xt as h,kt as i};
package/dist/context.d.ts CHANGED
@@ -10,6 +10,8 @@ export interface Timing {
10
10
  cacheCount: number;
11
11
  extMs: number;
12
12
  extCount: number;
13
+ modelMs: number;
14
+ modelCount: number;
13
15
  statements: Statement[];
14
16
  intervals: [number, number][];
15
17
  inner: string[];
package/dist/core.d.ts CHANGED
@@ -31,6 +31,8 @@ export interface Measurements {
31
31
  extMs?: number;
32
32
  extCount?: number;
33
33
  extTop?: Ranked[];
34
+ modelMs?: number;
35
+ modelCount?: number;
34
36
  renderMs?: number;
35
37
  renderTop?: Ranked[];
36
38
  preMs?: number;
@@ -62,5 +64,6 @@ export declare function summariseStatements(statements: Statement[]): {
62
64
  };
63
65
  export declare function spanAttributes(measurements: Measurements, authorised: boolean, sampleRatio: number): Record<string, string | number | boolean>;
64
66
  export declare function merge(own: string, inner: string[]): string;
67
+ export declare function isModelHost(host: string | undefined): boolean;
65
68
  export declare function shouldForward(forwardHosts: string[], authorised: boolean, host: string | undefined): boolean;
66
69
  export declare function scrubResponseHeaders(headers: Header[], authorised: boolean): Header[];
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as r,b as o,c as e,d as t,e as a,f as s,g as m,h as f,i as p}from"./chunk-FI5VOB3J.js";export{e as authorise,t as format,p as installHttpHook,r as maskSql,a as merge,o as readConfig,m as scrubResponseHeaders,s as shouldForward,f as startTracing};
1
+ import{a as r,b as o,c as e,d as t,e as a,f as s,g as m,h as f,i as p}from"./chunk-RYXD5HE7.js";export{e as authorise,t as format,p as installHttpHook,r as maskSql,a as merge,o as readConfig,m as scrubResponseHeaders,s as shouldForward,f as startTracing};
package/dist/register.js CHANGED
@@ -1 +1 @@
1
- import{b as i,h as o,i as t}from"./chunk-FI5VOB3J.js";var r=i(process.env);if(!r.ok)throw new Error(`Webority server timing: ${r.setting} is missing or invalid`);o(r.config);t(r.config);
1
+ import{b as i,h as o,i as t}from"./chunk-RYXD5HE7.js";var r=i(process.env);if(!r.ok)throw new Error(`Webority server timing: ${r.setting} is missing or invalid`);o(r.config);t(r.config);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/server-timing",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "engines": {
@@ -30,27 +30,29 @@
30
30
  ],
31
31
  "dependencies": {
32
32
  "@azure/monitor-opentelemetry-exporter": "1.0.0-beta.32",
33
- "@opentelemetry/api": "1.10.0",
34
- "@opentelemetry/instrumentation-http": "0.300.0",
35
- "@opentelemetry/instrumentation-ioredis": "0.72.0",
36
- "@opentelemetry/instrumentation-mongodb": "0.77.0",
37
- "@opentelemetry/instrumentation-mysql2": "0.70.0",
38
- "@opentelemetry/instrumentation-pg": "0.77.0",
39
- "@opentelemetry/instrumentation-redis": "0.72.0",
40
- "@opentelemetry/instrumentation-undici": "0.34.0",
41
- "@opentelemetry/resources": "3.0.0",
42
- "@opentelemetry/sdk-node": "0.300.0",
43
- "@opentelemetry/sdk-trace-base": "2.12.0",
33
+ "@opentelemetry/api": "1.9.1",
34
+ "@opentelemetry/instrumentation-http": "0.223.2",
35
+ "@opentelemetry/instrumentation-ioredis": "0.71.0",
36
+ "@opentelemetry/instrumentation-mongodb": "0.76.0",
37
+ "@opentelemetry/instrumentation-mysql2": "0.69.0",
38
+ "@opentelemetry/instrumentation-pg": "0.76.0",
39
+ "@opentelemetry/instrumentation-redis": "0.71.0",
40
+ "@opentelemetry/instrumentation-undici": "0.33.0",
41
+ "@opentelemetry/resources": "2.12.1",
42
+ "@opentelemetry/sdk-node": "0.223.2",
43
+ "@opentelemetry/sdk-trace-base": "2.12.1",
44
44
  "@opentelemetry/semantic-conventions": "1.44.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "24.19.2",
48
+ "@webority/biome-config": "0.171.3",
48
49
  "esbuild": "0.28.2",
49
50
  "typescript": "7.0.2"
50
51
  },
51
52
  "scripts": {
52
53
  "build": "node build.mjs",
53
- "check": "tsc -p .",
54
+ "check": "pnpm run typecheck && tsc -p .",
55
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.build.json",
54
56
  "test": "tsc -p . && node --test test/core.test.ts test/http-hook.test.ts"
55
57
  }
56
58
  }
@@ -1 +0,0 @@
1
- import{createHash as V,timingSafeEqual as X}from"node:crypto";var Y=/^[0-9a-f]{64}$/,Q=/^[a-z][a-z0-9-]{0,19}$/,Z=/^[a-z0-9][a-z0-9.-]*$/,J=/^(?:\d+(?:\.\d+)?|\.\d+)$/,ee=40,te=2048,ne=500,A="private, no-store",re=new Set(["server-timing","traceparent","traceresponse","timing-allow-origin"]);function b(e){return{ok:!1,setting:e}}function p(e){return Math.round(Math.round(e*1e9)/1e9*10)/10}var f=e=>e!=null;function $(e){let n=f(e.busyMs)?e.busyMs:(e.dbMs??0)+(e.cacheMs??0)+(e.extMs??0)+(e.renderMs??0);return Math.max(0,e.totalMs-n)}var se=/'(?:[^'\\]|\\.|'')*'/g,oe=/"(?:[^"\\]|\\.)*"/g,ie=/(?<![A-Za-z0-9_$])-?(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g,ae=/\b(IN)(\s*)\(\s*\?(?:\s*,\s*\?)*\s*\)/gi;function S(e){return e.replace(se,"?").replace(oe,"?").replace(ie,"?").replace(ae,"$1$2(?)")}function Je(e){let n="WEBORITY_TIMING_TOKEN_SHA256",t=(e[n]??"").split(",");if(t.length>2||!t.every(c=>Y.test(c)))return b(n);let r=e.WEBORITY_TIMING_SERVICE??"";if(!Q.test(r))return b("WEBORITY_TIMING_SERVICE");let s="WEBORITY_TIMING_FORWARD_HOSTS",o=e[s],i;if(o==="none")i=[];else if(i=(o??"").split(",").map(c=>c.trim().toLowerCase()),!i.every(c=>Z.test(c)))return b(s);let a=e.APPLICATIONINSIGHTS_CONNECTION_STRING??"";if(a.trim()==="")return b("APPLICATIONINSIGHTS_CONNECTION_STRING");let u="WEBORITY_TRACE_SAMPLE_RATIO",d=e[u]??"";if(!J.test(d)||Number(d)>1)return b(u);let m={tokenFingerprints:t,service:r,forwardHosts:i,sampleRatio:Number(d),connectionString:a};return Object.defineProperty(m,"connectionString",{value:a,enumerable:!1,writable:!1,configurable:!1}),{ok:!0,config:m}}function v(e,n){if(!n)return!1;let t=Buffer.from(V("sha256").update(n,"utf8").digest("hex"));return e.some(r=>{let s=Buffer.from(r);return s.length===t.length&&X(s,t)})}function O(e,n){return!e||!n?null:n}function w(e,n,t){return(t??[]).slice(0,3).map((r,s)=>`${e}.${n}${s+1};dur=${p(r.ms)};desc="${r.desc}"`)}function q(e,n){let t=n,r=[`${e}.total;dur=${p(t.totalMs)}`,`${e}.app;dur=${p($(t))}`,`${e}.db;dur=${p(t.dbMs??0)};desc="${t.dbCount??0} queries"`,...w(e,"db",t.dbTop)];if(f(t.cacheMs)){let o=t.cacheResult?`;desc="${t.cacheResult}"`:"";r.push(`${e}.cache;dur=${p(t.cacheMs)}${o}`)}r.push(`${e}.ext;dur=${p(t.extMs??0)};desc="${t.extCount??0} calls"`,...w(e,"ext",t.extTop),`${e}.render;dur=${p(t.renderMs??0)}`,...w(e,"render",t.renderTop)),f(t.preMs)&&r.push(`${e}.pre;dur=${p(t.preMs)}`),f(t.endpointMs)&&r.push(`${e}.endpoint;dur=${p(t.endpointMs)}`),t.queueMs!==void 0&&r.push(`${e}.queue;dur=${p(t.queueMs)}`),t.bootMs!==void 0&&r.push(`${e}.boot;dur=${p(t.bootMs)}`),t.pluginsMs!==void 0&&r.push(`${e}.plugins;dur=${p(t.pluginsMs)};desc="${t.pluginCount} plugins"`);let s=Object.entries(t.runtime??{}).sort(([o],[i])=>o<i?-1:o>i?1:0);if(s.length>0){let o=s.map(([i,a])=>`${i}=${p(a)}`).join(" ");r.push(`${e}.runtime;desc="${o}"`)}return r.push(`trace;desc="${t.traceId}"`),r.join(", ")}function L(e){let n=new Map,t=null;for(let o of e){let i=S(o.sql);n.set(i,(n.get(i)??0)+1),f(o.rows)&&(t===null||o.rows>t)&&(t=o.rows)}let r=0,s=null;for(let[o,i]of n)i>r&&(r=i,s=o);return{dbCount:e.length,dbRepeatMax:r,dbRepeatSql:s===null?null:s.slice(0,ne),dbRowsMax:t}}function ue(e,n){return e||n>=1||n<=0?1:Math.round(1e4/n)/1e4}function P(e,n,t){let r=e,s={"webority.timing.authorised":n,"webority.sample_rate":ue(n,t),"webority.timing.total_ms":p(r.totalMs),"webority.timing.app_ms":p($(r))},o={db_ms:r.dbMs,cache_ms:r.cacheMs,ext_ms:r.extMs,render_ms:r.renderMs,queue_ms:r.queueMs,boot_ms:r.bootMs,plugins_ms:r.pluginsMs};for(let[a,u]of Object.entries(o))f(u)&&(s[`webority.timing.${a}`]=p(u));let i={db_count:r.dbCount,ext_count:r.extCount,plugin_count:r.pluginCount,db_repeat_max:r.dbRepeatMax,db_repeat_sql:r.dbRepeatSql,db_rows_max:r.dbRowsMax,cache_result:r.cacheResult};for(let[a,u]of Object.entries(i))f(u)&&(s[`webority.timing.${a}`]=u);f(r.memPeakKb)&&(s["webority.mem.peak_kb"]=r.memPeakKb),f(r.cpuMs)&&(s["webority.cpu_ms"]=p(r.cpuMs));for(let[a,u]of Object.entries(r.runtime??{}))s[`webority.runtime.${a}`]=p(u);return s}function N(e){let n=[],t="",r=!1;for(let s of e)s==='"'&&(r=!r),s===","&&!r?(n.push(t.trim()),t=""):t+=s;return n.push(t.trim()),n.filter(s=>s.length>0)}var T=e=>e.startsWith("trace;");function D(e,n){let t=N(e),r=t.filter(T),s=t.filter(u=>!T(u)),o=n.flatMap(N).filter(u=>!T(u)),i=()=>[...s,...o,...r],a=i();for(;o.length>0&&(a.length>ee||a.join(", ").length>te);)o.pop(),a=i();return a.join(", ")}function G(e,n,t){if(!n||!t)return!1;let r=String(t).toLowerCase().replace(/:\d+$/,"");return e.includes(r)}function B(e,n){if(!n)return e.filter(([s])=>!re.has(s.toLowerCase()));let t=[],r=!1;for(let[s,o]of e)s.toLowerCase()!=="cache-control"?t.push([s,o]):r||(t.push(["Cache-Control",A]),r=!0);return r||t.push(["Cache-Control",A]),t}import{createRequire as pe,syncBuiltinESMExports as ce}from"node:module";import{NodeSDK as me}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as fe,TraceIdRatioBasedSampler as le,SamplingDecision as ge}from"@opentelemetry/sdk-trace-base";import{resourceFromAttributes as be}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as he}from"@opentelemetry/semantic-conventions";import{SpanKind as W,trace as Re}from"@opentelemetry/api";import{ClientRequest as z,IncomingMessage as Se}from"node:http";import{HttpInstrumentation as Me}from"@opentelemetry/instrumentation-http";import{MongoDBInstrumentation as we}from"@opentelemetry/instrumentation-mongodb";import{IORedisInstrumentation as Te}from"@opentelemetry/instrumentation-ioredis";import{RedisInstrumentation as xe}from"@opentelemetry/instrumentation-redis";import{MySQL2Instrumentation as ye}from"@opentelemetry/instrumentation-mysql2";import{PgInstrumentation as Ce}from"@opentelemetry/instrumentation-pg";import{UndiciInstrumentation as _e}from"@opentelemetry/instrumentation-undici";import{AzureMonitorTraceExporter as Ee}from"@azure/monitor-opentelemetry-exporter";import{AsyncLocalStorage as de}from"node:async_hooks";var h=new de,g=()=>h.getStore();var F="Webority-Timing-Token",He=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,y=["db.statement","db.query.text"],Ie="db.response.returned_rows",x=500,j=new WeakMap,l=([e,n])=>e*1e3+n/1e6,C=class{inject(){}extract(n,t,r){let s=r.get(t,"traceparent"),o=Array.isArray(s)?s[0]:s,i=typeof o=="string"?He.exec(o):null;if(!i)return n;let[,a,u,d]=i;return a===void 0||u===void 0||d===void 0||!/[1-9a-f]/.test(a)||!/[1-9a-f]/.test(u)?n:Re.setSpanContext(n,{traceId:a,spanId:u,traceFlags:parseInt(d,16),isRemote:!0})}fields(){return["traceparent"]}},_=class{attributes;span;constructor(n,t){this.span=n,this.attributes=t}get name(){return this.span.name}get kind(){return this.span.kind}spanContext(){return this.span.spanContext()}get parentSpanContext(){return this.span.parentSpanContext}get startTime(){return this.span.startTime}get endTime(){return this.span.endTime}get status(){return this.span.status}get links(){return this.span.links}get events(){return this.span.events}get duration(){return this.span.duration}get ended(){return this.span.ended}get resource(){return this.span.resource}get instrumentationScope(){return this.span.instrumentationScope}get droppedAttributesCount(){return this.span.droppedAttributesCount}get droppedEventsCount(){return this.span.droppedEventsCount}get droppedLinksCount(){return this.span.droppedLinksCount}};function ke(e){if(!y.some(t=>typeof e.attributes[t]=="string"))return e;let n={...e.attributes};for(let t of y){let r=n[t];typeof r=="string"&&(n[t]=S(r))}return new _(e,n)}function Ae(e){for(let n of y){let t=e.attributes[n];if(typeof t=="string")return t}return e.name}var E=class{constructor(n){this.inner=n}export(n,t){this.inner.export(n.map(ke),t)}shutdown(){return this.inner.shutdown()}forceFlush(){return this.inner.forceFlush?.()??Promise.resolve()}},H=class{onStart(n){let t=h.getStore();t&&(n.kind===W.SERVER&&!t.serverSpan&&(t.serverSpan=n,n.setAttribute("webority.timing.authorised",t.authorised)),j.set(n,t))}onEnd(n){let t=j.get(n);if(!t)return;let r=n.instrumentationScope.name;if(r.includes("mongodb")||r.includes("mysql2")||r.includes("pg")){t.dbMs+=l(n.duration),t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)]);let s={sql:S(Ae(n))},o=n.attributes[Ie];typeof o=="number"&&(s.rows=o),t.statements.push(s)}else r.includes("ioredis")||r.includes("redis")?(t.cacheMs+=l(n.duration),t.cacheCount+=1,t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)])):n.kind===W.CLIENT&&(r.includes("instrumentation-http")||r.includes("instrumentation-undici"))&&(t.extMs+=l(n.duration),t.extCount+=1,t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)]))}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function Ne(e){let n=new le(e);return{shouldSample(t,r,s,o,i,a){return g()?.authorised?{decision:ge.RECORD_AND_SAMPLED}:n.shouldSample(t,r,s,o,i,a)},toString(){return"WeborityTimingSampler"}}}function $e(e){return e instanceof Se&&(!("req"in e)||e.req===void 0||e.req instanceof z)}function U(e){let{traceId:n,spanId:t,traceFlags:r}=e.spanContext();return`00-${n}-${t}-${r.toString(16).padStart(2,"0")}`}function Mt(e){let n=s=>G(e.forwardHosts,!!g()?.authorised,s),t=new me({resource:be({[he]:e.service}),sampler:Ne(e.sampleRatio),spanProcessors:[new fe(new E(new Ee({connectionString:e.connectionString}))),new H],textMapPropagator:new C,instrumentations:[new Me({requestHook(s,o){let i=g()?.token;!(o instanceof z)||i===void 0||!n(o.host)||(o.setHeader(F,i),o.setHeader("traceparent",U(s)))},responseHook(s,o){let i=g();if(!$e(o))return;let a=o.headers["server-timing"];a&&i&&n(o.req?.host)&&i.inner.push(String(a))}}),new _e({requestHook(s,o){let i=g()?.token;i===void 0||!n(new URL(o.origin).hostname)||(o.addHeader(F,i),o.addHeader("traceparent",U(s)))},responseHook(s,{request:o,response:i}){let a=g();if(!a||!n(new URL(o.origin).hostname))return;let u=i.headers;for(let d=0;d+1<u.length;d+=2){let m=u[d],c=u[d+1];m&&c&&m.toString("latin1").toLowerCase()==="server-timing"&&a.inner.push(c.toString("latin1"))}}}),new we({enhancedDatabaseReporting:!1}),new Te,new xe,new ye,new Ce({enhancedDatabaseReporting:!1})]});t.start();let r=pe(import.meta.url);return r("node:http"),r("node:https"),ce(),t}import k from"node:http";import ve from"node:https";import{getHeapStatistics as Oe}from"node:v8";import{monitorEventLoopDelay as qe}from"node:perf_hooks";var I=1024*1024,Le=6e4,Pe=/^t=(\d+\.\d+)$/,De=/^t=(\d+)$/,M;function Ge(e,n){if(typeof e!="string")return;let t=Pe.exec(e),r=De.exec(e),s;if(t)s=Number(t[1])*1e3;else if(r)s=Number(r[1])/1e3;else return;let o=n-s;return o<0||o>Le?void 0:o}function Be(e,n,t){let r={authorised:e,queueMs:t,startNs:process.hrtime.bigint(),dbMs:0,cacheMs:0,cacheCount:0,extMs:0,extCount:0,statements:[],intervals:[],inner:[],serverSpan:void 0};return e&&Object.defineProperty(r,"token",{value:n,enumerable:!1}),r}function We(){let e=Oe();if(M===void 0)throw new TypeError("Webority server timing: the event loop monitor is not installed");return{eventloop_p99_ms:M.percentile(99)/1e6,heap_used_mb:e.used_heap_size/I,heap_limit_mb:e.heap_size_limit/I,rss_mb:process.memoryUsage.rss()/I}}function Fe(e){let n=0,t=-1/0;for(let[r,s]of[...e].sort((o,i)=>o[0]-i[0])){let o=Math.max(r,t);s>o&&(n+=s-o),t=Math.max(t,s)}return n}function je(e,n){let t=L(e.statements);return{totalMs:Number(process.hrtime.bigint()-e.startNs)/1e6,dbMs:e.dbMs,dbCount:t.dbCount,dbRepeatMax:t.dbRepeatMax,dbRepeatSql:t.dbRepeatSql,dbRowsMax:t.dbRowsMax,cacheMs:e.cacheCount>0?e.cacheMs:void 0,extMs:e.extMs,extCount:e.extCount,busyMs:e.intervals.length>0?Fe(e.intervals):void 0,queueMs:e.queueMs,runtime:We(),traceId:n}}function Ue(e){let n=e.route?.path;return typeof n=="string"?`${e.baseUrl??""}${n}`:void 0}function ze(e){let n=[];for(let t=0;t<e.length;t+=2)n.push([String(e[t]),e[t+1]]);return n}function Ke(e,n){let t=e.getRawHeaderNames().map(o=>[o,e.getHeader(o)]);if(!n)return t;let r=Array.isArray(n)?ze(n):Object.entries(n),s=new Set(r.map(([o])=>o.toLowerCase()));return[...t.filter(([o])=>!s.has(o.toLowerCase())),...r]}function K(e,n){if(n===void 0)throw new TypeError(`Webority server timing: header ${e} has no value`);return n}function Ve(e,n){let t=new Map;for(let[r,s]of n){let o=r.toLowerCase(),i=t.get(o)??{name:r,values:[]};i.values.push(...Array.isArray(s)?s:[s]),t.set(o,i)}for(let r of e.getRawHeaderNames())e.removeHeader(r);for(let{name:r,values:s}of t.values())s.length===1?e.setHeader(r,K(r,s[0])):e.setHeader(r,s.map(o=>String(K(r,o))))}function Xe(e,n,t,r){let s=n.serverSpan;if(!s){if(n.authorised)throw new Error("Webority server timing: an authorised request has no server span");return r}let o=je(n,s.spanContext().traceId),i=Ue(e),a=e.method;if(a===void 0)throw new TypeError("Webority server timing: a request has no method");if(s.updateName(i===void 0?a:`${a} ${i}`),s.setAttribute("http.route",i??"unmatched"),s.setAttributes(P(o,n.authorised,t.sampleRatio)),!n.authorised)return r;let u=D(q(t.service,o),n.inner),d=O(n.authorised,e.headers.origin),c=[...r.filter(([R])=>!["server-timing","timing-allow-origin"].includes(R.toLowerCase())),["Server-Timing",u]];return d!==null&&c.push(["Timing-Allow-Origin",d]),c}function Ye(e){return e instanceof k.ServerResponse&&"getRawHeaderNames"in e&&typeof e.getRawHeaderNames=="function"}function Qe(e,n,t,r){let s=n.writeHead;n.writeHead=function(o,...i){let[a,u]=i,d=typeof a=="string"?a:void 0,m=typeof a=="string"?u:a;if(n.headersSent)return s.call(this,o,d,m);let c=B(Ke(n,m),t.authorised);return o>=200&&(c=Xe(e,t,r,c)),Ve(n,c),s.call(this,o,d)}}function Ht(e){if(M)return;let n=qe({resolution:20});M=n,n.enable(),setInterval(()=>n.reset(),1e4).unref();for(let t of[k.Server,ve.Server]){let r=t.prototype.emit;t.prototype.emit=function(o,...i){if(o!=="request")return r.call(this,o,...i);let[a,u]=i;if(!(a instanceof k.IncomingMessage)||!Ye(u))throw new TypeError("Webority server timing: a request event carries no request and response");let d=a.headers["webority-timing-token"],m=typeof d=="string"?d:void 0,c=v(e.tokenFingerprints,m),R=Be(c,m,Ge(a.headers["x-request-start"],Date.now()));return Qe(a,u,R,e),h.run(R,()=>r.call(this,o,...i))}}}export{S as a,Je as b,v as c,q as d,D as e,G as f,B as g,Mt as h,Ht as i};