@watchtowerobservability/node 0.0.0-stage → 0.2.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.
Files changed (105) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +121 -2
  3. package/dist/cjs/buffer.d.ts +49 -0
  4. package/dist/cjs/buffer.js +134 -0
  5. package/dist/cjs/errors.d.ts +17 -0
  6. package/dist/cjs/errors.js +55 -0
  7. package/dist/cjs/index.d.ts +120 -0
  8. package/dist/cjs/index.js +302 -0
  9. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  10. package/dist/cjs/integrations/azure-functions.js +97 -0
  11. package/dist/cjs/integrations/express.d.ts +25 -0
  12. package/dist/cjs/integrations/express.js +58 -0
  13. package/dist/cjs/integrations/fastify.d.ts +6 -0
  14. package/dist/cjs/integrations/fastify.js +44 -0
  15. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  16. package/dist/cjs/integrations/genai-agents.js +124 -0
  17. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  18. package/dist/cjs/integrations/genai-stream.js +135 -0
  19. package/dist/cjs/integrations/genai.d.ts +18 -0
  20. package/dist/cjs/integrations/genai.js +150 -0
  21. package/dist/cjs/integrations/koa.d.ts +19 -0
  22. package/dist/cjs/integrations/koa.js +34 -0
  23. package/dist/cjs/integrations/lambda.d.ts +11 -0
  24. package/dist/cjs/integrations/lambda.js +68 -0
  25. package/dist/cjs/integrations/logs.d.ts +10 -0
  26. package/dist/cjs/integrations/logs.js +77 -0
  27. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  28. package/dist/cjs/integrations/nestjs.js +30 -0
  29. package/dist/cjs/integrations/next.d.ts +11 -0
  30. package/dist/cjs/integrations/next.js +59 -0
  31. package/dist/cjs/integrations/prisma.d.ts +3 -0
  32. package/dist/cjs/integrations/prisma.js +33 -0
  33. package/dist/cjs/integrations/util.d.ts +9 -0
  34. package/dist/cjs/integrations/util.js +37 -0
  35. package/dist/cjs/jest.d.ts +21 -0
  36. package/dist/cjs/jest.js +45 -0
  37. package/dist/cjs/load.d.ts +1 -0
  38. package/dist/cjs/load.js +11 -0
  39. package/dist/cjs/metrics.d.ts +10 -0
  40. package/dist/cjs/metrics.js +81 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payload.d.ts +42 -0
  43. package/dist/cjs/payload.js +145 -0
  44. package/dist/cjs/probes.d.ts +97 -0
  45. package/dist/cjs/probes.js +422 -0
  46. package/dist/cjs/profiling.d.ts +81 -0
  47. package/dist/cjs/profiling.js +253 -0
  48. package/dist/cjs/reporter-core.d.ts +32 -0
  49. package/dist/cjs/reporter-core.js +102 -0
  50. package/dist/cjs/test-plan.d.ts +93 -0
  51. package/dist/cjs/test-plan.js +262 -0
  52. package/dist/cjs/vitest.d.ts +27 -0
  53. package/dist/cjs/vitest.js +52 -0
  54. package/dist/esm/buffer.d.ts +49 -0
  55. package/dist/esm/buffer.js +92 -0
  56. package/dist/esm/errors.d.ts +17 -0
  57. package/dist/esm/errors.js +50 -0
  58. package/dist/esm/index.d.ts +120 -0
  59. package/dist/esm/index.js +251 -0
  60. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  61. package/dist/esm/integrations/azure-functions.js +60 -0
  62. package/dist/esm/integrations/express.d.ts +25 -0
  63. package/dist/esm/integrations/express.js +54 -0
  64. package/dist/esm/integrations/fastify.d.ts +6 -0
  65. package/dist/esm/integrations/fastify.js +41 -0
  66. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  67. package/dist/esm/integrations/genai-agents.js +118 -0
  68. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  69. package/dist/esm/integrations/genai-stream.js +130 -0
  70. package/dist/esm/integrations/genai.d.ts +18 -0
  71. package/dist/esm/integrations/genai.js +138 -0
  72. package/dist/esm/integrations/koa.d.ts +19 -0
  73. package/dist/esm/integrations/koa.js +31 -0
  74. package/dist/esm/integrations/lambda.d.ts +11 -0
  75. package/dist/esm/integrations/lambda.js +32 -0
  76. package/dist/esm/integrations/logs.d.ts +10 -0
  77. package/dist/esm/integrations/logs.js +40 -0
  78. package/dist/esm/integrations/nestjs.d.ts +16 -0
  79. package/dist/esm/integrations/nestjs.js +26 -0
  80. package/dist/esm/integrations/next.d.ts +11 -0
  81. package/dist/esm/integrations/next.js +22 -0
  82. package/dist/esm/integrations/prisma.d.ts +3 -0
  83. package/dist/esm/integrations/prisma.js +30 -0
  84. package/dist/esm/integrations/util.d.ts +9 -0
  85. package/dist/esm/integrations/util.js +32 -0
  86. package/dist/esm/jest.d.ts +21 -0
  87. package/dist/esm/jest.js +41 -0
  88. package/dist/esm/load.d.ts +1 -0
  89. package/dist/esm/load.js +5 -0
  90. package/dist/esm/metrics.d.ts +10 -0
  91. package/dist/esm/metrics.js +44 -0
  92. package/dist/esm/package.json +1 -0
  93. package/dist/esm/payload.d.ts +42 -0
  94. package/dist/esm/payload.js +131 -0
  95. package/dist/esm/probes.d.ts +97 -0
  96. package/dist/esm/probes.js +412 -0
  97. package/dist/esm/profiling.d.ts +81 -0
  98. package/dist/esm/profiling.js +242 -0
  99. package/dist/esm/reporter-core.d.ts +32 -0
  100. package/dist/esm/reporter-core.js +63 -0
  101. package/dist/esm/test-plan.d.ts +93 -0
  102. package/dist/esm/test-plan.js +248 -0
  103. package/dist/esm/vitest.d.ts +27 -0
  104. package/dist/esm/vitest.js +48 -0
  105. package/package.json +219 -4
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.pinoStream = pinoStream;
37
+ exports.watchtowerTransport = watchtowerTransport;
38
+ // Logs bridges: pino and winston records become OTLP logs carrying the active trace and span ids.
39
+ const wt = __importStar(require("../index.js"));
40
+ const load_js_1 = require("../load.js");
41
+ const defaultSink = { log: (level, body, attrs) => wt.log(level, body, attrs) };
42
+ const PINO = { 10: 'trace', 20: 'debug', 30: 'info', 40: 'warn', 50: 'error', 60: 'fatal' };
43
+ const CORE = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'v']);
44
+ const flat = (o, skip) => {
45
+ const attrs = {};
46
+ for (const [k, v] of Object.entries(o))
47
+ if (!skip || !skip.has(k))
48
+ attrs[k] = typeof v === 'object' ? JSON.stringify(v) : v;
49
+ return attrs;
50
+ };
51
+ /** pino(opts, pinoStream()) or pino.multistream([{ stream: pinoStream() }, { stream: process.stdout }]). */
52
+ function pinoStream(client) {
53
+ return {
54
+ write(line) {
55
+ let r;
56
+ try {
57
+ r = JSON.parse(line);
58
+ }
59
+ catch (_) {
60
+ return;
61
+ }
62
+ (client || defaultSink).log(PINO[r.level] || 'info', r.msg || '', flat(r, CORE));
63
+ },
64
+ };
65
+ }
66
+ const WINSTON = { silly: 'trace', debug: 'debug', verbose: 'debug', http: 'info', info: 'info', warn: 'warn', error: 'error' };
67
+ /** logger.add(watchtowerTransport()). Needs `winston-transport`, which winston always installs. */
68
+ function watchtowerTransport(client) {
69
+ const Transport = (0, load_js_1.load)('winston-transport');
70
+ return new (class extends Transport {
71
+ log(info, cb) {
72
+ const { level, message, ...rest } = info;
73
+ (client || defaultSink).log(WINSTON[level] || 'info', String(message), flat(rest));
74
+ cb();
75
+ }
76
+ })();
77
+ }
@@ -0,0 +1,16 @@
1
+ /** The slice of Nest's ExecutionContext this interceptor reads. */
2
+ export interface NestExecutionContext {
3
+ getClass(): {
4
+ name: string;
5
+ };
6
+ getHandler(): {
7
+ name: string;
8
+ };
9
+ }
10
+ /** app.useGlobalInterceptors(new WatchtowerInterceptor()): captures 5xx errors with controller and handler names.
11
+ * Duck-typed over the rxjs Observable (no rxjs import); pair with the express or fastify integration for spans. */
12
+ export declare class WatchtowerInterceptor {
13
+ intercept(execCtx: NestExecutionContext, next: {
14
+ handle(): any;
15
+ }): any;
16
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WatchtowerInterceptor = void 0;
4
+ const errors_js_1 = require("../errors.js");
5
+ const util_js_1 = require("./util.js");
6
+ /** app.useGlobalInterceptors(new WatchtowerInterceptor()): captures 5xx errors with controller and handler names.
7
+ * Duck-typed over the rxjs Observable (no rxjs import); pair with the express or fastify integration for spans. */
8
+ class WatchtowerInterceptor {
9
+ // `any`: the Observable is rxjs's, which this package deliberately does not import.
10
+ intercept(execCtx, next) {
11
+ const where = {};
12
+ try {
13
+ where['code.namespace'] = execCtx.getClass().name;
14
+ where['code.function'] = execCtx.getHandler().name;
15
+ }
16
+ catch (_) { /* non-http context */ }
17
+ const source = next.handle();
18
+ return source.pipe((src) => new src.constructor((sub) => src.subscribe({
19
+ next: (v) => sub.next(v),
20
+ error: (e) => {
21
+ const status = typeof e.getStatus === 'function' ? e.getStatus() : (0, util_js_1.statusOf)(e);
22
+ if (status >= 500)
23
+ (0, errors_js_1.captureException)(e, { attributes: where });
24
+ sub.error(e);
25
+ },
26
+ complete: () => sub.complete(),
27
+ })));
28
+ }
29
+ }
30
+ exports.WatchtowerInterceptor = WatchtowerInterceptor;
@@ -0,0 +1,11 @@
1
+ /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
2
+ export declare function register(): Promise<void>;
3
+ /** Next.js onRequestError: server render, route handler and server action errors. */
4
+ export declare function onRequestError(err: unknown, request?: {
5
+ path?: string;
6
+ method?: string;
7
+ }, context?: {
8
+ routerKind?: string;
9
+ routePath?: string;
10
+ routeType?: string;
11
+ }): Promise<void>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.register = register;
37
+ exports.onRequestError = onRequestError;
38
+ // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
39
+ const wt = __importStar(require("../index.js"));
40
+ /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
41
+ async function register() {
42
+ const rt = process.env.NEXT_RUNTIME;
43
+ if ((rt && rt !== 'nodejs') || !process.env.WT_INGEST_KEY)
44
+ return;
45
+ wt.init({});
46
+ }
47
+ /** Next.js onRequestError: server render, route handler and server action errors. */
48
+ async function onRequestError(err, request, context) {
49
+ const c = context || {};
50
+ wt.captureException(err, {
51
+ attributes: {
52
+ 'http.request.method': request && request.method,
53
+ 'url.path': request && request.path && String(request.path).split('?')[0],
54
+ 'http.route': c.routePath,
55
+ 'next.router_kind': c.routerKind,
56
+ 'next.route_type': c.routeType,
57
+ },
58
+ });
59
+ }
@@ -0,0 +1,3 @@
1
+ /** prisma.$extends(watchtowerExtension()): a CLIENT span per model operation (no query args recorded: they hold data).
2
+ * shortcut: $queryRaw/$executeRaw are not wrapped; add query.$queryRaw hooks if raw SQL spans are needed. */
3
+ export declare function watchtowerExtension(): object;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.watchtowerExtension = watchtowerExtension;
4
+ const api_1 = require("@opentelemetry/api");
5
+ /** prisma.$extends(watchtowerExtension()): a CLIENT span per model operation (no query args recorded: they hold data).
6
+ * shortcut: $queryRaw/$executeRaw are not wrapped; add query.$queryRaw hooks if raw SQL spans are needed. */
7
+ function watchtowerExtension() {
8
+ return {
9
+ name: 'watchtower',
10
+ query: {
11
+ $allModels: {
12
+ $allOperations({ model, operation, query, args }) {
13
+ return api_1.trace.getTracer('watchtower').startActiveSpan(`prisma ${model}.${operation}`, {
14
+ kind: api_1.SpanKind.CLIENT,
15
+ attributes: { 'db.system.name': 'prisma', 'db.collection.name': model, 'db.operation.name': operation },
16
+ }, async (span) => {
17
+ try {
18
+ return await query(args);
19
+ }
20
+ catch (e) {
21
+ span.recordException(e);
22
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e.message });
23
+ throw e;
24
+ }
25
+ finally {
26
+ span.end();
27
+ }
28
+ });
29
+ },
30
+ },
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context, Span } from '@opentelemetry/api';
2
+ export interface ServerSpan {
3
+ span: Span;
4
+ ctx: Context;
5
+ finish(status?: number, route?: string): void;
6
+ }
7
+ /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
8
+ export declare function serverSpan(method: string, path?: string): ServerSpan;
9
+ export declare const statusOf: (e: unknown) => number;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.statusOf = void 0;
4
+ exports.serverSpan = serverSpan;
5
+ const api_1 = require("@opentelemetry/api");
6
+ /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
7
+ function serverSpan(method, path) {
8
+ // url.path only: query strings can carry secrets
9
+ const span = api_1.trace.getTracer('watchtower').startSpan(method, {
10
+ kind: api_1.SpanKind.SERVER,
11
+ attributes: { 'http.request.method': method, 'url.path': String(path || '').split('?')[0] },
12
+ });
13
+ let done = false;
14
+ return {
15
+ span,
16
+ ctx: api_1.trace.setSpan(api_1.context.active(), span),
17
+ finish(status, route) {
18
+ if (done)
19
+ return;
20
+ done = true;
21
+ if (route) {
22
+ span.updateName(`${method} ${route}`);
23
+ span.setAttribute('http.route', route);
24
+ }
25
+ if (status)
26
+ span.setAttribute('http.response.status_code', status);
27
+ if (status !== undefined && status >= 500)
28
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR });
29
+ span.end();
30
+ },
31
+ };
32
+ }
33
+ const statusOf = (e) => {
34
+ const x = e;
35
+ return (x && (x.status || x.statusCode)) || 500;
36
+ };
37
+ exports.statusOf = statusOf;
@@ -0,0 +1,21 @@
1
+ import type { ReporterOptions } from './reporter-core.js';
2
+ /** The slice of Jest's `TestResult` this reporter reads. */
3
+ export interface JestTestResult {
4
+ testFilePath?: string;
5
+ testResults?: {
6
+ fullName?: string;
7
+ ancestorTitles?: string[];
8
+ title: string;
9
+ status?: string;
10
+ duration?: number | null;
11
+ failureMessages?: string[];
12
+ invocations?: number;
13
+ }[];
14
+ }
15
+ export default class WatchtowerJestReporter {
16
+ private readonly client;
17
+ private readonly tests;
18
+ constructor(_globalConfig?: unknown, options?: ReporterOptions);
19
+ onTestResult(_test: unknown, result: JestTestResult): void;
20
+ onRunComplete(): Promise<void>;
21
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // Jest reporter: `reporters: ['default', ['@watchtowerobservability/node/jest', { /* apiKey, client, ... */ }]]`.
4
+ // With the test-plan environment (test-plan.ts) a quarantined failure arrives as a pending test that
5
+ // still carries its failure message; it is reported as a quarantined failure. Uploads JUnit when
6
+ // WT_CI_RUN_ID is set.
7
+ const reporter_core_js_1 = require("./reporter-core.js");
8
+ const test_plan_js_1 = require("./test-plan.js");
9
+ class WatchtowerJestReporter {
10
+ client;
11
+ tests = [];
12
+ constructor(_globalConfig, options) {
13
+ this.client = (0, reporter_core_js_1.clientFor)(options);
14
+ }
15
+ onTestResult(_test, result) {
16
+ const end = Date.now();
17
+ const decide = (0, test_plan_js_1.decider)((0, test_plan_js_1.loadPlan)());
18
+ for (const t of result.testResults || []) {
19
+ const names = (t.ancestorTitles || []).concat(t.title);
20
+ const id = (0, test_plan_js_1.testId)((0, test_plan_js_1.suiteName)('jest'), result.testFilePath, names);
21
+ const d = decide(id);
22
+ const failures = t.failureMessages || [];
23
+ const qFail = d.quarantined !== undefined && t.status === 'pending' && failures.length > 0;
24
+ this.tests.push({
25
+ name: t.fullName || names.join(' '),
26
+ id,
27
+ outcome: qFail ? 'failed' : (0, reporter_core_js_1.outcome)(t.status),
28
+ durationMs: t.duration || 0,
29
+ message: failures[0],
30
+ endMs: end,
31
+ quarantined: qFail ? d.quarantined : undefined,
32
+ isNew: d.isNew,
33
+ attempts: Math.max(0, (t.invocations || 1) - 1),
34
+ });
35
+ }
36
+ }
37
+ async onRunComplete() {
38
+ await (0, reporter_core_js_1.reportTests)(this.client, this.tests, 'jest');
39
+ await (0, test_plan_js_1.uploadResults)(this.client, (0, test_plan_js_1.suiteName)('jest'), this.tests);
40
+ if (this.client)
41
+ await this.client.shutdown().catch(() => { });
42
+ }
43
+ }
44
+ exports.default = WatchtowerJestReporter;
45
+ module.exports = Object.assign(exports.default, { default: exports.default });
@@ -0,0 +1 @@
1
+ export declare function load(id: string): unknown;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.load = load;
4
+ // Optional-peer loader (winston-transport). This is the CommonJS form; scripts/build.mjs swaps in an ESM twin
5
+ // (createRequire(import.meta.url)) for dist/esm. The cwd fallback only matters when neither exists (test runners).
6
+ const node_module_1 = require("node:module");
7
+ function load(id) {
8
+ if (typeof require === 'function')
9
+ return require(id);
10
+ return (0, node_module_1.createRequire)(`${process.cwd()}/`)(id);
11
+ }
@@ -0,0 +1,10 @@
1
+ import type { Resource } from '@opentelemetry/resources';
2
+ import { MeterProvider } from '@opentelemetry/sdk-metrics';
3
+ import type { PushMetricExporter } from '@opentelemetry/sdk-metrics';
4
+ /** Explicit flag, else `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (default on); `OTEL_*_EXPORTER=none` turns it off. */
5
+ export declare function switchOn(name: string, otelExporterEnv: string, flag?: boolean): boolean;
6
+ export interface Metrics {
7
+ provider: MeterProvider;
8
+ stop(): void;
9
+ }
10
+ export declare function startMetrics(endpoint: string, headers: Record<string, string>, resource: Resource, bufferDir: string | undefined, fetch: typeof globalThis.fetch, exporter?: PushMetricExporter): Metrics;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.switchOn = switchOn;
37
+ exports.startMetrics = startMetrics;
38
+ // Metrics: the OTel metrics SDK with a periodic OTLP/HTTP reader. Counters and histograms use
39
+ // delta temporality unless OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set. Node runtime
40
+ // metrics (event loop delay and utilization, GC, heap) come from the optional peer
41
+ // @opentelemetry/instrumentation-runtime-node when it is installed.
42
+ const nodePath = __importStar(require("node:path"));
43
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
44
+ const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http");
45
+ const buffer_js_1 = require("./buffer.js");
46
+ const load_js_1 = require("./load.js");
47
+ /** Explicit flag, else `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (default on); `OTEL_*_EXPORTER=none` turns it off. */
48
+ function switchOn(name, otelExporterEnv, flag) {
49
+ if (flag !== undefined)
50
+ return flag;
51
+ const env = process.env;
52
+ if ((env[otelExporterEnv] || '').trim().toLowerCase() === 'none')
53
+ return false;
54
+ return !['off', 'false', '0', 'no'].includes((env[name] || 'on').trim().toLowerCase());
55
+ }
56
+ function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter) {
57
+ const url = `${endpoint}/v1/metrics`;
58
+ let exp = exporter;
59
+ if (!exp) {
60
+ const delta = process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE
61
+ ? {} : { temporalityPreference: exporter_metrics_otlp_http_1.AggregationTemporalityPreference.DELTA };
62
+ exp = new exporter_metrics_otlp_http_1.OTLPMetricExporter({ url, headers, ...delta });
63
+ if (bufferDir)
64
+ exp = new buffer_js_1.MetricSpool(exp, nodePath.join(bufferDir, 'metrics'), url, headers, fetch);
65
+ }
66
+ const interval = Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) || 60000;
67
+ const reader = new sdk_metrics_1.PeriodicExportingMetricReader({
68
+ exporter: exp, exportIntervalMillis: interval, exportTimeoutMillis: Math.min(30000, interval),
69
+ });
70
+ const provider = new sdk_metrics_1.MeterProvider({ resource, readers: [reader] });
71
+ let runtime;
72
+ try {
73
+ const mod = (0, load_js_1.load)('@opentelemetry/instrumentation-runtime-node');
74
+ runtime = new mod.RuntimeNodeInstrumentation();
75
+ runtime.setMeterProvider(provider);
76
+ }
77
+ catch {
78
+ // optional peer not installed
79
+ }
80
+ return { provider, stop: () => runtime?.disable() };
81
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,42 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ export interface CaptureRule {
3
+ route?: string | null;
4
+ request_headers?: string[];
5
+ response_headers?: string[];
6
+ body_bytes?: number;
7
+ graphql_query?: boolean;
8
+ }
9
+ export declare const HARD_MAX = 8192;
10
+ export declare const setCaptureRules: (r: CaptureRule[]) => void;
11
+ export declare const captureActive: () => boolean;
12
+ /** Fetch the service's rules; any failure leaves capture off. */
13
+ export declare function loadCaptureRules(o: {
14
+ apiUrl: string;
15
+ key: string;
16
+ service: string;
17
+ fetch?: typeof fetch;
18
+ }): Promise<CaptureRule[]>;
19
+ /** `*` matches any run of characters (the edge's glob). */
20
+ export declare function glob(pat: string, s: string): boolean;
21
+ export declare const ruleFor: (route: string) => CaptureRule | undefined;
22
+ /** Default secret and PII detectors: secret-named JSON and form fields, keys, tokens, emails, SSNs, Luhn-valid cards. */
23
+ export declare function redactText(s: string): string;
24
+ export declare const textLike: (type?: string) => boolean;
25
+ /** First `n` UTF-8 bytes without splitting a character. */
26
+ export declare function capBytes(s: string, n: number): string;
27
+ /** Redact a wider window than kept so a secret cut at the edge is still masked, then cap. */
28
+ export declare const excerpt: (s: string, n: number) => string;
29
+ /** Operation type and name of a GraphQL document (`{ ... }` is an anonymous query). */
30
+ export declare function graphqlOp(doc: string): {
31
+ type: string;
32
+ name?: string;
33
+ } | undefined;
34
+ export interface Payload {
35
+ route: string;
36
+ reqType?: string;
37
+ reqBody?: unknown;
38
+ resType?: string;
39
+ resBody?: unknown;
40
+ }
41
+ /** Record the bodies and GraphQL operation on `span` per the rule matching the route; no rule, nothing recorded. */
42
+ export declare function capturePayload(span: Span, p: Payload): void;
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.excerpt = exports.textLike = exports.ruleFor = exports.captureActive = exports.setCaptureRules = exports.HARD_MAX = void 0;
4
+ exports.loadCaptureRules = loadCaptureRules;
5
+ exports.glob = glob;
6
+ exports.redactText = redactText;
7
+ exports.capBytes = capBytes;
8
+ exports.graphqlOp = graphqlOp;
9
+ exports.capturePayload = capturePayload;
10
+ exports.HARD_MAX = 8192;
11
+ const R = '[REDACTED]';
12
+ let rules = [];
13
+ const setCaptureRules = (r) => { rules = Array.isArray(r) ? r : []; };
14
+ exports.setCaptureRules = setCaptureRules;
15
+ const captureActive = () => rules.length > 0;
16
+ exports.captureActive = captureActive;
17
+ /** Fetch the service's rules; any failure leaves capture off. */
18
+ async function loadCaptureRules(o) {
19
+ try {
20
+ const f = o.fetch || globalThis.fetch;
21
+ const res = await f(`${o.apiUrl}/v1/capture-rules?service=${encodeURIComponent(o.service)}`, {
22
+ headers: { Authorization: `Bearer ${o.key}` },
23
+ });
24
+ if (!res.ok)
25
+ return [];
26
+ const body = (await res.json());
27
+ (0, exports.setCaptureRules)(body.rules || []);
28
+ }
29
+ catch {
30
+ (0, exports.setCaptureRules)([]);
31
+ }
32
+ return rules;
33
+ }
34
+ /** `*` matches any run of characters (the edge's glob). */
35
+ function glob(pat, s) {
36
+ const body = pat.split('*').map((p) => p.replace(/[.+?^$()|{}[\]\\]/g, '\\$&')).join('.*');
37
+ return new RegExp('^' + body + '$', 's').test(s);
38
+ }
39
+ const ruleFor = (route) => rules.find((r) => !r.route || glob(r.route, route));
40
+ exports.ruleFor = ruleFor;
41
+ const luhn = (s) => {
42
+ const d = s.replace(/\D/g, '');
43
+ let sum = 0;
44
+ for (let i = 0; i < d.length; i++) {
45
+ let x = Number(d[d.length - 1 - i]);
46
+ if (i % 2)
47
+ x = x * 2 > 9 ? x * 2 - 9 : x * 2;
48
+ sum += x;
49
+ }
50
+ return d.length >= 13 && sum % 10 === 0;
51
+ };
52
+ const SECRET_KEYS = 'password|passwd|secret|token|access_token|refresh_token|client_secret|api_?key|authorization';
53
+ const PATTERNS = [
54
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
55
+ /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
56
+ /bearer\s+[A-Za-z0-9._~+/-]+=*/gi,
57
+ /wt[ik]_[a-z0-9]{8}_[A-Za-z0-9_-]{43}/g,
58
+ /(?:AKIA|ASIA)[0-9A-Z]{16}/g,
59
+ /gh[pousr]_[A-Za-z0-9]{36,}/g,
60
+ /[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g,
61
+ /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g,
62
+ /\b\d{3}-\d{2}-\d{4}\b/g,
63
+ ];
64
+ /** Default secret and PII detectors: secret-named JSON and form fields, keys, tokens, emails, SSNs, Luhn-valid cards. */
65
+ function redactText(s) {
66
+ let out = s
67
+ .replace(new RegExp(`("(?:${SECRET_KEYS})"\\s*:\\s*)"(?:[^"\\\\]|\\\\.)*"`, 'gi'), `$1"${R}"`)
68
+ .replace(new RegExp(`\\b((?:${SECRET_KEYS})=)[^&\\s]*`, 'gi'), `$1${R}`);
69
+ for (const re of PATTERNS)
70
+ out = out.replace(re, R);
71
+ return out.replace(/\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{1,7}\b/g, (m) => (luhn(m) ? R : m));
72
+ }
73
+ const textLike = (type) => !type || /json|^text\/|xml|x-www-form-urlencoded|graphql/i.test(type);
74
+ exports.textLike = textLike;
75
+ /** First `n` UTF-8 bytes without splitting a character. */
76
+ function capBytes(s, n) {
77
+ const b = Buffer.from(s, 'utf8');
78
+ if (b.length <= n)
79
+ return s;
80
+ return b.subarray(0, n).toString('utf8').replace(/�$/, '');
81
+ }
82
+ /** Redact a wider window than kept so a secret cut at the edge is still masked, then cap. */
83
+ const excerpt = (s, n) => capBytes(redactText(capBytes(s, n * 2)), n);
84
+ exports.excerpt = excerpt;
85
+ /** Operation type and name of a GraphQL document (`{ ... }` is an anonymous query). */
86
+ function graphqlOp(doc) {
87
+ const d = doc.replace(/#[^\n]*/g, '');
88
+ const m = /(?:^|\})\s*(query|mutation|subscription)\b\s*([_A-Za-z][_0-9A-Za-z]*)?/.exec(d);
89
+ if (m)
90
+ return { type: m[1], ...(m[2] ? { name: m[2] } : {}) };
91
+ return /^\s*\{/.test(d) ? { type: 'query' } : undefined;
92
+ }
93
+ const asText = (b) => {
94
+ if (b === undefined || b === null)
95
+ return undefined;
96
+ if (typeof b === 'string')
97
+ return b;
98
+ if (Buffer.isBuffer(b))
99
+ return b.toString('utf8');
100
+ if (typeof b.pipe === 'function')
101
+ return undefined; // a stream: never buffered
102
+ try {
103
+ return JSON.stringify(b);
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ };
109
+ /** Record the bodies and GraphQL operation on `span` per the rule matching the route; no rule, nothing recorded. */
110
+ function capturePayload(span, p) {
111
+ const rule = (0, exports.ruleFor)(p.route);
112
+ if (!rule)
113
+ return;
114
+ const n = Math.min(rule.body_bytes || 0, exports.HARD_MAX);
115
+ const req = (0, exports.textLike)(p.reqType) ? asText(p.reqBody) : undefined;
116
+ const res = (0, exports.textLike)(p.resType) ? asText(p.resBody) : undefined;
117
+ if (n > 0 && req)
118
+ span.setAttribute('http.request.body', (0, exports.excerpt)(req, n));
119
+ if (n > 0 && res)
120
+ span.setAttribute('http.response.body', (0, exports.excerpt)(res, n));
121
+ let doc;
122
+ let opName;
123
+ if (req && /graphql/i.test(p.reqType || ''))
124
+ doc = req;
125
+ else if (req) {
126
+ try {
127
+ const j = (typeof p.reqBody === 'object' ? p.reqBody : JSON.parse(req));
128
+ if (j && typeof j.query === 'string') {
129
+ doc = j.query;
130
+ if (typeof j.operationName === 'string')
131
+ opName = j.operationName;
132
+ }
133
+ }
134
+ catch { /* not JSON */ }
135
+ }
136
+ const op = doc ? graphqlOp(doc) : undefined;
137
+ if (!op || !doc)
138
+ return;
139
+ span.setAttribute('graphql.operation.type', op.type);
140
+ const name = opName || op.name;
141
+ if (name)
142
+ span.setAttribute('graphql.operation.name', name);
143
+ if (rule.graphql_query)
144
+ span.setAttribute('graphql.document', (0, exports.excerpt)(doc, exports.HARD_MAX));
145
+ }