@watchtowerobservability/node 0.0.0-stage → 0.3.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 (181) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +304 -2
  3. package/dist/cjs/appsec.d.ts +95 -0
  4. package/dist/cjs/appsec.js +206 -0
  5. package/dist/cjs/buffer.d.ts +49 -0
  6. package/dist/cjs/buffer.js +134 -0
  7. package/dist/cjs/errors.d.ts +17 -0
  8. package/dist/cjs/errors.js +55 -0
  9. package/dist/cjs/index.d.ts +123 -0
  10. package/dist/cjs/index.js +315 -0
  11. package/dist/cjs/integrations/amqp.d.ts +13 -0
  12. package/dist/cjs/integrations/amqp.js +96 -0
  13. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  14. package/dist/cjs/integrations/azure-functions.js +97 -0
  15. package/dist/cjs/integrations/bullmq.d.ts +19 -0
  16. package/dist/cjs/integrations/bullmq.js +83 -0
  17. package/dist/cjs/integrations/cache.d.ts +13 -0
  18. package/dist/cjs/integrations/cache.js +51 -0
  19. package/dist/cjs/integrations/db.d.ts +62 -0
  20. package/dist/cjs/integrations/db.js +288 -0
  21. package/dist/cjs/integrations/duckdb.d.ts +22 -0
  22. package/dist/cjs/integrations/duckdb.js +66 -0
  23. package/dist/cjs/integrations/express.d.ts +25 -0
  24. package/dist/cjs/integrations/express.js +58 -0
  25. package/dist/cjs/integrations/fastify.d.ts +6 -0
  26. package/dist/cjs/integrations/fastify.js +44 -0
  27. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  28. package/dist/cjs/integrations/genai-agents.js +124 -0
  29. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  30. package/dist/cjs/integrations/genai-stream.js +135 -0
  31. package/dist/cjs/integrations/genai.d.ts +18 -0
  32. package/dist/cjs/integrations/genai.js +150 -0
  33. package/dist/cjs/integrations/graphile-worker.d.ts +22 -0
  34. package/dist/cjs/integrations/graphile-worker.js +50 -0
  35. package/dist/cjs/integrations/koa.d.ts +19 -0
  36. package/dist/cjs/integrations/koa.js +34 -0
  37. package/dist/cjs/integrations/lambda.d.ts +11 -0
  38. package/dist/cjs/integrations/lambda.js +68 -0
  39. package/dist/cjs/integrations/level.d.ts +18 -0
  40. package/dist/cjs/integrations/level.js +71 -0
  41. package/dist/cjs/integrations/lmdb.d.ts +26 -0
  42. package/dist/cjs/integrations/lmdb.js +78 -0
  43. package/dist/cjs/integrations/logs.d.ts +10 -0
  44. package/dist/cjs/integrations/logs.js +77 -0
  45. package/dist/cjs/integrations/messaging.d.ts +17 -0
  46. package/dist/cjs/integrations/messaging.js +73 -0
  47. package/dist/cjs/integrations/mqtt.d.ts +7 -0
  48. package/dist/cjs/integrations/mqtt.js +41 -0
  49. package/dist/cjs/integrations/nats.d.ts +17 -0
  50. package/dist/cjs/integrations/nats.js +73 -0
  51. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  52. package/dist/cjs/integrations/nestjs.js +30 -0
  53. package/dist/cjs/integrations/next.d.ts +11 -0
  54. package/dist/cjs/integrations/next.js +59 -0
  55. package/dist/cjs/integrations/orm.d.ts +47 -0
  56. package/dist/cjs/integrations/orm.js +93 -0
  57. package/dist/cjs/integrations/pg-boss.d.ts +8 -0
  58. package/dist/cjs/integrations/pg-boss.js +63 -0
  59. package/dist/cjs/integrations/pools.d.ts +41 -0
  60. package/dist/cjs/integrations/pools.js +94 -0
  61. package/dist/cjs/integrations/postgres.d.ts +12 -0
  62. package/dist/cjs/integrations/postgres.js +92 -0
  63. package/dist/cjs/integrations/prisma.d.ts +3 -0
  64. package/dist/cjs/integrations/prisma.js +33 -0
  65. package/dist/cjs/integrations/sqlite.d.ts +36 -0
  66. package/dist/cjs/integrations/sqlite.js +125 -0
  67. package/dist/cjs/integrations/util.d.ts +9 -0
  68. package/dist/cjs/integrations/util.js +37 -0
  69. package/dist/cjs/jest.d.ts +21 -0
  70. package/dist/cjs/jest.js +45 -0
  71. package/dist/cjs/load.d.ts +1 -0
  72. package/dist/cjs/load.js +11 -0
  73. package/dist/cjs/metrics.d.ts +10 -0
  74. package/dist/cjs/metrics.js +81 -0
  75. package/dist/cjs/package.json +1 -0
  76. package/dist/cjs/payload.d.ts +42 -0
  77. package/dist/cjs/payload.js +145 -0
  78. package/dist/cjs/pprof.d.ts +6 -0
  79. package/dist/cjs/pprof.js +88 -0
  80. package/dist/cjs/probes.d.ts +97 -0
  81. package/dist/cjs/probes.js +422 -0
  82. package/dist/cjs/profiling.d.ts +84 -0
  83. package/dist/cjs/profiling.js +263 -0
  84. package/dist/cjs/reporter-core.d.ts +32 -0
  85. package/dist/cjs/reporter-core.js +102 -0
  86. package/dist/cjs/sql.d.ts +19 -0
  87. package/dist/cjs/sql.js +332 -0
  88. package/dist/cjs/test-plan.d.ts +102 -0
  89. package/dist/cjs/test-plan.js +352 -0
  90. package/dist/cjs/vitest.d.ts +27 -0
  91. package/dist/cjs/vitest.js +52 -0
  92. package/dist/esm/appsec.d.ts +95 -0
  93. package/dist/esm/appsec.js +193 -0
  94. package/dist/esm/buffer.d.ts +49 -0
  95. package/dist/esm/buffer.js +92 -0
  96. package/dist/esm/errors.d.ts +17 -0
  97. package/dist/esm/errors.js +50 -0
  98. package/dist/esm/index.d.ts +123 -0
  99. package/dist/esm/index.js +264 -0
  100. package/dist/esm/integrations/amqp.d.ts +13 -0
  101. package/dist/esm/integrations/amqp.js +92 -0
  102. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  103. package/dist/esm/integrations/azure-functions.js +60 -0
  104. package/dist/esm/integrations/bullmq.d.ts +19 -0
  105. package/dist/esm/integrations/bullmq.js +79 -0
  106. package/dist/esm/integrations/cache.d.ts +13 -0
  107. package/dist/esm/integrations/cache.js +46 -0
  108. package/dist/esm/integrations/db.d.ts +62 -0
  109. package/dist/esm/integrations/db.js +239 -0
  110. package/dist/esm/integrations/duckdb.d.ts +22 -0
  111. package/dist/esm/integrations/duckdb.js +29 -0
  112. package/dist/esm/integrations/express.d.ts +25 -0
  113. package/dist/esm/integrations/express.js +54 -0
  114. package/dist/esm/integrations/fastify.d.ts +6 -0
  115. package/dist/esm/integrations/fastify.js +41 -0
  116. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  117. package/dist/esm/integrations/genai-agents.js +118 -0
  118. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  119. package/dist/esm/integrations/genai-stream.js +130 -0
  120. package/dist/esm/integrations/genai.d.ts +18 -0
  121. package/dist/esm/integrations/genai.js +138 -0
  122. package/dist/esm/integrations/graphile-worker.d.ts +22 -0
  123. package/dist/esm/integrations/graphile-worker.js +46 -0
  124. package/dist/esm/integrations/koa.d.ts +19 -0
  125. package/dist/esm/integrations/koa.js +31 -0
  126. package/dist/esm/integrations/lambda.d.ts +11 -0
  127. package/dist/esm/integrations/lambda.js +32 -0
  128. package/dist/esm/integrations/level.d.ts +18 -0
  129. package/dist/esm/integrations/level.js +35 -0
  130. package/dist/esm/integrations/lmdb.d.ts +26 -0
  131. package/dist/esm/integrations/lmdb.js +42 -0
  132. package/dist/esm/integrations/logs.d.ts +10 -0
  133. package/dist/esm/integrations/logs.js +40 -0
  134. package/dist/esm/integrations/messaging.d.ts +17 -0
  135. package/dist/esm/integrations/messaging.js +64 -0
  136. package/dist/esm/integrations/mqtt.d.ts +7 -0
  137. package/dist/esm/integrations/mqtt.js +38 -0
  138. package/dist/esm/integrations/nats.d.ts +17 -0
  139. package/dist/esm/integrations/nats.js +70 -0
  140. package/dist/esm/integrations/nestjs.d.ts +16 -0
  141. package/dist/esm/integrations/nestjs.js +26 -0
  142. package/dist/esm/integrations/next.d.ts +11 -0
  143. package/dist/esm/integrations/next.js +22 -0
  144. package/dist/esm/integrations/orm.d.ts +47 -0
  145. package/dist/esm/integrations/orm.js +86 -0
  146. package/dist/esm/integrations/pg-boss.d.ts +8 -0
  147. package/dist/esm/integrations/pg-boss.js +60 -0
  148. package/dist/esm/integrations/pools.d.ts +41 -0
  149. package/dist/esm/integrations/pools.js +89 -0
  150. package/dist/esm/integrations/postgres.d.ts +12 -0
  151. package/dist/esm/integrations/postgres.js +55 -0
  152. package/dist/esm/integrations/prisma.d.ts +3 -0
  153. package/dist/esm/integrations/prisma.js +30 -0
  154. package/dist/esm/integrations/sqlite.d.ts +36 -0
  155. package/dist/esm/integrations/sqlite.js +84 -0
  156. package/dist/esm/integrations/util.d.ts +9 -0
  157. package/dist/esm/integrations/util.js +32 -0
  158. package/dist/esm/jest.d.ts +21 -0
  159. package/dist/esm/jest.js +41 -0
  160. package/dist/esm/load.d.ts +1 -0
  161. package/dist/esm/load.js +5 -0
  162. package/dist/esm/metrics.d.ts +10 -0
  163. package/dist/esm/metrics.js +44 -0
  164. package/dist/esm/package.json +1 -0
  165. package/dist/esm/payload.d.ts +42 -0
  166. package/dist/esm/payload.js +131 -0
  167. package/dist/esm/pprof.d.ts +6 -0
  168. package/dist/esm/pprof.js +85 -0
  169. package/dist/esm/probes.d.ts +97 -0
  170. package/dist/esm/probes.js +412 -0
  171. package/dist/esm/profiling.d.ts +84 -0
  172. package/dist/esm/profiling.js +251 -0
  173. package/dist/esm/reporter-core.d.ts +32 -0
  174. package/dist/esm/reporter-core.js +63 -0
  175. package/dist/esm/sql.d.ts +19 -0
  176. package/dist/esm/sql.js +324 -0
  177. package/dist/esm/test-plan.d.ts +102 -0
  178. package/dist/esm/test-plan.js +336 -0
  179. package/dist/esm/vitest.d.ts +27 -0
  180. package/dist/esm/vitest.js +48 -0
  181. package/package.json +379 -4
@@ -0,0 +1,18 @@
1
+ import type { DbOptions } from './db.js';
2
+ interface LevelDb {
3
+ location?: string;
4
+ sublevel?(...a: unknown[]): object;
5
+ }
6
+ /**
7
+ * `instrumentLevel(new ClassicLevel(dir))`, or `instrumentLevel(rocksdb(dir), { system: 'rocksdb' })`:
8
+ * a span per `get`/`getMany`/`put`/`del`/`batch`/`clear` (promise or callback form; keys and values
9
+ * are never recorded), on the db and on its sublevels (`db.collection.name`). With `metrics` (default
10
+ * on) and a `location`, `wt.embedded.file.size` reports the size of the store's directory.
11
+ * Returns `stop()` for the gauge.
12
+ * shortcut: iterators and the chained `batch()` builder are not traced.
13
+ */
14
+ export declare function instrumentLevel(db: LevelDb, opts?: DbOptions & {
15
+ system?: 'leveldb' | 'rocksdb';
16
+ metrics?: boolean;
17
+ }): () => void;
18
+ export {};
@@ -0,0 +1,71 @@
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.instrumentLevel = instrumentLevel;
37
+ const nodePath = __importStar(require("node:path"));
38
+ const db_js_1 = require("./db.js");
39
+ const OPS = ['get', 'getMany', 'put', 'del', 'batch', 'clear'];
40
+ /**
41
+ * `instrumentLevel(new ClassicLevel(dir))`, or `instrumentLevel(rocksdb(dir), { system: 'rocksdb' })`:
42
+ * a span per `get`/`getMany`/`put`/`del`/`batch`/`clear` (promise or callback form; keys and values
43
+ * are never recorded), on the db and on its sublevels (`db.collection.name`). With `metrics` (default
44
+ * on) and a `location`, `wt.embedded.file.size` reports the size of the store's directory.
45
+ * Returns `stop()` for the gauge.
46
+ * shortcut: iterators and the chained `batch()` builder are not traced.
47
+ */
48
+ function instrumentLevel(db, opts) {
49
+ const system = opts?.system ?? 'leveldb';
50
+ const namespace = db.location ? nodePath.basename(db.location) : undefined;
51
+ const wrap = (d, collection) => {
52
+ for (const m of OPS) {
53
+ (0, db_js_1.patch)(d, m, (orig) => function (...a) {
54
+ if (m === 'batch' && a.length === 0)
55
+ return orig.call(this); // chained builder
56
+ return (0, db_js_1.tracedCb)({ system, operation: m, collection, namespace }, opts, a, (args) => orig.apply(this, args));
57
+ });
58
+ }
59
+ (0, db_js_1.patch)(d, 'sublevel', (orig) => function (...a) {
60
+ const sub = orig.apply(this, a);
61
+ if (sub)
62
+ wrap(sub, typeof a[0] === 'string' ? a[0] : undefined);
63
+ return sub;
64
+ });
65
+ };
66
+ wrap(db);
67
+ const dir = db.location;
68
+ if (opts?.metrics === false || !dir)
69
+ return () => { };
70
+ return (0, db_js_1.observeEmbedded)(system, namespace, ['file.size'], () => ({ 'file.size': (0, db_js_1.sizeOf)(dir) }));
71
+ }
@@ -0,0 +1,26 @@
1
+ import type { DbOptions } from './db.js';
2
+ interface LmdbStats {
3
+ pageSize?: number;
4
+ mapSize?: number;
5
+ lastPageNumber?: number;
6
+ entryCount?: number;
7
+ numReaders?: number;
8
+ }
9
+ interface LmdbDb {
10
+ path?: string;
11
+ name?: string;
12
+ getStats?(): LmdbStats;
13
+ openDB?(...a: unknown[]): object;
14
+ }
15
+ /**
16
+ * `instrumentLmdb(open({ path }))` (lmdb-js): spans for async writes (`put`, `remove`, `ifVersion`,
17
+ * `ifNoExists`, `clearAsync`, `drop`), `getMany` and `transaction` (calls inside a transaction get
18
+ * child spans), on the root and on every `openDB` sub-database (`db.collection.name`). Sync reads
19
+ * (`get`) are memory-mapped and take microseconds, so they get no span. With `metrics` (default on)
20
+ * it also reports `wt.embedded.map.size`, `.map.used`, `.entries`, `.readers` and `.file.size`.
21
+ * Returns `stop()` for the gauges.
22
+ */
23
+ export declare function instrumentLmdb(db: LmdbDb, opts?: DbOptions & {
24
+ metrics?: boolean;
25
+ }): () => void;
26
+ export {};
@@ -0,0 +1,78 @@
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.instrumentLmdb = instrumentLmdb;
37
+ const nodePath = __importStar(require("node:path"));
38
+ const db_js_1 = require("./db.js");
39
+ const WRITES = ['put', 'remove', 'ifVersion', 'ifNoExists', 'clearAsync', 'drop', 'getMany', 'prefetch'];
40
+ /**
41
+ * `instrumentLmdb(open({ path }))` (lmdb-js): spans for async writes (`put`, `remove`, `ifVersion`,
42
+ * `ifNoExists`, `clearAsync`, `drop`), `getMany` and `transaction` (calls inside a transaction get
43
+ * child spans), on the root and on every `openDB` sub-database (`db.collection.name`). Sync reads
44
+ * (`get`) are memory-mapped and take microseconds, so they get no span. With `metrics` (default on)
45
+ * it also reports `wt.embedded.map.size`, `.map.used`, `.entries`, `.readers` and `.file.size`.
46
+ * Returns `stop()` for the gauges.
47
+ */
48
+ function instrumentLmdb(db, opts) {
49
+ const namespace = db.path ? nodePath.basename(db.path) : undefined;
50
+ const wrap = (d, collection) => {
51
+ for (const m of WRITES) {
52
+ (0, db_js_1.patch)(d, m, (orig) => function (...a) {
53
+ return (0, db_js_1.traced)({ system: 'lmdb', operation: m, collection, namespace }, opts, () => orig.apply(this, a));
54
+ });
55
+ }
56
+ (0, db_js_1.patch)(d, 'transaction', (orig) => function (...a) {
57
+ return (0, db_js_1.traced)({ system: 'lmdb', operation: 'transaction', collection, namespace }, opts, () => orig.apply(this, a), false);
58
+ });
59
+ (0, db_js_1.patch)(d, 'openDB', (orig) => function (...a) {
60
+ const sub = orig.apply(this, a);
61
+ const name = typeof a[0] === 'string' ? a[0] : a[0]?.name;
62
+ if (sub)
63
+ wrap(sub, name ?? sub.name);
64
+ return sub;
65
+ });
66
+ };
67
+ wrap(db);
68
+ if (opts?.metrics === false || typeof db.getStats !== 'function')
69
+ return () => { };
70
+ return (0, db_js_1.observeEmbedded)('lmdb', namespace, ['map.size', 'map.used', 'entries', 'readers', 'file.size'], () => {
71
+ const s = db.getStats();
72
+ const used = s.pageSize !== undefined && s.lastPageNumber !== undefined ? (s.lastPageNumber + 1) * s.pageSize : undefined;
73
+ return {
74
+ 'map.size': s.mapSize, 'map.used': used, entries: s.entryCount, readers: s.numReaders,
75
+ 'file.size': db.path ? (0, db_js_1.sizeOf)(db.path) : undefined,
76
+ };
77
+ });
78
+ }
@@ -0,0 +1,10 @@
1
+ /** Anything with a `log` method, e.g. a `Client`. */
2
+ export interface LogSink {
3
+ log(level: string, body: string, attrs?: Record<string, unknown>): void;
4
+ }
5
+ /** pino(opts, pinoStream()) or pino.multistream([{ stream: pinoStream() }, { stream: process.stdout }]). */
6
+ export declare function pinoStream(client?: LogSink): {
7
+ write(line: string): void;
8
+ };
9
+ /** logger.add(watchtowerTransport()). Needs `winston-transport`, which winston always installs. */
10
+ export declare function watchtowerTransport(client?: LogSink): object;
@@ -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,17 @@
1
+ import type { Attributes } from '@opentelemetry/api';
2
+ /** Key in job data that carries the producer's trace context (W3C `traceparent`/`tracestate`). */
3
+ export declare const CONTEXT_KEY = "_wt";
4
+ export declare function isPlainObject(v: unknown): v is Record<string, unknown>;
5
+ /** The active context as W3C headers. */
6
+ export declare function headers(): Record<string, string>;
7
+ /** Copy of `data` carrying the active context under `_wt`; non-object data is returned unchanged. */
8
+ export declare function injectData(data: unknown): unknown;
9
+ /** Remove and return the `_wt` carrier from object job data. */
10
+ export declare function takeContext(data: unknown): Record<string, unknown> | undefined;
11
+ /** A PRODUCER span around `fn`, which gets the headers to send (the producer span's context). */
12
+ export declare function produce<T>(name: string, attributes: Attributes, fn: (h: Record<string, string>) => T): T;
13
+ /**
14
+ * A CONSUMER span around `fn`, linked to the producer context of each carrier (header maps whose
15
+ * values may be strings or Buffers). With exactly one carrier the producer span is also the parent.
16
+ */
17
+ export declare function consume<T>(name: string, attributes: Attributes, carriers: Array<Record<string, unknown> | undefined>, fn: () => T): T;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTEXT_KEY = void 0;
4
+ exports.isPlainObject = isPlainObject;
5
+ exports.headers = headers;
6
+ exports.injectData = injectData;
7
+ exports.takeContext = takeContext;
8
+ exports.produce = produce;
9
+ exports.consume = consume;
10
+ // Shared core for queue and broker integrations: PRODUCER spans that hand out W3C headers, and
11
+ // CONSUMER spans parented by (and linked to) the producer, so the server can compute lag.
12
+ const api_1 = require("@opentelemetry/api");
13
+ const db_js_1 = require("./db.js");
14
+ /** Key in job data that carries the producer's trace context (W3C `traceparent`/`tracestate`). */
15
+ exports.CONTEXT_KEY = '_wt';
16
+ function isPlainObject(v) {
17
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
18
+ }
19
+ /** The active context as W3C headers. */
20
+ function headers() {
21
+ const carrier = {};
22
+ api_1.propagation.inject(api_1.context.active(), carrier);
23
+ return carrier;
24
+ }
25
+ /** Copy of `data` carrying the active context under `_wt`; non-object data is returned unchanged. */
26
+ function injectData(data) {
27
+ if (data !== undefined && !isPlainObject(data))
28
+ return data;
29
+ const carrier = headers();
30
+ return Object.keys(carrier).length ? { ...data, [exports.CONTEXT_KEY]: carrier } : data;
31
+ }
32
+ /** Remove and return the `_wt` carrier from object job data. */
33
+ function takeContext(data) {
34
+ if (!isPlainObject(data) || !isPlainObject(data[exports.CONTEXT_KEY]))
35
+ return undefined;
36
+ const c = data[exports.CONTEXT_KEY];
37
+ delete data[exports.CONTEXT_KEY];
38
+ return c;
39
+ }
40
+ /** A PRODUCER span around `fn`, which gets the headers to send (the producer span's context). */
41
+ function produce(name, attributes, fn) {
42
+ const parent = api_1.context.active();
43
+ if ((0, db_js_1.inside)(parent))
44
+ return fn(headers());
45
+ const span = api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.PRODUCER, attributes }, parent);
46
+ return (0, db_js_1.settle)(span, () => api_1.context.with((0, db_js_1.enter)(parent, span), () => fn(headers())));
47
+ }
48
+ const str = (v) => (typeof v === 'string' ? v : v instanceof Uint8Array ? Buffer.from(v).toString() : undefined);
49
+ /**
50
+ * A CONSUMER span around `fn`, linked to the producer context of each carrier (header maps whose
51
+ * values may be strings or Buffers). With exactly one carrier the producer span is also the parent.
52
+ */
53
+ function consume(name, attributes, carriers, fn) {
54
+ let parent = api_1.context.active();
55
+ const links = [];
56
+ for (const c of carriers) {
57
+ if (!c)
58
+ continue;
59
+ const tp = str(c.traceparent);
60
+ if (!tp)
61
+ continue;
62
+ const ts = str(c.tracestate);
63
+ const ctx = api_1.propagation.extract(parent, { traceparent: tp, ...(ts ? { tracestate: ts } : {}) });
64
+ const sc = api_1.trace.getSpanContext(ctx);
65
+ if (!sc || !api_1.trace.isSpanContextValid(sc))
66
+ continue;
67
+ links.push({ context: sc });
68
+ if (carriers.length === 1)
69
+ parent = ctx;
70
+ }
71
+ const span = api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.CONSUMER, attributes, links }, parent);
72
+ return (0, db_js_1.settle)(span, () => api_1.context.with((0, db_js_1.enter)(parent, span, false), fn));
73
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `instrumentMqtt(mqtt.connect(url))` for mqtt.js: PRODUCER spans on `publish`/`publishAsync`, and a
3
+ * CONSUMER span around the client's `message` listeners. The trace context travels in MQTT 5 user
4
+ * properties, so only `protocolVersion: 5` clients propagate (older clients get unlinked spans).
5
+ * shortcut: `publish` spans end when the call returns, not at the QoS 1/2 ack; use `publishAsync` for ack time.
6
+ */
7
+ export declare function instrumentMqtt(client: object): void;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instrumentMqtt = instrumentMqtt;
4
+ const db_js_1 = require("./db.js");
5
+ const messaging_js_1 = require("./messaging.js");
6
+ const attrs = (topic, type, op, payload, id) => ({
7
+ 'messaging.system': 'mqtt',
8
+ 'messaging.destination.name': topic,
9
+ 'messaging.operation.type': type,
10
+ 'messaging.operation.name': op,
11
+ ...(typeof payload === 'string' || payload instanceof Uint8Array ? { 'messaging.message.body.size': payload.length } : {}),
12
+ ...(id !== undefined ? { 'messaging.message.id': String(id) } : {}),
13
+ });
14
+ /**
15
+ * `instrumentMqtt(mqtt.connect(url))` for mqtt.js: PRODUCER spans on `publish`/`publishAsync`, and a
16
+ * CONSUMER span around the client's `message` listeners. The trace context travels in MQTT 5 user
17
+ * properties, so only `protocolVersion: 5` clients propagate (older clients get unlinked spans).
18
+ * shortcut: `publish` spans end when the call returns, not at the QoS 1/2 ack; use `publishAsync` for ack time.
19
+ */
20
+ function instrumentMqtt(client) {
21
+ const v5 = () => client.options?.protocolVersion === 5;
22
+ (0, db_js_1.patch)(client, 'publish', (orig) => function (topic, message, opts, cb) {
23
+ if (typeof opts === 'function')
24
+ [cb, opts] = [opts, undefined];
25
+ return (0, messaging_js_1.produce)(`publish ${topic}`, attrs(topic, 'send', 'publish', message), (h) => {
26
+ const o = opts;
27
+ const out = v5() ? { ...o, properties: { ...o?.properties, userProperties: { ...o?.properties?.userProperties, ...h } } } : o;
28
+ return cb === undefined ? orig.call(this, topic, message, out) : orig.call(this, topic, message, out ?? {}, cb);
29
+ });
30
+ });
31
+ // publishAsync calls publish, which then injects the context of this span
32
+ (0, db_js_1.patch)(client, 'publishAsync', (orig) => function (topic, message, ...rest) {
33
+ return (0, messaging_js_1.produce)(`publish ${topic}`, attrs(topic, 'send', 'publishAsync', message), () => orig.call(this, topic, message, ...rest));
34
+ });
35
+ (0, db_js_1.patch)(client, 'emit', (orig) => function (event, ...args) {
36
+ if (event !== 'message')
37
+ return orig.call(this, event, ...args);
38
+ const [topic, payload, packet] = args;
39
+ return (0, messaging_js_1.consume)(`process ${topic}`, attrs(topic, 'process', 'message', payload, packet?.messageId), [packet?.properties?.userProperties], () => orig.call(this, event, ...args));
40
+ });
41
+ }
@@ -0,0 +1,17 @@
1
+ interface MsgHdrs {
2
+ get(k: string): string;
3
+ set(k: string, v: string): void;
4
+ }
5
+ interface NatsModule {
6
+ headers(): MsgHdrs;
7
+ }
8
+ /**
9
+ * `instrumentNats(nc, nats)` (`import * as nats from 'nats'`; `nc = await nats.connect()`): patches the
10
+ * connection class. `publish`/`request` get PRODUCER spans with the context in NATS headers;
11
+ * `subscribe` messages get CONSUMER spans (child of and linked to the producer). With a `callback`
12
+ * subscription the span is active in the callback. With `for await (const m of sub)` each span runs
13
+ * from receipt to the next iteration and is not active in the loop body (child spans there are not
14
+ * parented to it; the producer link still gives lag).
15
+ */
16
+ export declare function instrumentNats(nc: object, nats: NatsModule): void;
17
+ export {};
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instrumentNats = instrumentNats;
4
+ const db_js_1 = require("./db.js");
5
+ const messaging_js_1 = require("./messaging.js");
6
+ const attrs = (subject, type, op, data, queue) => ({
7
+ 'messaging.system': 'nats',
8
+ 'messaging.destination.name': subject,
9
+ 'messaging.operation.type': type,
10
+ 'messaging.operation.name': op,
11
+ ...(typeof data?.length === 'number' ? { 'messaging.message.body.size': data.length } : {}),
12
+ ...(queue ? { 'messaging.consumer.group.name': queue } : {}),
13
+ });
14
+ const carrier = (m) => ({ traceparent: m.headers?.get('traceparent'), tracestate: m.headers?.get('tracestate') });
15
+ /**
16
+ * `instrumentNats(nc, nats)` (`import * as nats from 'nats'`; `nc = await nats.connect()`): patches the
17
+ * connection class. `publish`/`request` get PRODUCER spans with the context in NATS headers;
18
+ * `subscribe` messages get CONSUMER spans (child of and linked to the producer). With a `callback`
19
+ * subscription the span is active in the callback. With `for await (const m of sub)` each span runs
20
+ * from receipt to the next iteration and is not active in the loop body (child spans there are not
21
+ * parented to it; the producer link still gives lag).
22
+ */
23
+ function instrumentNats(nc, nats) {
24
+ const proto = Object.getPrototypeOf(nc);
25
+ const withHeaders = (o, h) => {
26
+ const hdrs = o?.headers ?? nats.headers();
27
+ for (const [k, v] of Object.entries(h))
28
+ hdrs.set(k, v);
29
+ return { ...o, headers: hdrs };
30
+ };
31
+ (0, db_js_1.patch)(proto, 'publish', (orig) => function (subject, data, o) {
32
+ return (0, messaging_js_1.produce)(`send ${subject}`, attrs(subject, 'send', 'publish', data), (h) => orig.call(this, subject, data, withHeaders(o, h)));
33
+ });
34
+ (0, db_js_1.patch)(proto, 'request', (orig) => function (subject, data, o) {
35
+ return (0, messaging_js_1.produce)(`send ${subject}`, attrs(subject, 'send', 'request', data), (h) => orig.call(this, subject, data, withHeaders(o, h)));
36
+ });
37
+ (0, db_js_1.patch)(proto, 'subscribe', (orig) => function (subject, o) {
38
+ const cb = o?.callback;
39
+ if (typeof cb === 'function') {
40
+ const callback = (err, m) => (err || !m
41
+ ? cb(err, m)
42
+ : (0, messaging_js_1.consume)(`process ${m.subject}`, attrs(m.subject, 'process', 'subscribe', m.data, o?.queue), [carrier(m)], () => cb(err, m)));
43
+ return orig.call(this, subject, { ...o, callback });
44
+ }
45
+ const sub = orig.call(this, subject, o);
46
+ const iter = sub[Symbol.asyncIterator]?.bind(sub);
47
+ if (!iter)
48
+ return sub;
49
+ sub[Symbol.asyncIterator] = () => {
50
+ const inner = iter();
51
+ let end;
52
+ const close = () => { end?.(); end = undefined; };
53
+ return {
54
+ async next() {
55
+ close();
56
+ const r = await inner.next();
57
+ if (!r.done) {
58
+ const m = r.value;
59
+ // the span ends when this promise resolves, i.e. on the next iteration or return
60
+ void (0, messaging_js_1.consume)(`process ${m.subject}`, attrs(m.subject, 'process', 'subscribe', m.data, o?.queue), [carrier(m)], () => new Promise((res) => { end = res; }));
61
+ }
62
+ return r;
63
+ },
64
+ async return(v) {
65
+ close();
66
+ return inner.return ? inner.return(v) : { done: true, value: v };
67
+ },
68
+ [Symbol.asyncIterator]() { return this; },
69
+ };
70
+ };
71
+ return sub;
72
+ });
73
+ }
@@ -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
+ }