@zigordev/otel 0.0.0-stage → 1.8.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 (50) hide show
  1. package/README.md +328 -2
  2. package/dist/diagnostics.d.ts +9 -0
  3. package/dist/diagnostics.d.ts.map +1 -0
  4. package/dist/diagnostics.js +29 -0
  5. package/dist/diagnostics.js.map +1 -0
  6. package/dist/health.d.ts +25 -0
  7. package/dist/health.d.ts.map +1 -0
  8. package/dist/health.js +31 -0
  9. package/dist/health.js.map +1 -0
  10. package/dist/index.d.ts +12 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +8 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/loader-hooks.d.ts +2 -0
  15. package/dist/loader-hooks.d.ts.map +1 -0
  16. package/dist/loader-hooks.js +14 -0
  17. package/dist/loader-hooks.js.map +1 -0
  18. package/dist/logger.d.ts +12 -0
  19. package/dist/logger.d.ts.map +1 -0
  20. package/dist/logger.js +56 -0
  21. package/dist/logger.js.map +1 -0
  22. package/dist/metrics.d.ts +3 -0
  23. package/dist/metrics.d.ts.map +1 -0
  24. package/dist/metrics.js +9 -0
  25. package/dist/metrics.js.map +1 -0
  26. package/dist/output.d.ts +4 -0
  27. package/dist/output.d.ts.map +1 -0
  28. package/dist/output.js +63 -0
  29. package/dist/output.js.map +1 -0
  30. package/dist/privacy.d.ts +5 -0
  31. package/dist/privacy.d.ts.map +1 -0
  32. package/dist/privacy.js +34 -0
  33. package/dist/privacy.js.map +1 -0
  34. package/dist/process-events.d.ts +5 -0
  35. package/dist/process-events.d.ts.map +1 -0
  36. package/dist/process-events.js +19 -0
  37. package/dist/process-events.js.map +1 -0
  38. package/dist/register.d.ts +2 -0
  39. package/dist/register.d.ts.map +1 -0
  40. package/dist/register.js +5 -0
  41. package/dist/register.js.map +1 -0
  42. package/dist/route.d.ts +2 -0
  43. package/dist/route.d.ts.map +1 -0
  44. package/dist/route.js +9 -0
  45. package/dist/route.js.map +1 -0
  46. package/dist/telemetry.d.ts +18 -0
  47. package/dist/telemetry.d.ts.map +1 -0
  48. package/dist/telemetry.js +101 -0
  49. package/dist/telemetry.js.map +1 -0
  50. package/package.json +59 -3
package/README.md CHANGED
@@ -1,3 +1,329 @@
1
- # Temporary Holding Version
1
+ # @zigordev/otel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Telemetry for a service, the same in every one: traces and metrics through OpenTelemetry, log lines that carry the trace, and the answer of the health route.
4
+
5
+ ## What it is
6
+
7
+ Telemetry is what a running app reports about itself. It comes in three kinds:
8
+
9
+ | Kind | What it is | Example |
10
+ | -------- | ------------------------------------------------------------------------------- | ----------------------------------------- |
11
+ | Trace | The journey of one request, as timed steps. One step is called a span | A request, its database query, its call |
12
+ | Metric | A number that is counted or measured over time | Requests by route, and how long they took |
13
+ | Log line | One thing that happened, written as one line of JSON, the usual format for data | `pool.created` |
14
+
15
+ OpenTelemetry is the open standard for traces and metrics, and the library that records them. pino is the logger that writes the JSON lines. This package sets both up one way, so a service does not.
16
+
17
+ | Export | What it does |
18
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
19
+ | `@zigordev/otel/register` | Captures the output and starts telemetry when Node.js loads it with `--import`, before the app's own code |
20
+ | `startTelemetry(options?)` | The same start, for an app that adds an instrumentation of its own |
21
+ | `shutdownTelemetry()` | Sends what the service still holds, then stops. A service calls it before it exits |
22
+ | `createLogger(options)` | The logger: one JSON line per event, on standard output |
23
+ | `logStarted`, `logStopping`, `logProcessCrashes` | The standard events that every service writes |
24
+ | `captureOutput(logger?)` | Turns what `console` prints, and what Node.js warns of, into JSON lines. The register entry calls it |
25
+ | `checkHealth(options)` | Works out the answer of `GET /health` from the parts the service depends on |
26
+ | `createCounterAtZero(meter, name, options, known)` | A counter whose known series all start at 0 |
27
+ | `nameRoute(route)` | Tells telemetry which route the request in progress matched, such as `/api/v1/pools/:poolId` |
28
+ | `isProbeRequest(url)` | Says whether a path is a probe, which leaves no trace |
29
+
30
+ An instrumentation is code that records telemetry for a library, such as the database driver, without the app writing any. A probe is a request that only asks whether the app is alive.
31
+
32
+ ## Why we have it
33
+
34
+ Every app on the platform promises four things that this package keeps for a TypeScript service. [The platform](../../docs/handbook/the-platform.md) lists them as promises 3 to 6: answer `GET /health`, write logs as JSON lines with no personal data, send traces and metrics under its own name, and stop cleanly.
35
+
36
+ Without the package, three things go wrong:
37
+
38
+ - Each service wires OpenTelemetry its own way, and the names differ. One dashboard and one set of alerts cover every app only because every app reports under the same names.
39
+ - The rules that keep telemetry worth reading live in a document, and a service forgets one. Here they are code: nothing personal, no trace for a probe, no trace for background work.
40
+ - A service loses its last seconds of telemetry at every stop, because nothing sends them before it exits.
41
+
42
+ ## How it works here
43
+
44
+ ### The start
45
+
46
+ Telemetry starts before the app's own code:
47
+
48
+ ```bash
49
+ node --import @zigordev/otel/register src/main.ts
50
+ ```
51
+
52
+ The order matters. The instrumentations wrap a module at the moment Node.js loads it, so they have to be in place first. For that the start installs loader hooks, which are functions that Node.js calls for each module it loads. It takes them from the copy of `import-in-the-middle` that OpenTelemetry's own instrumentation uses, so one process never holds two.
53
+
54
+ From then on a service records, by itself:
55
+
56
+ | What | As |
57
+ | -------------------------------------------------- | ---------------------------------------------------------------- |
58
+ | Each request that comes in | A span, and the metric `http.server.request.duration` |
59
+ | Each request it makes, with `fetch` or `node:http` | A span, and the metric `http.client.request.duration` |
60
+ | Each PostgreSQL query | A span, and the numbers of the connection pool |
61
+ | The Node.js runtime | Metrics of the event loop, the memory and the garbage collection |
62
+
63
+ A span and a duration are worth little under the raw path, because every id makes a path of its own. The app's web framework knows the pattern that a request matched, and passes it on with `nameRoute`. The span is then named `GET /api/v1/pools/:poolId`, and the duration metric carries the pattern as `http.route`.
64
+
65
+ It sends them over OTLP, the protocol of OpenTelemetry, to the telemetry agent: spans every 5 seconds and metrics every 60. Logs never travel that way. The agent reads them from the container's output.
66
+
67
+ The start reads the standard variables of OpenTelemetry:
68
+
69
+ | Variable | Holds |
70
+ | ----------------------------- | ----------------------------------------------------------------------------------------------- |
71
+ | `OTEL_SERVICE_NAME` | The app's one name, `<product>-<part>`, such as `gpool-api` |
72
+ | `OTEL_SERVICE_VERSION` | The version that is running. It becomes `service.version` |
73
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | The agent's address. `http://localhost:4318` when it is not set |
74
+ | `OTEL_RESOURCE_ATTRIBUTES` | More facts about the service, such as `deployment.environment.name=production` |
75
+ | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/json` sends JSON, which a person can read. Anything else sends protobuf, a compact format |
76
+ | `OTEL_SDK_DISABLED` | `true` switches telemetry off, for a unit test |
77
+ | `OTEL_EXPORTER_OTLP_TIMEOUT` | How long one send may take, in milliseconds. 10000 when it is not set |
78
+ | `OTEL_LOG_LEVEL` | How much OpenTelemetry says about itself. Warnings and errors when it is not set |
79
+
80
+ Nothing differs between the laptop and production. A service sends to the agent in both, and only the agent knows where the data goes next.
81
+
82
+ Every span and every metric says who sent it. The start names the service, its version and one id for each running copy, the process with its Node.js version, the operating system, and the host. In a container the host's name is the container's id. The id of the machine is never read: on a laptop it is the hardware's own number, and in a container there is none. `OTEL_NODE_RESOURCE_DETECTORS` is not read, so these facts are the same everywhere.
83
+
84
+ ### The rules it keeps
85
+
86
+ - **A probe leaves no trace.** A request to `/health`, `/favicon.ico` or `/_next/static/` gets no span, whichever part of the app would start one.
87
+ - **Background work starts no trace.** A query or an outgoing request gets a span only inside another span, so a timer that polls does not fill the store. A background task that is worth a trace starts its own span.
88
+ - **Every trace is kept.** Nothing is sampled, so `OTEL_TRACES_SAMPLER` is not read.
89
+ - **Nothing identifies a visitor.** Before a span leaves the service, it loses the visitor's address, the user agent and the query string. A web address keeps only what comes before its `?`.
90
+ - **Starting twice does nothing.** The second call returns the first one's handle.
91
+ - **A stop never fails over telemetry.** `shutdownTelemetry()` sends what the service still holds. When the agent cannot be reached, it waits until the send gives up, says so in a line at the level `warn`, and returns as usual.
92
+ - **Every line is a JSON line.** What a library prints with `console`, what OpenTelemetry says about itself and what Node.js warns of all become lines of the same shape as the service's own.
93
+
94
+ The attributes a span loses are `client.address`, `client.port`, `network.peer.address`, `network.peer.port`, `url.query` and `user_agent.original`, and their older names. `url.full`, `http.url` and `http.target` are cut at the query.
95
+
96
+ ### Logs
97
+
98
+ Each line is one JSON object on standard output:
99
+
100
+ | Field | Present | Holds |
101
+ | ----------- | ----------------------------------------------------- | ----------------------------------------------- |
102
+ | `timestamp` | Always | The time in UTC, as ISO 8601 |
103
+ | `level` | Always | `debug`, `info`, `warn` or `error` |
104
+ | `service` | Always | The app's name, the same as `OTEL_SERVICE_NAME` |
105
+ | `release` | When it is given | The version, the same as `OTEL_SERVICE_VERSION` |
106
+ | `event` | On an event line | The event's name |
107
+ | `message` | On a message line | Free text |
108
+ | `traceId` | Inside a request | The trace this line belongs to |
109
+ | `spanId` | Inside a request | The step of that trace |
110
+ | `error` | On a failure | The error's `name`, `message` and `stack` |
111
+ | `source` | On a line that the service's own logger did not write | `console` or `opentelemetry` |
112
+
113
+ Any other field that the code passes sits at the top level, beside these.
114
+
115
+ A field named `password`, `token`, `secret`, `authorization` or `cookie` is written as `[redacted]`, at the top level and one level down. It is a last defence: a secret or personal data does not belong in a log line at all.
116
+
117
+ A level means the same in every service:
118
+
119
+ | Level | Means |
120
+ | ------- | --------------------------------------------------------------- |
121
+ | `error` | Something failed that a person should look at |
122
+ | `warn` | Something went wrong and the app handled it: a retry, a refusal |
123
+ | `info` | The service's life and its business events |
124
+ | `debug` | Detail for a run on the laptop. Production filters it out |
125
+
126
+ An event is named `area.what_happened`, in lower case, such as `pool.created`. Dashboards and alerts search for these names, so a name never changes its meaning, and a new outcome gets a new name. Three functions write the events that every service has:
127
+
128
+ | Function | Event | When |
129
+ | ------------------- | ----------------------------------------------------------- | ------------------------------------------------- |
130
+ | `logStarted` | `service.started` | Once, when the service is ready |
131
+ | `logStopping` | `service.stopping` | On the signal that asks it to stop |
132
+ | `logProcessCrashes` | `process.uncaught_exception`, `process.unhandled_rejection` | Before the process dies of an error nobody caught |
133
+
134
+ The register entry writes one more by itself, `process.warning`, whenever Node.js warns.
135
+
136
+ `logProcessCrashes` only watches. Node.js still ends the process, as it would without it.
137
+
138
+ ### What a library prints
139
+
140
+ A library does not know the service's logger. Next.js prints a few lines as it starts, OpenTelemetry reports its own failures, and Node.js warns of a function that is going away. Left alone, each of them is plain text, and the agent cannot tell its level.
141
+
142
+ The register entry therefore captures the output before any other code runs. Each of these becomes one JSON line on standard output, with the service's name and version, and with the trace when it is printed inside a request:
143
+
144
+ | What writes | The line it becomes |
145
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
146
+ | `console.log`, `console.info`, `console.dir` | `info`, with `"source":"console"` and the text as `message` |
147
+ | `console.debug`, `console.trace` | `debug`. A trace keeps the stack of its caller |
148
+ | `console.warn` | `warn` |
149
+ | `console.error` | `error`. An error that is printed keeps its stack, inside `message` |
150
+ | A warning of Node.js | `warn`, with the event `process.warning`, the warning as `error`, and its `code` when it has one |
151
+ | OpenTelemetry about itself | `warn` or `error`, with `"source":"opentelemetry"`. A failure to send comes with the failure as `error` |
152
+
153
+ The other `console` methods, such as `console.table` and `console.assert`, are built on these, so they are caught too.
154
+
155
+ A line of the service's own logger has no `source`. Searching the logs for `source="console"` therefore shows what libraries print, and any call to `console` that was left in our own code.
156
+
157
+ Two things can still be plain text:
158
+
159
+ - **A crash.** Node.js prints the error itself when the process dies of one that nobody caught, after the `process.uncaught_exception` line.
160
+ - **OpenTelemetry while it starts**, before its logger is in place. At the usual level it writes then only to complain about a setting, such as an unknown name in `OTEL_PROPAGATORS`. With `OTEL_LOG_LEVEL=debug`, its first lines are plain text.
161
+
162
+ ### Health
163
+
164
+ `checkHealth` asks each part the service depends on, and answers for the whole:
165
+
166
+ | Answer | Code | Means |
167
+ | ---------- | ---- | ------------------------------------------------------------ |
168
+ | `ok` | 200 | Every part is up |
169
+ | `degraded` | 200 | A part that is not required is down. The service still works |
170
+ | `error` | 503 | A required part is down. The service cannot do its job |
171
+
172
+ A part reports `up`, `down` or `unknown`. `unknown` means nothing has tried it yet, and it does not count as failing. A check that throws, or that takes longer than 800 ms, counts as `down`, so the route answers in under a second.
173
+
174
+ ```json
175
+ {
176
+ "status": "ok",
177
+ "service": "gpool-api",
178
+ "components": { "db": { "status": "up" } }
179
+ }
180
+ ```
181
+
182
+ ### Counters
183
+
184
+ A counter that is created at its first event starts at 1, and a dashboard then misses that first event. `createCounterAtZero` creates every series it is told about at 0, when the service starts.
185
+
186
+ ## How to use it
187
+
188
+ Add the package, and the OpenTelemetry API that it shares with the app:
189
+
190
+ ```bash
191
+ pnpm add @zigordev/otel @opentelemetry/api
192
+ ```
193
+
194
+ pnpm stops an install when a dependency brings an install script that nobody has decided about. One comes with OpenTelemetry, in `protobufjs`, and nothing here needs it. Refuse it in the repo's `pnpm-workspace.yaml`:
195
+
196
+ ```yaml
197
+ allowBuilds:
198
+ protobufjs: false
199
+ ```
200
+
201
+ The worked example is the whole `src/main.ts` of a small service. Its settings come from [`@zigordev/config`](../config/README.md):
202
+
203
+ ```ts
204
+ import { createServer } from 'node:http';
205
+ import {
206
+ checkHealth,
207
+ createLogger,
208
+ logProcessCrashes,
209
+ logStarted,
210
+ logStopping,
211
+ shutdownTelemetry,
212
+ } from '@zigordev/otel';
213
+ import { config } from './config.ts';
214
+
215
+ const logger = createLogger({
216
+ service: config.OTEL_SERVICE_NAME,
217
+ release: config.OTEL_SERVICE_VERSION,
218
+ level: config.LOG_LEVEL,
219
+ });
220
+ logProcessCrashes(logger);
221
+
222
+ const server = createServer(async (request, response) => {
223
+ if (request.url === '/health') {
224
+ const report = await checkHealth({ service: config.OTEL_SERVICE_NAME, components: [] });
225
+ response.writeHead(report.statusCode, { 'content-type': 'application/json' });
226
+ response.end(JSON.stringify(report.body));
227
+ return;
228
+ }
229
+ logger.info({ event: 'greeting.sent' });
230
+ response.end('hello');
231
+ });
232
+
233
+ server.listen(config.PORT, () => logStarted(logger, { port: config.PORT }));
234
+
235
+ process.once('SIGTERM', () => {
236
+ logStopping(logger, 'SIGTERM');
237
+ server.close(async () => {
238
+ await shutdownTelemetry();
239
+ process.exit(0);
240
+ });
241
+ });
242
+ ```
243
+
244
+ Start it with `node --import @zigordev/otel/register src/main.ts`. A request to `/` then leaves one span, one count in `http.server.request.duration` and one log line that carries the span's trace. A request to `/health` leaves none of the three.
245
+
246
+ A dependency becomes a part of the health answer. `required` says whether the service can work without it:
247
+
248
+ ```ts
249
+ const report = await checkHealth({
250
+ service: config.OTEL_SERVICE_NAME,
251
+ components: [{ name: 'db', required: true, check: pingDatabase }],
252
+ });
253
+ ```
254
+
255
+ A number of the business is a counter. Give it every value its attributes can take:
256
+
257
+ ```ts
258
+ import { metrics } from '@opentelemetry/api';
259
+ import { createCounterAtZero } from '@zigordev/otel';
260
+
261
+ const actions = createCounterAtZero(
262
+ metrics.getMeter('gpool-api'),
263
+ 'gpool.pool.actions',
264
+ { description: 'Pool actions' },
265
+ [{ action: 'create' }, { action: 'join' }]
266
+ );
267
+
268
+ actions.add(1, { action: 'join' });
269
+ ```
270
+
271
+ An attribute holds a value from a short, fixed list: an outcome or a route pattern, never an id, an address or a raw path.
272
+
273
+ A web framework names the route once it has matched the request. In Fastify that is one hook:
274
+
275
+ ```ts
276
+ import { nameRoute } from '@zigordev/otel';
277
+
278
+ app.addHook('onRequest', async (request) => {
279
+ const route = request.routeOptions.url;
280
+ if (route !== undefined) {
281
+ nameRoute(route);
282
+ }
283
+ });
284
+ ```
285
+
286
+ A request that matches no route gets no name. Its raw path would be a new value each time, and a metric must not carry one.
287
+
288
+ An app that needs one more instrumentation writes its own start file, and loads that file with `--import` in place of the register entry:
289
+
290
+ ```ts
291
+ import { startTelemetry } from '@zigordev/otel';
292
+
293
+ startTelemetry({ instrumentations: [frameworkInstrumentation] });
294
+ ```
295
+
296
+ ## How to check that it works
297
+
298
+ | Try this | What must happen |
299
+ | ---------------------------------------------------- | ---------------------------------------------------------------------------------- |
300
+ | Start the service and read its output | The first line is JSON and has `"event":"service.started"` |
301
+ | Print with `console.log` anywhere in the service | One JSON line with `"source":"console"` appears, and nothing on the error output |
302
+ | Call a route, then search for the service in Grafana | A trace shows the request as a span, with its queries and calls beneath it |
303
+ | Log inside a request | The line has a `traceId`, and searching for that id finds the trace |
304
+ | Call `/health` | It answers 200 with `"status":"ok"`, and no trace appears |
305
+ | Call a route with `?email=ada@example.com` | The span has the path, and neither the address nor the user agent nor the email |
306
+ | Send the service a SIGTERM | It writes `service.stopping`, exits with code 0, and its last spans still arrive |
307
+ | Make a required part fail, then call `/health` | It answers 503 with `"status":"error"`, and the body names the part that is `down` |
308
+
309
+ The package's own test does the first seven in a real process, against a stand-in for the agent:
310
+
311
+ ```bash
312
+ pnpm exec vitest run packages/otel/src/telemetry.e2e.test.ts
313
+ ```
314
+
315
+ When no telemetry arrives, the service cannot reach the agent, and OpenTelemetry says so in lines at the level `error`, with `"source":"opentelemetry"`. Check `OTEL_EXPORTER_OTLP_ENDPOINT`, and that `OTEL_SDK_DISABLED` is not set.
316
+
317
+ When a stop takes about ten seconds, the agent cannot be reached either, and the last send waits until it gives up. The service still exits with code 0. A smaller `OTEL_EXPORTER_OTLP_TIMEOUT` shortens the wait.
318
+
319
+ When requests leave no span at all, the service started without `--import`, so the instrumentations came too late.
320
+
321
+ When a query is missing from a trace, it ran outside a request. Background work starts no trace unless it starts a span of its own.
322
+
323
+ When every request of a service shows as plain `GET` or `POST`, nothing names the route. Call `nameRoute` from the framework, as shown above.
324
+
325
+ When a log line has no `traceId`, it was written outside a request, or inside a probe.
326
+
327
+ When telemetry arrives under a name that starts with `unknown_service`, `OTEL_SERVICE_NAME` is not set.
328
+
329
+ When a dashboard misses the first event after a start, the counter was created at that event. Create it with `createCounterAtZero`.
@@ -0,0 +1,9 @@
1
+ import type { DiagLogger } from '@opentelemetry/api';
2
+ import type { ErrorHandler } from '@opentelemetry/core';
3
+ import type { Logger } from './logger.ts';
4
+ export interface Diagnostics {
5
+ readonly logger: DiagLogger;
6
+ readonly onError: ErrorHandler;
7
+ }
8
+ export declare function createDiagnostics(logger: Logger): Diagnostics;
9
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../src/diagnostics.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAI1C,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;CAChC;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CA4B7D"}
@@ -0,0 +1,29 @@
1
+ import { format } from 'node:util';
2
+ export function createDiagnostics(logger) {
3
+ const lines = logger.child({ source: 'opentelemetry' });
4
+ const write = (level) => (message, ...values) => {
5
+ const last = values.at(-1);
6
+ if (last instanceof Error) {
7
+ lines[level]({ error: last }, format(message, ...values.slice(0, -1)));
8
+ return;
9
+ }
10
+ lines[level](format(message, ...values));
11
+ };
12
+ return {
13
+ logger: {
14
+ error: write('error'),
15
+ warn: write('warn'),
16
+ info: write('info'),
17
+ debug: write('debug'),
18
+ verbose: write('debug'),
19
+ },
20
+ onError: (failure) => {
21
+ if (failure instanceof Error) {
22
+ lines.error({ error: failure }, failure.message);
23
+ return;
24
+ }
25
+ lines.error(format(failure));
26
+ },
27
+ };
28
+ }
29
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../src/diagnostics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WA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@
1
+ export type ComponentStatus = 'up' | 'down' | 'unknown';
2
+ export type HealthStatus = 'ok' | 'degraded' | 'error';
3
+ export interface HealthComponent {
4
+ readonly name: string;
5
+ readonly required: boolean;
6
+ readonly check: () => ComponentStatus | Promise<ComponentStatus>;
7
+ }
8
+ export interface HealthBody {
9
+ readonly status: HealthStatus;
10
+ readonly service: string;
11
+ readonly components: Readonly<Record<string, {
12
+ readonly status: ComponentStatus;
13
+ }>>;
14
+ }
15
+ export interface HealthReport {
16
+ readonly statusCode: 200 | 503;
17
+ readonly body: HealthBody;
18
+ }
19
+ export interface CheckHealthOptions {
20
+ readonly service: string;
21
+ readonly components: readonly HealthComponent[];
22
+ readonly timeoutMs?: number;
23
+ }
24
+ export declare function checkHealth(options: CheckHealthOptions): Promise<HealthReport>;
25
+ //# sourceMappingURL=health.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../src/health.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,eAAe,GAAG,IAAI,GAAG,MAAM,GAAG,SAAS,CAAC;AACxD,MAAM,MAAM,YAAY,GAAG,IAAI,GAAG,UAAU,GAAG,OAAO,CAAC;AAEvD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;CAClE;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;KAAE,CAAC,CAAC,CAAC;CACrF;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,UAAU,EAAE,GAAG,GAAG,GAAG,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,SAAS,eAAe,EAAE,CAAC;IAChD,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAgBD,wBAAsB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CAsBpF"}
package/dist/health.js ADDED
@@ -0,0 +1,31 @@
1
+ async function runCheck(component, timeoutMs) {
2
+ let timer;
3
+ const timeout = new Promise((resolve) => {
4
+ timer = setTimeout(() => resolve('down'), timeoutMs);
5
+ });
6
+ try {
7
+ return await Promise.race([Promise.resolve().then(component.check), timeout]);
8
+ }
9
+ catch {
10
+ return 'down';
11
+ }
12
+ finally {
13
+ clearTimeout(timer);
14
+ }
15
+ }
16
+ export async function checkHealth(options) {
17
+ const timeoutMs = options.timeoutMs ?? 800;
18
+ const results = await Promise.all(options.components.map(async (component) => ({
19
+ component,
20
+ status: await runCheck(component, timeoutMs),
21
+ })));
22
+ const components = Object.fromEntries(results.map(({ component, status }) => [component.name, { status }]));
23
+ const requiredDown = results.some(({ component, status }) => component.required && status === 'down');
24
+ const optionalDown = results.some(({ component, status }) => !component.required && status === 'down');
25
+ const status = requiredDown ? 'error' : optionalDown ? 'degraded' : 'ok';
26
+ return {
27
+ statusCode: requiredDown ? 503 : 200,
28
+ body: { status, service: options.service, components },
29
+ };
30
+ }
31
+ //# sourceMappingURL=health.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.js","sourceRoot":"","sources":["../src/health.ts"],"names":[],"mappings":"AA0BA,KAAK,UAAU,QAAQ,CAAC,SAA0B,EAAE,SAAiB;IACnE,IAAI,KAAiC,CAAC;IACtC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAkB,CA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AAE,CAAC,CAAC,SAAS,CAAC,QAAQ,IAAI,MAAM,KAAK,MAAM,CACpE,CAAC;IACF,MAAM,MAAM,GAAiB,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;IACvF,OAAO;QACL,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;QACpC,IAAI,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE;KACvD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,12 @@
1
+ export type { CheckHealthOptions, ComponentStatus, HealthBody, HealthComponent, HealthReport, HealthStatus, } from './health.ts';
2
+ export { checkHealth } from './health.ts';
3
+ export type { Logger, LoggerOptions, LogLevel } from './logger.ts';
4
+ export { createLogger } from './logger.ts';
5
+ export { createCounterAtZero } from './metrics.ts';
6
+ export type { RestoreOutput } from './output.ts';
7
+ export { captureOutput } from './output.ts';
8
+ export { logProcessCrashes, logStarted, logStopping } from './process-events.ts';
9
+ export { nameRoute } from './route.ts';
10
+ export type { Telemetry, TelemetryOptions } from './telemetry.ts';
11
+ export { isProbeRequest, shutdownTelemetry, startTelemetry } from './telemetry.ts';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,eAAe,EACf,YAAY,EACZ,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { checkHealth } from './health.js';
2
+ export { createLogger } from './logger.js';
3
+ export { createCounterAtZero } from './metrics.js';
4
+ export { captureOutput } from './output.js';
5
+ export { logProcessCrashes, logStarted, logStopping } from './process-events.js';
6
+ export { nameRoute } from './route.js';
7
+ export { isProbeRequest, shutdownTelemetry, startTelemetry } from './telemetry.js';
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare function installLoaderHooks(): void;
2
+ //# sourceMappingURL=loader-hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-hooks.d.ts","sourceRoot":"","sources":["../src/loader-hooks.ts"],"names":[],"mappings":"AAUA,wBAAgB,kBAAkB,IAAI,IAAI,CAUzC"}
@@ -0,0 +1,14 @@
1
+ import { createRequire } from 'node:module';
2
+ const installedKey = Symbol.for('zigordev.otel.loader-hooks');
3
+ export function installLoaderHooks() {
4
+ const holder = globalThis;
5
+ if (holder[installedKey]) {
6
+ return;
7
+ }
8
+ const fromHere = createRequire(import.meta.url);
9
+ const fromInstrumentation = createRequire(fromHere.resolve('@opentelemetry/instrumentation'));
10
+ const hooks = fromInstrumentation('import-in-the-middle/register-hooks.mjs');
11
+ hooks.register();
12
+ holder[installedKey] = true;
13
+ }
14
+ //# sourceMappingURL=loader-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-hooks.js","sourceRoot":"","sources":["../src/loader-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAM5C,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAI9D,MAAM,UAAU,kBAAkB;IAChC,MAAM,MAAM,GAAG,UAAyB,CAAC;IACzC,IAAI,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC;QACzB,OAAO;IACT,CAAC;IACD,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IAChD,MAAM,mBAAmB,GAAG,aAAa,CAAC,QAAQ,CAAC,OAAO,CAAC,gCAAgC,CAAC,CAAC,CAAC;IAC9F,MAAM,KAAK,GAAG,mBAAmB,CAAC,yCAAyC,CAAgB,CAAC;IAC5F,KAAK,CAAC,QAAQ,EAAE,CAAC;IACjB,MAAM,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { type DestinationStream, type Logger } from 'pino';
2
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
3
+ export interface LoggerOptions {
4
+ readonly service: string;
5
+ readonly release?: string | undefined;
6
+ readonly level?: LogLevel | undefined;
7
+ readonly destination?: DestinationStream;
8
+ }
9
+ export type { Logger };
10
+ export declare function createLogger(options: LoggerOptions): Logger;
11
+ export declare function createProcessLogger(): Logger;
12
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,iBAAiB,EAAe,KAAK,MAAM,EAAQ,MAAM,MAAM,CAAC;AAE9E,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAE3D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,WAAW,CAAC,EAAE,iBAAiB,CAAC;CAC1C;AAED,YAAY,EAAE,MAAM,EAAE,CAAC;AAoCvB,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAiB3D;AAED,wBAAgB,mBAAmB,IAAI,MAAM,CAM5C"}
package/dist/logger.js ADDED
@@ -0,0 +1,56 @@
1
+ import { TraceFlags, trace } from '@opentelemetry/api';
2
+ import { destination, pino } from 'pino';
3
+ const redactedPaths = [
4
+ 'password',
5
+ 'token',
6
+ 'secret',
7
+ 'authorization',
8
+ 'cookie',
9
+ '*.password',
10
+ '*.token',
11
+ '*.secret',
12
+ '*.authorization',
13
+ '*.cookie',
14
+ 'headers.authorization',
15
+ 'headers.cookie',
16
+ ];
17
+ function traceFields() {
18
+ const span = trace.getActiveSpan();
19
+ if (span === undefined) {
20
+ return {};
21
+ }
22
+ const context = span.spanContext();
23
+ if ((context.traceFlags & TraceFlags.SAMPLED) === 0) {
24
+ return {};
25
+ }
26
+ return { traceId: context.traceId, spanId: context.spanId };
27
+ }
28
+ function serializeError(value) {
29
+ if (value instanceof Error) {
30
+ return { name: value.name, message: value.message, stack: value.stack };
31
+ }
32
+ return value;
33
+ }
34
+ export function createLogger(options) {
35
+ return pino({
36
+ level: options.level ?? 'info',
37
+ messageKey: 'message',
38
+ errorKey: 'error',
39
+ base: options.release
40
+ ? { service: options.service, release: options.release }
41
+ : { service: options.service },
42
+ timestamp: () => `,"timestamp":"${new Date().toISOString()}"`,
43
+ formatters: { level: (label) => ({ level: label }) },
44
+ serializers: { error: serializeError },
45
+ mixin: traceFields,
46
+ redact: { paths: redactedPaths, censor: '[redacted]' },
47
+ }, options.destination ?? destination({ fd: 1, sync: true }));
48
+ }
49
+ export function createProcessLogger() {
50
+ return createLogger({
51
+ service: process.env.OTEL_SERVICE_NAME || 'unknown_service',
52
+ release: process.env.OTEL_SERVICE_VERSION || undefined,
53
+ level: 'debug',
54
+ });
55
+ }
56
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAA0B,WAAW,EAAe,IAAI,EAAE,MAAM,MAAM,CAAC;AAa9E,MAAM,aAAa,GAAG;IACpB,UAAU;IACV,OAAO;IACP,QAAQ;IACR,eAAe;IACf,QAAQ;IACR,YAAY;IACZ,SAAS;IACT,UAAU;IACV,iBAAiB;IACjB,UAAU;IACV,uBAAuB;IACvB,gBAAgB;CACjB,CAAC;AAEF,SAAS,WAAW;IAClB,MAAM,IAAI,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC;IACnC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,OAA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AAO,CAAC,WAAW,IAAI,WAAW,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,mBAAmB;IACjC,OAAO,YAAY,CAAC;QAClB,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,iBAAiB;QAC3D,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,SAAS;QACtD,KAAK,EAAE,OAAO;KACf,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Attributes, Counter, Meter, MetricOptions } from '@opentelemetry/api';
2
+ export declare function createCounterAtZero(meter: Meter, name: string, options: MetricOptions, knownAttributes?: readonly Attributes[]): Counter;
3
+ //# sourceMappingURL=metrics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEpF,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,EACtB,eAAe,GAAE,SAAS,UAAU,EAAO,GAC1C,OAAO,CAOT"}
@@ -0,0 +1,9 @@
1
+ export function createCounterAtZero(meter, name, options, knownAttributes = []) {
2
+ const counter = meter.createCounter(name, options);
3
+ const sets = knownAttributes.length > 0 ? knownAttributes : [{}];
4
+ for (const attributes of sets) {
5
+ counter.add(0, attributes);
6
+ }
7
+ return counter;
8
+ }
9
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,mBAAmB,CACjC,KAAY,EACZ,IAAY,EACZ,OAAsB,EACtB,eAAe,GAA0B,EAAE;IAE3C,MAAM,OAAO,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACnD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACjE,KAAK,MAAM,UAAU,IAAI,IAAI,EAAE,CAAC;QAC9B,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { type Logger } from './logger.ts';
2
+ export type RestoreOutput = () => void;
3
+ export declare function captureOutput(given?: Logger): RestoreOutput;
4
+ //# sourceMappingURL=output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AACA,OAAO,EAAuB,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAE/D,MAAM,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC;AAkBvC,wBAAgB,aAAa,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,aAAa,CAqD3D"}
package/dist/output.js ADDED
@@ -0,0 +1,63 @@
1
+ import { format, inspect } from 'node:util';
2
+ import { createProcessLogger } from './logger.js';
3
+ const restoreKey = Symbol.for('zigordev.otel.output');
4
+ const levelOf = {
5
+ debug: 'debug',
6
+ log: 'info',
7
+ info: 'info',
8
+ warn: 'warn',
9
+ error: 'error',
10
+ };
11
+ export function captureOutput(given) {
12
+ const holder = globalThis;
13
+ const existing = holder[restoreKey];
14
+ if (existing) {
15
+ return existing;
16
+ }
17
+ const target = globalThis.console;
18
+ const logger = given ?? createProcessLogger();
19
+ const lines = logger.child({ source: 'console' });
20
+ const original = {
21
+ debug: target.debug,
22
+ log: target.log,
23
+ info: target.info,
24
+ warn: target.warn,
25
+ error: target.error,
26
+ trace: target.trace,
27
+ dir: target.dir,
28
+ };
29
+ for (const method of Object.keys(levelOf)) {
30
+ target[method] = (...values) => {
31
+ lines[levelOf[method]](format(...values));
32
+ };
33
+ }
34
+ target.trace = function trace(...values) {
35
+ const held = { name: 'Trace', message: format(...values), stack: '' };
36
+ Error.captureStackTrace(held, trace);
37
+ lines.debug(held.stack);
38
+ };
39
+ target.dir = (value, options) => {
40
+ lines.info(inspect(value, options));
41
+ };
42
+ const previous = process.listeners('warning');
43
+ const onWarning = (warning) => {
44
+ logger.warn({
45
+ event: 'process.warning',
46
+ ...(warning.code ? { code: warning.code } : {}),
47
+ error: warning,
48
+ });
49
+ };
50
+ process.removeAllListeners('warning');
51
+ process.on('warning', onWarning);
52
+ const restore = () => {
53
+ Object.assign(target, original);
54
+ process.off('warning', onWarning);
55
+ for (const listener of previous) {
56
+ process.on('warning', listener);
57
+ }
58
+ delete holder[restoreKey];
59
+ };
60
+ holder[restoreKey] = restore;
61
+ return restore;
62
+ }
63
+ //# sourceMappingURL=output.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output.js","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAuB,OAAO,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAe,MAAM,aAAa,CAAC;AAI/D,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;AAMtD,MAAM,OAAO,GAAG;IACd,KAAK,EAAE,OAAO;IACd,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,OAAO;CACN,CAAC;AAIX,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,MAAM,MAAM,GAAG,UAA0B,CAAC;IAC1C,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;IACpC,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IA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AAC,CAAC,CAAC;IACtC,CAAC,CAAC;IAEF,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC9C,MAAM,SAAS,GAAG,CAAC,OAAgB,EAAQ,EAAE;QAC3C,MAAM,CAAC,IAAI,CAAC;YACV,KAAK,EAAE,iBAAiB;YACxB,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC/C,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;IACtC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAEjC,MAAM,OAAO,GAAkB,GAAG,EAAE;QAClC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChC,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;QAClC,KAAK,MAAM,QAAQ,IAAI,QAAQ,EAAE,CAAC;YAChC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,MAAM,CAAC,UAAU,CAAC,CAAC;IAC5B,CAAC,CAAC;IACF,MAAM,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC;IAC7B,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Attributes } from '@opentelemetry/api';
2
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
3
+ export declare function removePersonalData(attributes: Attributes): void;
4
+ export declare const privacySpanProcessor: SpanProcessor;
5
+ //# sourceMappingURL=privacy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"privacy.d.ts","sourceRoot":"","sources":["../src/privacy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAqB9D,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAU/D;AAED,eAAO,MAAM,oBAAoB,EAAE,aAKlC,CAAC"}
@@ -0,0 +1,34 @@
1
+ const removed = [
2
+ 'client.address',
3
+ 'client.port',
4
+ 'network.peer.address',
5
+ 'network.peer.port',
6
+ 'url.query',
7
+ 'user_agent.original',
8
+ 'http.client_ip',
9
+ 'http.user_agent',
10
+ 'net.peer.ip',
11
+ 'net.peer.port',
12
+ 'net.sock.peer.addr',
13
+ 'net.sock.peer.port',
14
+ ];
15
+ const addresses = ['url.full', 'http.url', 'http.target'];
16
+ const queryOrFragment = /[?#].*$/s;
17
+ export function removePersonalData(attributes) {
18
+ for (const key of removed) {
19
+ delete attributes[key];
20
+ }
21
+ for (const key of addresses) {
22
+ const value = attributes[key];
23
+ if (typeof value === 'string') {
24
+ attributes[key] = value.replace(queryOrFragment, '');
25
+ }
26
+ }
27
+ }
28
+ export const privacySpanProcessor = {
29
+ onStart: () => undefined,
30
+ onEnd: (span) => removePersonalData(span.attributes),
31
+ forceFlush: () => Promise.resolve(),
32
+ shutdown: () => Promise.resolve(),
33
+ };
34
+ //# sourceMappingURL=privacy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"privacy.js","sourceRoot":"","sources":["../src/privacy.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG;IACd,gBAAgB;IAChB,aAAa;IACb,sBAAsB;IACtB,mBAAmB;IACnB,WAAW;IACX,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,aAAa;IACb,eAAe;IACf,oBAAoB;IACpB,oBAAoB;CACrB,CAAC;AAEF,MAAM,SAAS,GAAG,CAAC,UAAU,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;AAE1D,MAAM,eAAe,GAAG,UAAU,CAAC;AAEnC,MAAM,UAAU,kBAAkB,CAAC,UAAsB;IACvD,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;QAC5B,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;QAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,UAAU,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,oBAAoB,GAAkB;IACjD,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;IACxB,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC;IACpD,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;IACnC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;CAClC,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Logger } from 'pino';
2
+ export declare function logStarted(logger: Logger, fields?: Record<string, unknown>): void;
3
+ export declare function logStopping(logger: Logger, signal: string): void;
4
+ export declare function logProcessCrashes(logger: Logger): () => void;
5
+ //# sourceMappingURL=process-events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-events.d.ts","sourceRoot":"","sources":["../src/process-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAEnC,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GAAG,IAAI,CAErF;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAEhE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,IAAI,CAY5D"}
@@ -0,0 +1,19 @@
1
+ export function logStarted(logger, fields = {}) {
2
+ logger.info({ event: 'service.started', runtime: `node ${process.version}`, ...fields });
3
+ }
4
+ export function logStopping(logger, signal) {
5
+ logger.info({ event: 'service.stopping', signal });
6
+ }
7
+ export function logProcessCrashes(logger) {
8
+ const listener = (error, origin) => {
9
+ const event = origin === 'unhandledRejection'
10
+ ? 'process.unhandled_rejection'
11
+ : 'process.uncaught_exception';
12
+ logger.error({ event, error });
13
+ };
14
+ process.on('uncaughtExceptionMonitor', listener);
15
+ return () => {
16
+ process.off('uncaughtExceptionMonitor', listener);
17
+ };
18
+ }
19
+ //# sourceMappingURL=process-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-events.js","sourceRoot":"","sources":["../src/process-events.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,UAAU,CAAC,MAAc,EAAE,MAAM,GAA4B,EAAE;IAC7E,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,QAAQ,OAAO,CAAC,OAAO,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;AAC3F,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,MAAc,EAAE,MAAc;IACxD,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,CAAC,CAAC;AACrD,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAc;IAC9C,MAAM,QAAQ,GAAG,CAAC,KAAY,EAAE,MAAc,EAAQ,EAAE;QACtD,MAAM,KAAK,GACT,MAAM,KAAK,oBAAoB;YAC7B,CAAC,CAAC,6BAA6B;YAC/B,CAAC,CAAC,4BAA4B,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACjC,CAAC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,0BAA0B,EAAE,QAAQ,CAAC,CAAC;IACjD,OAAO,GAAG,EAAE;QACV,OAAO,CAAC,GAAG,CAAC,0BAA0B,EAAE,QAAQ,CAAC,CAAC;IACpD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=register.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../src/register.ts"],"names":[],"mappings":""}
@@ -0,0 +1,5 @@
1
+ import { captureOutput } from './output.js';
2
+ import { startTelemetry } from './telemetry.js';
3
+ captureOutput();
4
+ startTelemetry();
5
+ //# sourceMappingURL=register.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.js","sourceRoot":"","sources":["../src/register.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,aAAa,EAAE,CAAC;AAChB,cAAc,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare function nameRoute(route: string): void;
2
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAGA,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAK7C"}
package/dist/route.js ADDED
@@ -0,0 +1,9 @@
1
+ import { context } from '@opentelemetry/api';
2
+ import { getRPCMetadata, RPCType } from '@opentelemetry/core';
3
+ export function nameRoute(route) {
4
+ const metadata = getRPCMetadata(context.active());
5
+ if (metadata?.type === RPCType.HTTP) {
6
+ metadata.route = route;
7
+ }
8
+ }
9
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9D,MAAM,UAAU,SAAS,CAAC,KAAa;IACrC,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAClD,IAAI,QAAQ,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,EAAE,CAAC;QACpC,QAAQ,CAAC,KAAK,GAAG,KAAK,CAAC;IACzB,CAAC;AACH,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { type ResourceDetector } from '@opentelemetry/resources';
2
+ import { startNodeSdk } from '@opentelemetry/sdk-node';
3
+ import { type Sampler } from '@opentelemetry/sdk-trace';
4
+ type SdkOptions = NonNullable<Parameters<typeof startNodeSdk>[0]>;
5
+ type Instrumentations = NonNullable<SdkOptions['instrumentations']>;
6
+ export interface TelemetryOptions {
7
+ readonly instrumentations?: Instrumentations;
8
+ }
9
+ export interface Telemetry {
10
+ readonly shutdown: () => Promise<void>;
11
+ }
12
+ export declare function isProbeRequest(url: string | undefined): boolean;
13
+ export declare const probeAwareSampler: Sampler;
14
+ export declare const hostNameDetector: ResourceDetector;
15
+ export declare function startTelemetry(options?: TelemetryOptions): Telemetry;
16
+ export declare function shutdownTelemetry(): Promise<void>;
17
+ export {};
18
+ //# sourceMappingURL=telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,KAAK,gBAAgB,EAGtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAGL,KAAK,OAAO,EAGb,MAAM,0BAA0B,CAAC;AAMlC,KAAK,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAClE,KAAK,gBAAgB,GAAG,WAAW,CAAC,UAAU,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAEpE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CAC9C;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACxC;AAMD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAG/D;AAiBD,eAAO,MAAM,iBAAiB,EAAE,OAAsD,CAAC;AAEvF,eAAO,MAAM,gBAAgB,EAAE,gBAE9B,CAAC;AAqBF,wBAAgB,cAAc,CAAC,OAAO,GAAE,gBAAqB,GAAG,SAAS,CA0CxE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CAEvD"}
@@ -0,0 +1,101 @@
1
+ import { hostname } from 'node:os';
2
+ import { diag, SpanKind } from '@opentelemetry/api';
3
+ import { diagLogLevelFromString, setGlobalErrorHandler } from '@opentelemetry/core';
4
+ import { OTLPTraceExporter as JsonTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
5
+ import { OTLPTraceExporter as ProtobufTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
6
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
7
+ import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
8
+ import { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node';
9
+ import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
10
+ import { osDetector, processDetector, serviceInstanceIdDetector, serviceNameEnvDetector, } from '@opentelemetry/resources';
11
+ import { startNodeSdk } from '@opentelemetry/sdk-node';
12
+ import { BatchSpanProcessor, ParentBasedSampler, SamplingDecision, } from '@opentelemetry/sdk-trace';
13
+ import { createDiagnostics } from './diagnostics.js';
14
+ import { installLoaderHooks } from './loader-hooks.js';
15
+ import { createProcessLogger } from './logger.js';
16
+ import { privacySpanProcessor } from './privacy.js';
17
+ const handleKey = Symbol.for('zigordev.otel.telemetry');
18
+ export function isProbeRequest(url) {
19
+ const path = (url ?? '').split('?')[0] ?? '';
20
+ return path === '/health' || path === '/favicon.ico' || path.startsWith('/_next/static/');
21
+ }
22
+ function requestPath(attributes) {
23
+ const path = attributes['url.path'] ?? attributes['http.target'];
24
+ return typeof path === 'string' ? path : undefined;
25
+ }
26
+ const skipProbes = {
27
+ shouldSample(_context, _traceId, _spanName, spanKind, attributes) {
28
+ if (spanKind === SpanKind.SERVER && isProbeRequest(requestPath(attributes))) {
29
+ return { decision: SamplingDecision.NOT_RECORD };
30
+ }
31
+ return { decision: SamplingDecision.RECORD_AND_SAMPLED };
32
+ },
33
+ toString: () => 'SkipProbes',
34
+ };
35
+ export const probeAwareSampler = new ParentBasedSampler({ root: skipProbes });
36
+ export const hostNameDetector = {
37
+ detect: () => ({ attributes: { 'host.name': hostname() } }),
38
+ };
39
+ const resourceDetectors = [
40
+ serviceInstanceIdDetector,
41
+ serviceNameEnvDetector,
42
+ processDetector,
43
+ osDetector,
44
+ hostNameDetector,
45
+ ];
46
+ function serviceVersion() {
47
+ const version = process.env.OTEL_SERVICE_VERSION;
48
+ return version ? { 'service.version': version } : {};
49
+ }
50
+ function traceExporter() {
51
+ return process.env.OTEL_EXPORTER_OTLP_PROTOCOL === 'http/json'
52
+ ? new JsonTraceExporter()
53
+ : new ProtobufTraceExporter();
54
+ }
55
+ export function startTelemetry(options = {}) {
56
+ const holder = globalThis;
57
+ const existing = holder[handleKey];
58
+ if (existing) {
59
+ return existing;
60
+ }
61
+ installLoaderHooks();
62
+ const logLevel = process.env.OTEL_LOG_LEVEL || 'warn';
63
+ const sdk = startNodeSdk({
64
+ logLevel,
65
+ resourceAttributes: serviceVersion(),
66
+ resourceDetectors,
67
+ sampler: probeAwareSampler,
68
+ spanProcessors: [privacySpanProcessor, new BatchSpanProcessor({ exporter: traceExporter() })],
69
+ logRecordProcessors: [],
70
+ instrumentations: [
71
+ new HttpInstrumentation({
72
+ ignoreIncomingRequestHook: (request) => isProbeRequest(request.url),
73
+ requireParentforOutgoingSpans: true,
74
+ }),
75
+ new UndiciInstrumentation({ requireParentforSpans: true }),
76
+ new PgInstrumentation({ requireParentSpan: true }),
77
+ new RuntimeNodeInstrumentation(),
78
+ ...(options.instrumentations ?? []),
79
+ ],
80
+ });
81
+ const diagnostics = createDiagnostics(createProcessLogger());
82
+ diag.setLogger(diagnostics.logger, {
83
+ logLevel: diagLogLevelFromString(logLevel),
84
+ suppressOverrideMessage: true,
85
+ });
86
+ setGlobalErrorHandler(diagnostics.onError);
87
+ const telemetry = {
88
+ shutdown: async () => {
89
+ delete holder[handleKey];
90
+ await sdk.shutdown().catch((error) => {
91
+ diag.warn('The last telemetry could not be sent before the stop.', error);
92
+ });
93
+ },
94
+ };
95
+ holder[handleKey] = telemetry;
96
+ return telemetry;
97
+ }
98
+ export async function shutdownTelemetry() {
99
+ await globalThis[handleKey]?.shutdown();
100
+ }
101
+ //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAmB,IAAI,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACpF,OAAO,EAAE,iBAAiB,IAAI,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AACjG,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AACtG,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,0BAA0B,EAAE,MAAM,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AAC;YAC5E,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;IACF,MAAM,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IAC9B,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB;IACrC,MAAO,UAA8B,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,CAAC;AAC/D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@zigordev/otel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.8.0",
4
+ "description": "Telemetry for zigordev services: traces and metrics over OpenTelemetry, structured logs with the trace in them, and the answer of the health route",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./register": {
19
+ "types": "./dist/register.d.ts",
20
+ "default": "./dist/register.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@opentelemetry/core": "3.1.1",
25
+ "@opentelemetry/exporter-trace-otlp-http": "0.301.2",
26
+ "@opentelemetry/exporter-trace-otlp-proto": "0.301.2",
27
+ "@opentelemetry/instrumentation": "0.301.2",
28
+ "@opentelemetry/instrumentation-http": "0.301.2",
29
+ "@opentelemetry/instrumentation-pg": "0.78.0",
30
+ "@opentelemetry/instrumentation-runtime-node": "0.38.0",
31
+ "@opentelemetry/instrumentation-undici": "0.35.1",
32
+ "@opentelemetry/resources": "3.1.1",
33
+ "@opentelemetry/sdk-node": "0.301.2",
34
+ "@opentelemetry/sdk-trace": "3.1.1",
35
+ "pino": "10.4.0"
36
+ },
37
+ "peerDependencies": {
38
+ "@opentelemetry/api": "^1.10.0"
39
+ },
40
+ "devDependencies": {
41
+ "@opentelemetry/api": "1.10.0",
42
+ "@opentelemetry/context-async-hooks": "3.1.1",
43
+ "@opentelemetry/sdk-metrics": "3.1.1",
44
+ "@types/node": "26.6.6",
45
+ "@zigordev/dev": "1.8.0",
46
+ "pg": "8.23.1",
47
+ "typescript": "7.0.2",
48
+ "vitest": "5.1.1"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/zigordev/toolkit.git",
56
+ "directory": "packages/otel"
57
+ },
58
+ "scripts": {
59
+ "build": "tsc -p tsconfig.build.json",
60
+ "typecheck": "tsc -p tsconfig.json"
61
+ }
6
62
  }