@foam-ai/node 0.1.0-alpha.1 → 0.1.0-alpha.11

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 (64) hide show
  1. package/README.md +656 -0
  2. package/dist/before-send.d.ts +27 -0
  3. package/dist/before-send.js +46 -0
  4. package/dist/constants.d.ts +44 -0
  5. package/dist/constants.js +67 -0
  6. package/dist/endpoint.d.ts +2 -0
  7. package/dist/endpoint.js +11 -0
  8. package/dist/exporters.d.ts +34 -0
  9. package/dist/exporters.js +208 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +28 -0
  12. package/dist/ingest.d.ts +12 -0
  13. package/dist/ingest.js +70 -0
  14. package/dist/init.d.ts +26 -0
  15. package/dist/init.js +171 -0
  16. package/dist/instrumentations.d.ts +4 -0
  17. package/dist/instrumentations.js +120 -0
  18. package/dist/library-versions.d.ts +1 -0
  19. package/dist/library-versions.js +59 -0
  20. package/dist/logs.d.ts +10 -0
  21. package/dist/logs.js +61 -0
  22. package/dist/metrics.d.ts +5 -0
  23. package/dist/metrics.js +29 -0
  24. package/dist/network-capture/collector.d.ts +27 -0
  25. package/dist/network-capture/collector.js +411 -0
  26. package/dist/network-capture/http.d.ts +5 -0
  27. package/dist/network-capture/http.js +221 -0
  28. package/dist/network-capture/index.d.ts +3 -0
  29. package/dist/network-capture/index.js +20 -0
  30. package/dist/network-capture/redact.d.ts +9 -0
  31. package/dist/network-capture/redact.js +401 -0
  32. package/dist/network-capture/support.d.ts +2 -0
  33. package/dist/network-capture/support.js +38 -0
  34. package/dist/network-capture/undici.d.ts +5 -0
  35. package/dist/network-capture/undici.js +177 -0
  36. package/dist/otlp.d.ts +8 -0
  37. package/dist/otlp.js +46 -0
  38. package/dist/propagation.d.ts +5 -0
  39. package/dist/propagation.js +47 -0
  40. package/dist/redaction-keys.d.ts +4 -0
  41. package/dist/redaction-keys.js +480 -0
  42. package/dist/redaction.d.ts +24 -0
  43. package/dist/redaction.js +281 -0
  44. package/dist/report.d.ts +9 -0
  45. package/dist/report.js +56 -0
  46. package/dist/resource.d.ts +3 -0
  47. package/dist/resource.js +24 -0
  48. package/dist/state.d.ts +26 -0
  49. package/dist/state.js +61 -0
  50. package/dist/traces.d.ts +1 -0
  51. package/dist/traces.js +21 -0
  52. package/dist/utils.d.ts +4 -0
  53. package/dist/utils.js +20 -0
  54. package/package.json +47 -19
  55. package/dist/node/src/capture-exception.d.ts +0 -9
  56. package/dist/node/src/capture-exception.js +0 -31
  57. package/dist/node/src/index.d.ts +0 -9
  58. package/dist/node/src/index.js +0 -12
  59. package/dist/node/src/init.d.ts +0 -27
  60. package/dist/node/src/init.js +0 -203
  61. package/dist/shared/constants.d.ts +0 -1
  62. package/dist/shared/constants.js +0 -4
  63. package/dist/shared/util.d.ts +0 -9
  64. package/dist/shared/util.js +0 -21
package/README.md ADDED
@@ -0,0 +1,656 @@
1
+ # Foam OpenTelemetry SDK for Node.js
2
+
3
+ `@foam-ai/node` is Foam's OpenTelemetry distribution for Node.js.
4
+
5
+ ## Requirements
6
+
7
+ - Node.js `^18.19.0 || >=20.6.0`, matching the supported engine range of
8
+ `@opentelemetry/auto-instrumentations-node`
9
+ - Foam ingest token, stored as `FOAM_OTEL_TOKEN`
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @foam-ai/node
15
+ ```
16
+
17
+ ## Initialize
18
+
19
+ Call `init()` before your app loads so OpenTelemetry can patch libraries as
20
+ they import. Put `init()` in its own file and preload it with `--import` or
21
+ `--require` (below).
22
+
23
+ Set `enabled: false` to turn Foam off.
24
+
25
+ Store the ingest token as `FOAM_OTEL_TOKEN` and pass
26
+ `process.env.FOAM_OTEL_TOKEN` to `init()`.
27
+
28
+ ### TypeScript
29
+
30
+ Create `instrumentation.ts`:
31
+
32
+ ```ts
33
+ import { init } from "@foam-ai/node";
34
+
35
+ init({
36
+ name: "checkout-api",
37
+ environment: "production",
38
+ enabled: true,
39
+ token: process.env.FOAM_OTEL_TOKEN,
40
+ version: "1.0.0",
41
+ });
42
+ ```
43
+
44
+ Compile it with the app. If TypeScript emits ESM, preload with `--import`
45
+ (same rule as ESM below):
46
+
47
+ ```sh
48
+ node --import ./dist/instrumentation.js ./dist/app.js
49
+ ```
50
+
51
+ If TypeScript emits CommonJS, preload with `--require`:
52
+
53
+ ```sh
54
+ node --require ./dist/instrumentation.js ./dist/app.js
55
+ ```
56
+
57
+ To run TypeScript without compiling first:
58
+
59
+ ```sh
60
+ node --import tsx --import ./instrumentation.ts ./src/app.ts
61
+ ```
62
+
63
+ ### ESM
64
+
65
+ Create `instrumentation.mjs` with the same `init()` call.
66
+
67
+ `import` lines always run first, even if you write `init()` above them.
68
+ Don't import your app from that file. Use `--import`, or
69
+ `await import("./app.js")` after `init()`:
70
+
71
+ ```sh
72
+ node --import ./instrumentation.mjs ./app.js
73
+ ```
74
+
75
+ ### CommonJS
76
+
77
+ Create `instrumentation.cjs`. `require()` runs in order, so `init()` then
78
+ `require("./app")` in this file is fine. `--require` is still the better
79
+ preload:
80
+
81
+ ```js
82
+ const { init } = require("@foam-ai/node");
83
+
84
+ init({
85
+ name: "checkout-api",
86
+ environment: "production",
87
+ enabled: true,
88
+ token: process.env.FOAM_OTEL_TOKEN,
89
+ version: "1.0.0",
90
+ });
91
+ ```
92
+
93
+ ```sh
94
+ node --require ./instrumentation.cjs ./app.js
95
+ ```
96
+
97
+ ## Public API
98
+
99
+ ### `init(options)`
100
+
101
+ Sets up tracing, metrics, logs, auto-instrumentation, OTLP export to Foam,
102
+ and W3C context propagation.
103
+
104
+ Call this once. Use it when Foam should run OpenTelemetry for the process.
105
+
106
+ ```js
107
+ import { init } from "@foam-ai/node";
108
+
109
+ init({
110
+ name: "checkout-api",
111
+ environment: "production",
112
+ enabled: true,
113
+ token: process.env.FOAM_OTEL_TOKEN,
114
+ version: "1.0.0",
115
+ });
116
+ ```
117
+
118
+ ```ts
119
+ init({
120
+ name,
121
+ environment,
122
+ enabled,
123
+ token,
124
+ endpoint?,
125
+ version?,
126
+ sampleRate?,
127
+ additionalInstrumentations?,
128
+ additionalSpanProcessors?,
129
+ additionalLogRecordProcessors?,
130
+ additionalMetricReaders?,
131
+ additionalResourceAttributes?,
132
+ disableLogSending?,
133
+ networkCapture?,
134
+ ignoredOutboundHosts?,
135
+ redact?,
136
+ beforeSend?,
137
+ }): void
138
+ ```
139
+
140
+ `name`, `environment`, and `enabled` are required.
141
+ `token` is required only when Foam is enabled; store it as `FOAM_OTEL_TOKEN`.
142
+
143
+ `endpoint` defaults to Foam's OTLP endpoint and is where all telemetry is
144
+ delivered. Override it only to route through a Foam-compatible OTLP
145
+ gateway, such as an egress proxy or a local collector. It must be an
146
+ `http(s)` URL; its host is always excluded from outbound tracing so
147
+ export calls do not become client spans.
148
+
149
+ `version` sets `service.version`.
150
+
151
+ `sampleRate` is a number from `0` to `1` and defaults to `1`. Rarely if ever updated. Only change it if you are sending telemetry in the petabytes range.
152
+
153
+ `additionalInstrumentations` adds extra OpenTelemetry instrumentations next
154
+ to Foam's Node auto bundle and `ConsoleInstrumentation`.
155
+
156
+ `additionalSpanProcessors`, `additionalLogRecordProcessors`, and
157
+ `additionalMetricReaders` add extra processors/readers from other vendors next to Foam's
158
+ exporters. Note: Never add Foam's own processors/readers helpers.
159
+
160
+ `additionalResourceAttributes` adds extra resource attributes (for example
161
+ `team` or `cloud.region`) to all telemetry.
162
+
163
+ `disableLogSending` defaults to `false`. Set `true` to stop Foam from
164
+ adding its own sending path to supported loggers; trace correlation in
165
+ log records is unaffected (see Loggers).
166
+
167
+ `networkCapture` defaults to `"basic"`. Upgrade to `"advanced"` unless you
168
+ cannot; it gives much more powerful HTTP and Undici capture. See Network capture.
169
+
170
+ `redact` adds keys to Foam's built-in redaction. `secrets` preserves the last
171
+ four characters of longer values; `pii` fully masks values.
172
+
173
+ ```js
174
+ init({
175
+ // ...
176
+ redact: {
177
+ secrets: ["internalId", "internalReference"],
178
+ pii: ["customerEmail", "homeAddress"],
179
+ },
180
+ });
181
+ ```
182
+
183
+ `beforeSend` can edit or drop spans and logs before Foam exports them. Return
184
+ the event to send it or `null` to drop it. Span events carry `name`,
185
+ `attributes`, `events` (span events, e.g. recorded exceptions), and `links`;
186
+ log events carry `body`, `severityText`, and `attributes`.
187
+
188
+ ```js
189
+ init({
190
+ // ...
191
+ beforeSend: (event) => {
192
+ if (event.type === "span" && event.attributes["url.path"] === "/health") {
193
+ return null; // drop health checks
194
+ }
195
+ delete event.attributes["user.email"];
196
+ return event;
197
+ },
198
+ });
199
+ ```
200
+
201
+ Metrics are not passed through `beforeSend`. See Redaction for coverage.
202
+
203
+ `ignoredOutboundHosts` skips outbound HTTP tracing for those hostnames.
204
+ The configured `endpoint` host is always skipped so export calls do not
205
+ become client spans. Add extra hosts for high-volume clients that would drown traces,
206
+ for example a sidecar health-check host (`localhost`) or another vendor's
207
+ OTLP ingest host you already export to.
208
+
209
+ TODO(pcga11): Add other common Gen AI providers.
210
+
211
+ If another SDK already registered traces, metrics, logs, or the propagator,
212
+ `init()` leaves the signal's slot untouched and only takes what is available. When a slot is taken, use its ingest helper instead.
213
+
214
+ ### `createFoamIngestSpanProcessor(name, environment, token, options?)`
215
+
216
+ The helper returns a span processor but does not attach it to the
217
+ application's provider. Include it in the `spanProcessors` option when
218
+ constructing `BasicTracerProvider`. It cannot be added after provider
219
+ construction in `@opentelemetry/sdk-trace-base` 2.10; the old
220
+ `addSpanProcessor()` API is obsolete. If another SDK creates the provider,
221
+ configure the processor through that SDK's startup options.
222
+
223
+ ```js
224
+ import { trace } from "@opentelemetry/api";
225
+ import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
226
+ import { createFoamIngestSpanProcessor } from "@foam-ai/node";
227
+
228
+ const spanProcessor = createFoamIngestSpanProcessor(
229
+ "checkout-api",
230
+ "production",
231
+ process.env.FOAM_OTEL_TOKEN,
232
+ );
233
+ const tracerProvider = new BasicTracerProvider({
234
+ spanProcessors: [spanProcessor],
235
+ });
236
+ trace.setGlobalTracerProvider(tracerProvider);
237
+ ```
238
+
239
+ ### `createFoamIngestLogRecordProcessor(name, environment, token, options?)`
240
+
241
+ The helper returns a log-record processor but does not attach it to the
242
+ application's provider. Include it in the `processors` option when constructing
243
+ `LoggerProvider`. It cannot be added after provider construction in
244
+ `@opentelemetry/sdk-logs` 0.221; the old `addLogRecordProcessor()` API is
245
+ obsolete. If another SDK creates the provider, configure the processor through
246
+ that SDK's startup options.
247
+
248
+ ```js
249
+ import { logs } from "@opentelemetry/api-logs";
250
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
251
+ import { createFoamIngestLogRecordProcessor } from "@foam-ai/node";
252
+
253
+ const logRecordProcessor = createFoamIngestLogRecordProcessor(
254
+ "checkout-api",
255
+ "production",
256
+ process.env.FOAM_OTEL_TOKEN,
257
+ );
258
+ const loggerProvider = new LoggerProvider({
259
+ processors: [logRecordProcessor],
260
+ });
261
+ logs.setGlobalLoggerProvider(loggerProvider);
262
+ ```
263
+
264
+ All ingest helpers accept the same `redact` option as `init()`; the span and
265
+ log helpers also accept `beforeSend`.
266
+
267
+ ### `createFoamIngestMetricReader(name, environment, token, options?)`
268
+
269
+ The helper returns a metric reader but does not attach it to the application's
270
+ provider. Include it in the `readers` option when constructing `MeterProvider`.
271
+ It cannot be added after provider construction in
272
+ `@opentelemetry/sdk-metrics` 2.10; the old `addMetricReader()` API is obsolete.
273
+ If another SDK creates the provider, configure the reader through that SDK's
274
+ startup options.
275
+
276
+ ```js
277
+ import { metrics } from "@opentelemetry/api";
278
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
279
+ import { createFoamIngestMetricReader } from "@foam-ai/node";
280
+
281
+ const metricReader = createFoamIngestMetricReader(
282
+ "checkout-api",
283
+ "production",
284
+ process.env.FOAM_OTEL_TOKEN,
285
+ );
286
+ const meterProvider = new MeterProvider({
287
+ readers: [metricReader],
288
+ });
289
+ metrics.setGlobalMeterProvider(meterProvider);
290
+ ```
291
+
292
+ If a vendor SDK does not expose a processor or reader startup option, add Foam
293
+ at the collector instead.
294
+
295
+ If the other SDK already set `service.name` or environment,
296
+ Foam's values overwrite them on that copy only. The original spans, logs,
297
+ and metrics are left unchanged. For the Foam SDK, ensure all of the signals (spans, logs and metrics)
298
+ carry identical `service.name`.
299
+
300
+ Don't use `init()` and an ingest helper for the same signal. If another
301
+ SDK already owns traces (or another signal), call `init()` for the rest
302
+ and attach ingest only to the provider you don't own. Don't pass ingest
303
+ helpers as `additionalSpanProcessors` or extra readers: `init()` already
304
+ installs Foam exporters.
305
+
306
+ Ingest helpers do not register instrumentations. If you cannot call
307
+ `init()`, register them with the official OpenTelemetry API
308
+ before the app imports those libraries:
309
+
310
+ ```js
311
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
312
+ import { RedisInstrumentation } from "@opentelemetry/instrumentation-redis";
313
+ import { createFoamIngestSpanProcessor } from "@foam-ai/node";
314
+
315
+ registerInstrumentations({
316
+ instrumentations: [new RedisInstrumentation()],
317
+ });
318
+ ```
319
+
320
+ Attach the ingest helper to the other SDK's provider as in the examples
321
+ above. If that SDK already instruments the same library, don't register a
322
+ second copy.
323
+
324
+ OpenTelemetry allows only one global propagator per signal. Foam registers W3C Trace
325
+ Context and W3C Baggage (`traceparent`, `tracestate`, `baggage`), not B3,
326
+ Jaeger, or AWS X-Ray. Auto-instrumented HTTP uses whichever propagator
327
+ won. If another SDK already registered a propagator, Foam keeps it and
328
+ `getState().signals.baggage` is `"none"`. A non-W3C propagator will not
329
+ send `traceparent`, so a Foam peer starts a new trace. Foam does not add
330
+ W3C headers on top.
331
+
332
+ A work around is to initialize Foam first, or include W3C in the other
333
+ SDK's composite, if those headers must be on HTTP.
334
+
335
+ TODO(pcga11): Handle traceparent conflict^
336
+
337
+ ### `injectTraceContext(headers)`
338
+
339
+ Writes W3C `traceparent`, `tracestate`, and `baggage` onto a header map.
340
+
341
+ Use this when you send a message yourself (Kafka, a queue, a custom
342
+ socket). Auto-instrumented HTTP, Express, Undici, and Fetch already inject
343
+ these headers; don't call this on ordinary HTTP. This uses Foam's local
344
+ W3C propagator so it works even if Foam did not get the global one.
345
+
346
+ ```js
347
+ const headers = {};
348
+ injectTraceContext(headers);
349
+ await kafka.send({ value: payload, headers });
350
+ ```
351
+
352
+ ### `extractTraceContext(headers)`
353
+
354
+ Reads W3C trace and baggage headers and returns a parent OpenTelemetry
355
+ context.
356
+
357
+ Use this when receiving a message on a custom transport. Without extraction,
358
+ the handler loses the propagated parent context.
359
+
360
+ ```js
361
+ import { context } from "@opentelemetry/api";
362
+
363
+ const parent = extractTraceContext(message.headers);
364
+ await context.with(parent, () => handle(message));
365
+ ```
366
+
367
+ ### `setBaggage(key, value, callback)`
368
+
369
+ Runs a callback with a request-scoped string such as a tenant or user ID.
370
+ The value follows work started by the callback across `await`s without leaking
371
+ to later handlers. Call `injectTraceContext` to send it on custom transports.
372
+
373
+ ```js
374
+ await setBaggage("tenant.id", "acme", () => handleRequest());
375
+ ```
376
+
377
+ ### `getBaggage(key)`
378
+
379
+ Returns a baggage value from the current request, or `undefined`.
380
+
381
+ Use this later in the same request to read a value set with `setBaggage`,
382
+ or a key that arrived on an inbound `baggage` header.
383
+
384
+ ```js
385
+ const tenant = getBaggage("tenant.id"); // "acme"
386
+ ```
387
+
388
+ ### `incrementCounter(name, value?, attributes?, options?)`
389
+
390
+ Creates the counter if it does not exist, then increments it.
391
+
392
+ This counter can only increases. Use this for event counts.
393
+
394
+ ```js
395
+ incrementCounter("orders.created", 1, { "cloud.region": "us-west-1" });
396
+ ```
397
+
398
+ ### `recordHistogram(name, value, attributes?, options?)`
399
+
400
+ Creates the histogram if it does not exist, then records a measurement.
401
+
402
+ Use this for values you want percentiles or averages of: latency, duration, payload size.
403
+
404
+ ```js
405
+ recordHistogram("checkout.duration", 0.142, undefined, { unit: "s" });
406
+ ```
407
+
408
+ ### `addUpDownCounter(name, value, attributes?, options?)`
409
+
410
+ Creates the up-down counter if it does not exist, then adds a signed
411
+ delta. The value can go up or down.
412
+
413
+ Use this for occupancy: active jobs, open connections, items in a pool.
414
+
415
+ In other terms, pass +value when something starts occupying a slot, -value when it leaves. The metric is the current state of occupancy.
416
+
417
+ ```js
418
+ addUpDownCounter("jobs.active", -1);
419
+ ```
420
+
421
+ ### `setMetric(name, value, attributes?, options?)`
422
+
423
+ Creates the gauge if it does not exist, then sets its current value.
424
+
425
+ Use this for a point-in-time level: queue depth, heap used, cache size.
426
+
427
+ ```js
428
+ setMetric("queue.depth", 27);
429
+ ```
430
+
431
+ TODO(pcga11): Investigate if it's worth support observable (pull) instruments API.
432
+
433
+ ### `log(body, severity?, attributes?)`
434
+
435
+ Sends a log record to Foam on Foam's own export path. It does not write to the app's logger, and it does not emit on a LoggerProvider Foam does
436
+ not own.
437
+
438
+ Use this to send logs directly. Typically used for Pino 5–6, Winston 1–2 as they do not support sending logs.
439
+
440
+ ```js
441
+ import { log, SeverityNumber } from "@foam-ai/node";
442
+
443
+ log("checkout failed");
444
+ log("checkout failed", SeverityNumber.ERROR);
445
+ ```
446
+
447
+ ### `recordException(error)`
448
+
449
+ Records an exception on the current active span and sets the span status
450
+ to `ERROR`. Accepts an `Error` or any value (stringified). Never throws;
451
+ does nothing when no span is active or the span is not recording.
452
+
453
+ Use this in `catch` blocks inside auto-instrumented handlers (HTTP
454
+ routes, message consumers) where you did not create the span yourself.
455
+ The exception lands on whichever SDK owns the active span, so it works
456
+ even when another SDK owns tracing.
457
+
458
+ ```js
459
+ import { recordException } from "@foam-ai/node";
460
+
461
+ try {
462
+ await chargeCard(order);
463
+ } catch (err) {
464
+ recordException(err);
465
+ throw err;
466
+ }
467
+ ```
468
+
469
+ ### `getState()`
470
+
471
+ Returns whether Foam initialized, which instrumentations registered, and
472
+ which signals have an export path.
473
+
474
+ Use this in health checks, tests, or diagnostics to confirm Foam is
475
+ running.
476
+
477
+ ```js
478
+ import { getState } from "@foam-ai/node";
479
+
480
+ getState();
481
+ // {
482
+ // initialized: true,
483
+ // instrumentations: ["http", "express", "pg", ...],
484
+ // signals: {
485
+ // traces: "global",
486
+ // metrics: "global",
487
+ // logs: "global",
488
+ // baggage: "global",
489
+ // profile: "none",
490
+ // },
491
+ // }
492
+ ```
493
+
494
+ `instrumentations` lists only the instrumentations registered with a
495
+ successfully started Foam SDK, after upstream defaults and
496
+ `OTEL_NODE_ENABLED_INSTRUMENTATIONS` /
497
+ `OTEL_NODE_DISABLED_INSTRUMENTATIONS` filtering. Registered means the
498
+ instrumentation is ready to patch a supported module when that module
499
+ loads.
500
+
501
+ Each `signals` value names the source of the Foam export path for that
502
+ signal:
503
+
504
+ - `"global"` — `init()` registered Foam's provider in the global
505
+ OpenTelemetry slot.
506
+ - `"ingest"` — a `createFoamIngest*` processor/reader was constructed for
507
+ another SDK's pipeline. Foam cannot tell whether you actually registered
508
+ the returned object.
509
+ - `"local"` — logs only: another SDK owns the global LoggerProvider, but
510
+ Foam keeps its own local provider so `log()` still delivers to Foam.
511
+ - `"none"` — no Foam export path.
512
+
513
+ A value other than `"none"` means telemetry is expected, not that the app
514
+ has already produced or exported it.
515
+
516
+ ## Custom spans and other OpenTelemetry APIs
517
+
518
+ Foam does not wrap span creation. To start your own spans, read the
519
+ current span, or work with context, import `@opentelemetry/api` directly.
520
+ `init()` registers Foam's providers in the global OpenTelemetry slots, so
521
+ the official API routes to Foam automatically.
522
+
523
+ Install the API in your app so it resolves one compatible `1.x` copy:
524
+
525
+ ```sh
526
+ npm install @opentelemetry/api
527
+ ```
528
+
529
+ ```js
530
+ import { trace, SpanStatusCode } from "@opentelemetry/api";
531
+
532
+ const tracer = trace.getTracer("checkout");
533
+
534
+ await tracer.startActiveSpan("charge-card", async (span) => {
535
+ try {
536
+ await chargeCard(order);
537
+ } catch (err) {
538
+ span.recordException(err);
539
+ span.setStatus({ code: SpanStatusCode.ERROR });
540
+ throw err;
541
+ } finally {
542
+ span.end();
543
+ }
544
+ });
545
+ ```
546
+
547
+ Prefer `startActiveSpan` over `startSpan`: it makes the span current, so
548
+ auto-instrumented HTTP/database spans and nested custom spans parent under
549
+ it. Always call `span.end()` (the `finally` above), or the span never
550
+ exports. When you did not create the span yourself, Foam's
551
+ `recordException(err)` does the exception-plus-ERROR-status pair on the
552
+ current active span for you.
553
+
554
+ The same applies to the rest of the API: `trace.getActiveSpan()` to tag
555
+ the current request (`span.setAttribute(...)`), and `context.with(...)`
556
+ to run code under a specific context.
557
+
558
+ This is safe in every state: if another SDK owns the global tracer slot,
559
+ these spans go to that SDK; before `init()` (or when Foam is disabled)
560
+ the API returns a no-op tracer and nothing is recorded. Custom spans
561
+ export wherever `getState().signals.traces` points.
562
+
563
+ ## Network capture
564
+
565
+ `networkCapture` defaults to `"basic"` and controls extra HTTP detail.
566
+
567
+ - `"off"` keeps standard OpenTelemetry HTTP/Undici telemetry, with no extra
568
+ capture.
569
+ - `"basic"` adds allowlisted `content-type`, `content-length`, and
570
+ `content-encoding` headers.
571
+ - `"advanced"` adds those headers plus full Node `http`/`https` and
572
+ Fetch/Undici request and response bodies as raw wire bytes, up to 1 MiB. Always set to `"advanced"` when security and compliance allows.
573
+
574
+ ## Redaction
575
+
576
+ Foam always masks common credentials in captured request and response data,
577
+ URLs, and exported span and log fields. The built-in floor matches both exact
578
+ well-known names and any key containing a sensitive term (`legacy_api_key_2`,
579
+ `stripeToken`), so credential-bearing keys do not need to be enumerated. Add
580
+ application-specific keys with the `redact` option shown under `init(options)`;
581
+ customer keys match exactly after normalization.
582
+
583
+ Redaction applies to everything Foam exports — span, span event, and link
584
+ attributes, log bodies and attributes, metric data-point attributes, and
585
+ resource attributes — including the ingest helpers. It does not modify
586
+ telemetry sent through other exporters.
587
+
588
+ ## Loggers
589
+
590
+ Initialize Foam before you import or construct the logger.
591
+
592
+ What Foam does depends on the logger version:
593
+
594
+ - Bunyan 1, Pino 7–10, and Winston 3: Foam adds trace IDs to every
595
+ record and automatically sends a copy to Foam.
596
+ - Pino 5.14–6 and Winston 1–2: Foam adds trace IDs, but these versions
597
+ have no way to attach a sender, so no copy reaches Foam. Upgrade the
598
+ logger, or call `log()` yourself.
599
+ - Everything else: Foam does nothing. Use `console.*` (captured
600
+ below), call `log()`, or upgrade the logger.
601
+
602
+ ### If the app already ships logs somewhere
603
+
604
+ - To a non-OTel destination (files, another vendor's transport): no
605
+ conflict. Keep the defaults; Foam sends its own copy alongside.
606
+ - Through its own OTel stream/transport (a Bunyan OTel stream,
607
+ Winston `OpenTelemetryTransportV3`): those already deliver to Foam
608
+ via the global LoggerProvider. Set `disableLogSending: true` so
609
+ records don't arrive twice.
610
+ - Through another OTel SDK's LoggerProvider: set
611
+ `disableLogSending: true` and attach
612
+ `createFoamIngestLogRecordProcessor` to that provider (see Public
613
+ API) so Foam gets a copy.
614
+ - Through `pino-opentelemetry-transport`: it runs in a worker
615
+ thread and never touches the in-process LoggerProvider, so nothing
616
+ conflicts. Keep `disableLogSending: false`, or Foam gets no Pino
617
+ records at all.
618
+ - Through a collector or agent reading stdout/files: no app changes;
619
+ add a Foam OTLP exporter to the collector config.
620
+
621
+ `log()` sends a single record straight to Foam in any setup. It is a
622
+ manual per-record call, not a mirror of the logger. Use it for
623
+ targeted, high-value records.
624
+
625
+ `ConsoleInstrumentation` turns calls to `console.*` into OTel log records.
626
+ It does not capture arbitrary stdout/stderr writes.
627
+
628
+ ```js
629
+ console.log("hi"); // captured
630
+ process.stdout.write("hi\n"); // not captured
631
+ ```
632
+
633
+ ## OpenTelemetry configuration and compliance
634
+
635
+ Foam uses the official OpenTelemetry JavaScript API, SDK, resource,
636
+ propagation, instrumentation, and OTLP exporter packages.
637
+
638
+ The [OpenTelemetry JavaScript compliance matrix](https://github.com/open-telemetry/opentelemetry-specification/blob/main/spec-compliance-matrix/js.yaml)
639
+
640
+ ## TODO(pcga11): OpenTelemetry profiling
641
+
642
+ The official OpenTelemetry JavaScript SDK has no in-process Profiles provider, processor, or exporter yet. Track upstream progress:
643
+
644
+ - [OpenTelemetry JS profiling implementation issue](https://github.com/open-telemetry/opentelemetry-js/issues/6500)
645
+ - [Profiling SIG language SDK support tracker](https://github.com/open-telemetry/sig-profiling/issues/106)
646
+ - [OpenTelemetry Profiles public alpha announcement](https://opentelemetry.io/blog/2026/profiles-alpha/)
647
+ - [OpenTelemetry eBPF profiler](https://github.com/open-telemetry/opentelemetry-ebpf-profiler)
648
+
649
+ ## TODO(pcga11): Anthropic instrumentation
650
+
651
+ There is no released official OpenTelemetry JavaScript instrumentation for the Anthropic SDK yet, but one is actively in progress in js-contrib, based on the OpenInference donation from Arize. Once `@opentelemetry/instrumentation-anthropic` is released (and picked up by `auto-instrumentations-node`), bundle it here like the OpenAI and aws-sdk ones. Until then, Anthropic coverage is handled case by case with the FDE (see FDE.md). Track upstream progress:
652
+
653
+ - [feat(instrumentation-anthropic): add basic messages instrumentation](https://github.com/open-telemetry/opentelemetry-js-contrib/pull/3664)
654
+ - [refactor(instrumentation-anthropic): use genai-util library](https://github.com/open-telemetry/opentelemetry-js-contrib/pull/3698)
655
+ - [Tracking: Migrate OpenInference JS instrumentations into opentelemetry-js-contrib](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3668)
656
+ - [feat: Add @opentelemetry/genai-util package for GenAI instrumentations](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3681)
@@ -0,0 +1,27 @@
1
+ export interface BeforeSendSpanEventEntry {
2
+ name: string;
3
+ attributes?: Record<string, unknown>;
4
+ time?: unknown;
5
+ }
6
+ export interface BeforeSendSpanLink {
7
+ context: Record<string, unknown>;
8
+ attributes?: Record<string, unknown>;
9
+ }
10
+ interface BeforeSendSpanEvent {
11
+ readonly type: "span";
12
+ name: string;
13
+ attributes: Record<string, unknown>;
14
+ events: BeforeSendSpanEventEntry[];
15
+ links: BeforeSendSpanLink[];
16
+ }
17
+ interface BeforeSendLogEvent {
18
+ readonly type: "log";
19
+ body?: unknown;
20
+ severityText?: string;
21
+ attributes: Record<string, unknown>;
22
+ }
23
+ export type BeforeSendEvent = BeforeSendSpanEvent | BeforeSendLogEvent;
24
+ export type BeforeSendHook = (event: BeforeSendEvent) => BeforeSendEvent | null;
25
+ export declare function resolveBeforeSend(hook: unknown): BeforeSendHook | undefined;
26
+ export declare function invokeBeforeSend(hook: BeforeSendHook, event: BeforeSendEvent): BeforeSendEvent | null | undefined;
27
+ export {};