@mark1russell7/otel-ts 0.0.0-bootstrap.0 → 0.1.2

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 (113) hide show
  1. package/README.md +417 -2
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/before-flush.d.ts +21 -0
  4. package/dist/before-flush.d.ts.map +1 -0
  5. package/dist/before-flush.js +46 -0
  6. package/dist/before-flush.js.map +1 -0
  7. package/dist/common.d.ts +11 -0
  8. package/dist/common.d.ts.map +1 -0
  9. package/dist/common.js +22 -0
  10. package/dist/common.js.map +1 -0
  11. package/dist/constants.d.ts +12 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +12 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/context-manager.d.ts +36 -0
  16. package/dist/context-manager.d.ts.map +1 -0
  17. package/dist/context-manager.js +60 -0
  18. package/dist/context-manager.js.map +1 -0
  19. package/dist/core.d.ts +14 -0
  20. package/dist/core.d.ts.map +1 -0
  21. package/dist/core.js +26 -0
  22. package/dist/core.js.map +1 -0
  23. package/dist/env.d.ts +6 -0
  24. package/dist/env.d.ts.map +1 -0
  25. package/dist/env.js +8 -0
  26. package/dist/env.js.map +1 -0
  27. package/dist/faro.d.ts +8 -0
  28. package/dist/faro.d.ts.map +1 -0
  29. package/dist/faro.js +24 -0
  30. package/dist/faro.js.map +1 -0
  31. package/dist/id.d.ts +22 -0
  32. package/dist/id.d.ts.map +1 -0
  33. package/dist/id.js +54 -0
  34. package/dist/id.js.map +1 -0
  35. package/dist/index.d.ts +14 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +33 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/init.d.ts +8 -0
  40. package/dist/init.d.ts.map +1 -0
  41. package/dist/init.js +135 -0
  42. package/dist/init.js.map +1 -0
  43. package/dist/lifecycle.d.ts +33 -0
  44. package/dist/lifecycle.d.ts.map +1 -0
  45. package/dist/lifecycle.js +39 -0
  46. package/dist/lifecycle.js.map +1 -0
  47. package/dist/logs.d.ts +6 -0
  48. package/dist/logs.d.ts.map +1 -0
  49. package/dist/logs.js +17 -0
  50. package/dist/logs.js.map +1 -0
  51. package/dist/metrics.d.ts +5 -0
  52. package/dist/metrics.d.ts.map +1 -0
  53. package/dist/metrics.js +37 -0
  54. package/dist/metrics.js.map +1 -0
  55. package/dist/node-testing.d.ts +23 -0
  56. package/dist/node-testing.d.ts.map +1 -0
  57. package/dist/node-testing.js +71 -0
  58. package/dist/node-testing.js.map +1 -0
  59. package/dist/node.d.ts +37 -0
  60. package/dist/node.d.ts.map +1 -0
  61. package/dist/node.js +54 -0
  62. package/dist/node.js.map +1 -0
  63. package/dist/resource.d.ts +38 -0
  64. package/dist/resource.d.ts.map +1 -0
  65. package/dist/resource.js +54 -0
  66. package/dist/resource.js.map +1 -0
  67. package/dist/session-processors.d.ts +9 -0
  68. package/dist/session-processors.d.ts.map +1 -0
  69. package/dist/session-processors.js +37 -0
  70. package/dist/session-processors.js.map +1 -0
  71. package/dist/session.d.ts +21 -0
  72. package/dist/session.d.ts.map +1 -0
  73. package/dist/session.js +76 -0
  74. package/dist/session.js.map +1 -0
  75. package/dist/trace-echo.d.ts +60 -0
  76. package/dist/trace-echo.d.ts.map +1 -0
  77. package/dist/trace-echo.js +118 -0
  78. package/dist/trace-echo.js.map +1 -0
  79. package/dist/tracing.d.ts +7 -0
  80. package/dist/tracing.d.ts.map +1 -0
  81. package/dist/tracing.js +48 -0
  82. package/dist/tracing.js.map +1 -0
  83. package/dist/types.d.ts +210 -0
  84. package/dist/types.d.ts.map +1 -0
  85. package/dist/types.js +2 -0
  86. package/dist/types.js.map +1 -0
  87. package/dist/zone.d.ts +14 -0
  88. package/dist/zone.d.ts.map +1 -0
  89. package/dist/zone.js +40 -0
  90. package/dist/zone.js.map +1 -0
  91. package/package.json +84 -5
  92. package/src/before-flush.ts +64 -0
  93. package/src/common.ts +46 -0
  94. package/src/constants.ts +12 -0
  95. package/src/context-manager.ts +82 -0
  96. package/src/core.ts +38 -0
  97. package/src/env.ts +7 -0
  98. package/src/faro.ts +29 -0
  99. package/src/id.ts +59 -0
  100. package/src/index.ts +45 -0
  101. package/src/init.ts +177 -0
  102. package/src/lifecycle.ts +52 -0
  103. package/src/logs.ts +30 -0
  104. package/src/metrics.ts +63 -0
  105. package/src/node-testing.ts +88 -0
  106. package/src/node.ts +89 -0
  107. package/src/resource.ts +73 -0
  108. package/src/session-processors.ts +48 -0
  109. package/src/session.ts +86 -0
  110. package/src/trace-echo.ts +137 -0
  111. package/src/tracing.ts +64 -0
  112. package/src/types.ts +261 -0
  113. package/src/zone.ts +52 -0
package/src/session.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { SESSION_STORAGE_KEY } from "./constants.js";
2
+ import { randomUuid } from "./id.js";
3
+
4
+ interface StoredSession {
5
+ id: string;
6
+ timestamp: number;
7
+ }
8
+
9
+ /** sessionStorage, or undefined where it doesn't exist (e.g. Web Workers) */
10
+ function getSessionStorage(): Storage | undefined {
11
+ try {
12
+ return typeof sessionStorage === "undefined" ? undefined : sessionStorage;
13
+ } catch {
14
+ // Reading it throws where storage is blocked (e.g. sandboxed iframes)
15
+ return undefined;
16
+ }
17
+ }
18
+
19
+ function isStoredSession(value: unknown): value is StoredSession {
20
+ if (typeof value !== "object" || value === null) return false;
21
+ const { id, timestamp } = value as Partial<StoredSession>;
22
+ return typeof id === "string" && id !== "" && typeof timestamp === "number";
23
+ }
24
+
25
+ function readSession(storage: Storage): StoredSession | undefined {
26
+ try {
27
+ const raw = storage.getItem(SESSION_STORAGE_KEY);
28
+ if (!raw) return undefined;
29
+ const stored: unknown = JSON.parse(raw);
30
+ return isStoredSession(stored) ? stored : undefined;
31
+ } catch {
32
+ // sessionStorage unavailable or corrupt — treat as no session
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ function writeSession(storage: Storage, session: StoredSession): void {
38
+ try {
39
+ storage.setItem(SESSION_STORAGE_KEY, JSON.stringify(session));
40
+ } catch {
41
+ // Storage full or unavailable — proceed without persistence
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Returns a function that reports the current session ID. Log records and
47
+ * spans call it as they are created, so a session rotation shows up on the
48
+ * next record.
49
+ *
50
+ * Each call counts as activity: it resumes the session stored in
51
+ * sessionStorage and refreshes its timestamp, or starts a new session once
52
+ * `ttlMs` has passed without activity. A session that another tracker in the
53
+ * same tab started or rotated is adopted, so all of them agree.
54
+ *
55
+ * Where sessionStorage is missing, blocked or full (Web Workers, sandboxed
56
+ * iframes), the session lives in this tracker's memory, with the same TTL.
57
+ */
58
+ export function createSessionTracker(ttlMs: number): () => string {
59
+ // The session this tracker last reported
60
+ let current: StoredSession | undefined;
61
+
62
+ return () => {
63
+ const now = Date.now();
64
+ const storage = getSessionStorage();
65
+ const stored = storage ? readSession(storage) : undefined;
66
+
67
+ // Prefer storage: it is shared with the tab's other trackers
68
+ const live = [stored, current].find(
69
+ (session) => session !== undefined && now - session.timestamp < ttlMs,
70
+ );
71
+
72
+ current = { id: live?.id ?? randomUuid(), timestamp: now };
73
+ if (storage) writeSession(storage, current);
74
+
75
+ return current.id;
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Resumes the session stored in sessionStorage and refreshes its timestamp,
81
+ * or starts a new session if there is none or it is older than `ttlMs`.
82
+ * Where sessionStorage is missing or blocked, returns a new ID on every call.
83
+ */
84
+ export function getOrCreateSessionId(ttlMs: number): string {
85
+ return createSessionTracker(ttlMs)();
86
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The trace of a write, carried to its echo. A write ends its request, and a
3
+ * change stream (or another queue) reports the change later, without the
4
+ * context of the request. The write handler keeps the trace context of the
5
+ * write for some seconds, keyed by what the echo can name (for example the
6
+ * collection and the id). The handler of the echo takes it, and the clients
7
+ * then apply the echo in the trace of the write.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ import { context, defaultTextMapGetter, propagation, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, type Attributes, type Tracer } from "@opentelemetry/api";
12
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
13
+
14
+ /** The W3C propagator of runInRemoteTrace: it reads the traceparent also when no global propagator is set. */
15
+ const W3C = new W3CTraceContextPropagator();
16
+
17
+ const TRACEPARENT = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
18
+
19
+ /**
20
+ * The W3C trace context to pass on: the context of the active span when the
21
+ * SDK operates, else the `traceparent` header of the request.
22
+ */
23
+ export function outgoingTraceparent(header: unknown): string | undefined {
24
+ const carrier: Record<string, string> = {};
25
+ propagation.inject(context.active(), carrier);
26
+ const value = carrier["traceparent"] ?? (typeof header === "string" ? header : undefined);
27
+ return value && TRACEPARENT.test(value) ? value : undefined;
28
+ }
29
+
30
+ /** A store of the trace contexts of the writes, until their echoes arrive */
31
+ export interface TraceEcho {
32
+ /** Keep the trace of a write to (`scope`, `id`). It ignores an empty trace. */
33
+ remember(scope: string, id: unknown, traceparent: string | undefined, now?: number): void;
34
+ /** The trace of the write that caused this echo, one time. Undefined when none or expired. */
35
+ take(scope: string, id: unknown, now?: number): string | undefined;
36
+ /** The count of the kept traces */
37
+ readonly size: number;
38
+ }
39
+
40
+ /** A trace-echo store: each trace lives `ttlMs` (default 10 s), `maxEntries` at most (default 10,000). */
41
+ export function createTraceEcho(options: { ttlMs?: number; maxEntries?: number } = {}): TraceEcho {
42
+ const ttl = options.ttlMs ?? 10_000;
43
+ const max = options.maxEntries ?? 10_000;
44
+ const pending = new Map<string, { traceparent: string; at: number }>();
45
+ const keyOf = (scope: string, id: unknown): string => `${scope}\u0000${String(id)}`;
46
+ /** Drop the expired entries, and when the store is full, the oldest half */
47
+ const sweep = (now: number): void => {
48
+ for (const [k, v] of pending) if (now - v.at > ttl) pending.delete(k);
49
+ if (pending.size >= max) {
50
+ let drop = Math.floor(pending.size / 2);
51
+ for (const k of pending.keys()) {
52
+ if (drop-- <= 0) break;
53
+ pending.delete(k);
54
+ }
55
+ }
56
+ };
57
+ return {
58
+ remember(scope, id, traceparent, now = Date.now()) {
59
+ if (!traceparent) return;
60
+ if (pending.size >= max) sweep(now);
61
+ pending.set(keyOf(scope, id), { traceparent, at: now });
62
+ },
63
+ take(scope, id, now = Date.now()) {
64
+ const key = keyOf(scope, id);
65
+ const hit = pending.get(key);
66
+ if (!hit) return undefined;
67
+ pending.delete(key);
68
+ return now - hit.at <= ttl ? hit.traceparent : undefined;
69
+ },
70
+ get size() {
71
+ return pending.size;
72
+ },
73
+ };
74
+ }
75
+
76
+ /** The options of `runInRemoteTrace` */
77
+ export interface RemoteTraceOptions {
78
+ /** The name of the span. Default: `remote.apply`. */
79
+ name?: string;
80
+ /** The attributes of the span, for example the collection and the kind of the change. */
81
+ attributes?: Attributes;
82
+ /** The tracer of the span. Default: the global tracer `@mark1russell7/otel-ts`. */
83
+ tracer?: Tracer;
84
+ }
85
+
86
+ /**
87
+ * The other end of the trace echo: run `fn` inside the trace that a message
88
+ * carries. A message (for example a change on a live connection) can carry the
89
+ * `traceparent` of the write that caused it. This function starts a consumer
90
+ * span whose parent is that trace, and runs `fn` with the span active. Thus one
91
+ * trace shows the action, the write, the server and each client that applies
92
+ * the change. Without a valid `traceparent`, it only runs `fn`.
93
+ *
94
+ * The span ends when `fn` returns, or when the promise of `fn` settles. An
95
+ * error of `fn` sets the status of the span to ERROR, and passes through.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * socket.onChange((msg) => runInRemoteTrace(msg.traceparent, () => store.apply(msg), {
100
+ * name: "realtime.echo",
101
+ * attributes: { "app.collection": msg.collection },
102
+ * }));
103
+ * ```
104
+ */
105
+ export function runInRemoteTrace<T>(traceparent: string | undefined, fn: () => T, options: RemoteTraceOptions = {}): T {
106
+ if (!traceparent || !TRACEPARENT.test(traceparent)) return fn();
107
+ const parent = W3C.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
108
+ const tracer = options.tracer ?? trace.getTracer("@mark1russell7/otel-ts");
109
+ const span = tracer.startSpan(options.name ?? "remote.apply", { kind: SpanKind.CONSUMER, ...(options.attributes ? { attributes: options.attributes } : {}) }, parent);
110
+ const fail = (error: unknown): void => {
111
+ span.recordException(error instanceof Error ? error : String(error));
112
+ span.setStatus({ code: SpanStatusCode.ERROR });
113
+ };
114
+ let result: T;
115
+ try {
116
+ result = context.with(trace.setSpan(parent, span), fn);
117
+ } catch (error) {
118
+ fail(error);
119
+ span.end();
120
+ throw error;
121
+ }
122
+ if (result && typeof (result as { then?: unknown }).then === "function") {
123
+ return (result as unknown as Promise<unknown>).then(
124
+ (value) => {
125
+ span.end();
126
+ return value;
127
+ },
128
+ (error: unknown) => {
129
+ fail(error);
130
+ span.end();
131
+ throw error;
132
+ },
133
+ ) as T;
134
+ }
135
+ span.end();
136
+ return result;
137
+ }
package/src/tracing.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
3
+ import type { ContextManager } from "@opentelemetry/api";
4
+ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
5
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
6
+ import { getWebAutoInstrumentations } from "@opentelemetry/auto-instrumentations-web";
7
+ import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-task";
8
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
9
+ import type { ResolvedConfig } from "./types.js";
10
+ import { hasDom } from "./env.js";
11
+ import {
12
+ createSessionSpanProcessor,
13
+ type SessionIdReader,
14
+ } from "./session-processors.js";
15
+
16
+ export function setupTracing(
17
+ resource: Resource,
18
+ config: ResolvedConfig,
19
+ getSessionId: SessionIdReader,
20
+ contextManager: ContextManager,
21
+ ): WebTracerProvider {
22
+ // Document-load and user-interaction need a DOM; skip them in Web Workers
23
+ const dom = hasDom();
24
+
25
+ const exporter = new OTLPTraceExporter({
26
+ url: `${config.endpoint}/v1/traces`,
27
+ });
28
+
29
+ const provider = new WebTracerProvider({
30
+ resource,
31
+ spanProcessors: [
32
+ createSessionSpanProcessor(getSessionId),
33
+ new BatchSpanProcessor(exporter),
34
+ ],
35
+ });
36
+
37
+ provider.register({ contextManager });
38
+
39
+ registerInstrumentations({
40
+ instrumentations: [
41
+ getWebAutoInstrumentations({
42
+ "@opentelemetry/instrumentation-document-load": {
43
+ enabled: config.instrumentDocumentLoad && dom,
44
+ },
45
+ "@opentelemetry/instrumentation-fetch": {
46
+ enabled: config.instrumentFetch,
47
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls,
48
+ },
49
+ "@opentelemetry/instrumentation-xml-http-request": {
50
+ enabled: config.instrumentXhr,
51
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls,
52
+ },
53
+ "@opentelemetry/instrumentation-user-interaction": {
54
+ enabled: config.instrumentUserInteraction && dom,
55
+ },
56
+ }),
57
+ ...(config.instrumentLongTask
58
+ ? [new LongTaskInstrumentation()]
59
+ : []),
60
+ ],
61
+ });
62
+
63
+ return provider;
64
+ }
package/src/types.ts ADDED
@@ -0,0 +1,261 @@
1
+ import type { ContextManager } from "@opentelemetry/api";
2
+ import type { StateTransition } from "page-lifecycle-tracker";
3
+
4
+ export type MetricsTemporality = "cumulative" | "delta";
5
+
6
+ /**
7
+ * The names of the context managers of otel-ts. Each entry has some of them:
8
+ * - "async": the `AsyncContextManager` of async-browser-context. Only in
9
+ * `@mark1russell7/otel-ts`, where it is the default. Its runtime patches
10
+ * `Promise.prototype.then`, the timers, the event listeners and other
11
+ * callback APIs, so their callbacks keep the active span. After a native
12
+ * `await`, the span stays only in code that the Vite plugin or the Babel
13
+ * preset of async-browser-context transforms. On Node.js, it uses the
14
+ * native `AsyncLocalStorage`.
15
+ * - "zone": `ZoneContextManager` (zone.js). Only in
16
+ * `@mark1russell7/otel-ts/zone`, where it is the default. It keeps the
17
+ * active span across timers, events and `then` callbacks, but not after a
18
+ * native `await`.
19
+ * - "stack": `StackContextManager`. In each entry, and the default of
20
+ * `@mark1russell7/otel-ts/core`. It patches nothing, and it keeps the active
21
+ * span only in synchronous code.
22
+ */
23
+ export type ContextManagerName = "async" | "stack" | "zone";
24
+
25
+ /**
26
+ * A value of the `contextManager` option: a name, or a `ContextManager`
27
+ * instance of the app. `Name` is the names that the entry has.
28
+ */
29
+ export type ContextManagerOption<Name extends ContextManagerName = ContextManagerName> =
30
+ | Name
31
+ | ContextManager;
32
+
33
+ /** How histogram instruments aggregate their measurements */
34
+ export type HistogramAggregation = "explicit" | "exponential";
35
+
36
+ /**
37
+ * The configuration of `init()`. `Name` is the context manager names that the
38
+ * entry has. Each entry exports `OtelTsConfig` with its own names.
39
+ */
40
+ export interface OtelTsConfig<Name extends ContextManagerName = ContextManagerName> {
41
+ /** OTLP HTTP endpoint. Default: "http://localhost:4318" */
42
+ endpoint?: string;
43
+
44
+ /** Service name for resource identification. Default: "frontend-app" */
45
+ serviceName?: string;
46
+
47
+ /** Service version. Default: "0.0.0" */
48
+ serviceVersion?: string;
49
+
50
+ /**
51
+ * Sets the `service.instance.id` resource attribute, which Prometheus and
52
+ * Mimir turn into the `instance` label. Every SDK instance must have its
53
+ * own value, or many browsers write to the same metric series.
54
+ * Default: a new random UUID v4 for every `init()` call (see
55
+ * `createInstanceId()`), shared by the metrics, logs and traces resources.
56
+ * Never persisted, never derived from the session ID.
57
+ */
58
+ serviceInstanceId?: string;
59
+
60
+ /** Additional resource attributes */
61
+ resourceAttributes?: Record<string, string>;
62
+
63
+ /**
64
+ * Put the browser attributes of the semantic conventions on the resource:
65
+ * `browser.brands`, `browser.platform`, `browser.mobile`,
66
+ * `browser.language` and `user_agent.original`, from `navigator`.
67
+ * Default: true
68
+ */
69
+ browserAttributes?: boolean;
70
+
71
+ // --- Tracing ---
72
+
73
+ /** Enable tracing. Default: true */
74
+ tracing?: boolean;
75
+
76
+ /**
77
+ * The context manager of the tracer provider. Default: "async" in
78
+ * `@mark1russell7/otel-ts`, "zone" in `@mark1russell7/otel-ts/zone` and
79
+ * "stack" in `@mark1russell7/otel-ts/core`.
80
+ */
81
+ contextManager?: ContextManagerOption<Name>;
82
+
83
+ /** Propagate trace context to these origins. Default: all origins */
84
+ propagateTraceHeaderCorsUrls?: Array<string | RegExp>;
85
+
86
+ // --- Metrics ---
87
+
88
+ /** Enable metrics. Default: true */
89
+ metrics?: boolean;
90
+
91
+ /**
92
+ * Metrics export interval in ms. Default: 15000. Telemetry is also flushed
93
+ * whenever the page is hidden.
94
+ */
95
+ metricsExportIntervalMs?: number;
96
+
97
+ /**
98
+ * Aggregation temporality requested from the OTLP metrics exporter.
99
+ * "cumulative" exports running totals; "delta" exports counters and
100
+ * histograms as the change since the previous export (up-down counters stay
101
+ * cumulative). Default: "cumulative"
102
+ */
103
+ metricsTemporality?: MetricsTemporality;
104
+
105
+ /**
106
+ * Aggregation for histogram instruments.
107
+ * "explicit": explicit-bucket histograms, with the boundaries from the
108
+ * instrument's advice or the SDK defaults. Every backend stores these.
109
+ * "exponential": base-2 exponential histograms, for every histogram
110
+ * instrument (advice boundaries are ignored). Mimir stores each one as a
111
+ * single native-histogram series; this needs native-histogram ingestion
112
+ * turned on (`native_histograms_ingestion_enabled`), or the data is lost.
113
+ * Default: "explicit"
114
+ */
115
+ histogramAggregation?: HistogramAggregation;
116
+
117
+ // --- Logs ---
118
+
119
+ /** Enable logs. Default: true */
120
+ logs?: boolean;
121
+
122
+ // --- Auto-Instrumentations ---
123
+
124
+ /** Enable document-load instrumentation. Default: true. Needs a DOM. */
125
+ instrumentDocumentLoad?: boolean;
126
+
127
+ /** Enable fetch instrumentation. Default: true */
128
+ instrumentFetch?: boolean;
129
+
130
+ /** Enable XMLHttpRequest instrumentation. Default: true */
131
+ instrumentXhr?: boolean;
132
+
133
+ /** Enable user-interaction instrumentation. Default: true. Needs a DOM. */
134
+ instrumentUserInteraction?: boolean;
135
+
136
+ /** Enable long-task instrumentation. Default: true */
137
+ instrumentLongTask?: boolean;
138
+
139
+ // --- Faro ---
140
+
141
+ /**
142
+ * Enable Grafana Faro integration. Default: true. Faro starts only when
143
+ * `faroCollectorUrl` is set and there is a DOM.
144
+ */
145
+ faro?: boolean;
146
+
147
+ /**
148
+ * Faro collector URL. Faro has nowhere to send data without it, so it does
149
+ * not start. Omit for local OTLP-only mode.
150
+ */
151
+ faroCollectorUrl?: string;
152
+
153
+ /** Faro app name. Defaults to serviceName. */
154
+ faroAppName?: string;
155
+
156
+ // --- Session ---
157
+
158
+ /**
159
+ * Enable session tracking. Default: true. The session ID lives in
160
+ * sessionStorage (in memory where there is none) and rotates after 30
161
+ * minutes without activity. When false, each `init()` call gets a new
162
+ * random session ID that is not stored.
163
+ *
164
+ * The session ID is set as the `session.id` attribute of every log record
165
+ * and span, never on the resource.
166
+ */
167
+ sessionTracking?: boolean;
168
+
169
+ // --- Debug ---
170
+
171
+ /** Enable console debug output. Default: false */
172
+ debug?: boolean;
173
+ }
174
+
175
+ export interface ResolvedConfig {
176
+ endpoint: string;
177
+ serviceName: string;
178
+ serviceVersion: string;
179
+ serviceInstanceId: string;
180
+ resourceAttributes: Record<string, string>;
181
+ browserAttributes: boolean;
182
+ tracing: boolean;
183
+ contextManager: ContextManagerOption;
184
+ propagateTraceHeaderCorsUrls: Array<string | RegExp>;
185
+ metrics: boolean;
186
+ metricsExportIntervalMs: number;
187
+ metricsTemporality: MetricsTemporality;
188
+ histogramAggregation: HistogramAggregation;
189
+ logs: boolean;
190
+ instrumentDocumentLoad: boolean;
191
+ instrumentFetch: boolean;
192
+ instrumentXhr: boolean;
193
+ instrumentUserInteraction: boolean;
194
+ instrumentLongTask: boolean;
195
+ faro: boolean;
196
+ faroCollectorUrl: string | undefined;
197
+ faroAppName: string | undefined;
198
+ sessionTracking: boolean;
199
+ debug: boolean;
200
+ }
201
+
202
+ /** What started a flush */
203
+ export interface FlushCause {
204
+ /**
205
+ * The lifecycle transition that started the flush: to `hidden`, `frozen`
206
+ * or `terminated` (page-lifecycle-tracker). Undefined for a call of
207
+ * `forceFlush()` or `shutdown()`.
208
+ */
209
+ readonly transition?: StateTransition;
210
+ /**
211
+ * @deprecated otel-ts no longer passes the page event. It flushes in the
212
+ * `export` phase of the shared lifecycle tracker, after the monitors of the
213
+ * page recorded the transition, so a listener does not need the event.
214
+ */
215
+ readonly event?: Event;
216
+ }
217
+
218
+ export interface OtelTsInstance {
219
+ /**
220
+ * Flush pending telemetry and shut down all providers. Runs once; later
221
+ * calls return the same promise.
222
+ */
223
+ shutdown(): Promise<void>;
224
+
225
+ /**
226
+ * Export pending telemetry now; providers keep running. Also runs
227
+ * automatically whenever the page is hidden.
228
+ */
229
+ forceFlush(): Promise<void>;
230
+
231
+ /**
232
+ * Register a function that runs synchronously just before each flush:
233
+ * every page hide, the shutdown when the page is discarded, and every
234
+ * manual `forceFlush()` or `shutdown()`. Values it records go out in that
235
+ * flush, whatever order the page's `pagehide` listeners run in (Chromium
236
+ * runs window listeners in registration order). Listeners run in
237
+ * registration order; one that throws doesn't stop the others or the
238
+ * flush, and only the first error is logged. They don't run after
239
+ * shutdown, and a returned promise isn't awaited.
240
+ *
241
+ * The listener gets the cause of the flush. For a page hide it has the
242
+ * `visibilitychange` or `pagehide` event, so a listener can handle that
243
+ * event before the flush even when its own listener of that event would
244
+ * run too late, as in Chromium.
245
+ *
246
+ * @returns A function that removes the listener
247
+ */
248
+ onBeforeFlush(listener: (cause: FlushCause) => void): () => void;
249
+
250
+ /**
251
+ * Get the current session ID: the value the next log record or span gets.
252
+ * Counts as activity, like emitting a log record or starting a span.
253
+ */
254
+ getSessionId(): string;
255
+
256
+ /** Get a named Meter for creating instruments (histograms, gauges, counters) */
257
+ getMeter(name: string): import("@opentelemetry/api").Meter;
258
+
259
+ /** Get a named Logger for emitting log records */
260
+ getLogger(name: string): import("@opentelemetry/api-logs").Logger;
261
+ }
package/src/zone.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The zone.js entry, `@mark1russell7/otel-ts/zone`. The same API as
3
+ * `@mark1russell7/otel-ts`, but it keeps the active span with zone.js: the
4
+ * default `contextManager` is "zone".
5
+ *
6
+ * ```ts
7
+ * import { init } from "@mark1russell7/otel-ts/zone";
8
+ *
9
+ * const otel = init();
10
+ * ```
11
+ *
12
+ * zone.js (through `@opentelemetry/context-zone`) patches `Promise`, the
13
+ * timers and the event listeners of the page when this entry loads. This
14
+ * entry does not import async-browser-context: the two libraries cannot share
15
+ * a page.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { ZoneContextManager } from "@opentelemetry/context-zone";
20
+ import {
21
+ createStackContextManager,
22
+ type EntryContextManagers,
23
+ } from "./context-manager.js";
24
+ import { initWith } from "./init.js";
25
+ import type * as Types from "./types.js";
26
+
27
+ export * from "./common.js";
28
+
29
+ /** The context manager names of this entry: "zone" (default) and "stack" */
30
+ export type ContextManagerOption = Types.ContextManagerOption<"zone" | "stack">;
31
+
32
+ /** The configuration of `init()` in this entry */
33
+ export type OtelTsConfig = Types.OtelTsConfig<"zone" | "stack">;
34
+
35
+ const managers: EntryContextManagers = {
36
+ entry: "zone",
37
+ defaultName: "zone",
38
+ factories: {
39
+ zone: () => new ZoneContextManager(),
40
+ stack: createStackContextManager,
41
+ },
42
+ };
43
+
44
+ /**
45
+ * Starts traces, metrics and logs. The default `contextManager` is "zone".
46
+ *
47
+ * @throws For `contextManager: "async"`: async-browser-context cannot share
48
+ * the page with zone.js. Import `init` from `@mark1russell7/otel-ts`.
49
+ */
50
+ export function init(config?: OtelTsConfig): Types.OtelTsInstance {
51
+ return initWith(managers, config);
52
+ }