@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
@@ -0,0 +1,9 @@
1
+ import type { LogRecordProcessor } from "@opentelemetry/sdk-logs";
2
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace-base";
3
+ /** Returns the current session ID; called once per log record or span */
4
+ export type SessionIdReader = () => string;
5
+ /** Sets `session.id` on each log record as it is emitted */
6
+ export declare function createSessionLogRecordProcessor(getSessionId: SessionIdReader): LogRecordProcessor;
7
+ /** Sets `session.id` on each span as it starts */
8
+ export declare function createSessionSpanProcessor(getSessionId: SessionIdReader): SpanProcessor;
9
+ //# sourceMappingURL=session-processors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-processors.d.ts","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAGnE,yEAAyE;AACzE,MAAM,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC;AAa3C,4DAA4D;AAC5D,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE,eAAe,GAC5B,kBAAkB,CAUpB;AAED,kDAAkD;AAClD,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,eAAe,GAC5B,aAAa,CAWf"}
@@ -0,0 +1,37 @@
1
+ import { ATTR_SESSION_ID } from "./constants.js";
2
+ /*
3
+ * The OpenTelemetry Browser SDK's session-processor pattern: `session.id` is
4
+ * an attribute of each log record and span, read as the record is created,
5
+ * not a resource attribute. Resources are fixed for the life of a provider,
6
+ * so a resource `session.id` goes stale when the session rotates, and on the
7
+ * metrics resource it inflates Prometheus `target_info`.
8
+ *
9
+ * A `session.id` the caller set explicitly (e.g. on a `session.end` event
10
+ * for the previous session) is kept.
11
+ */
12
+ /** Sets `session.id` on each log record as it is emitted */
13
+ export function createSessionLogRecordProcessor(getSessionId) {
14
+ return {
15
+ onEmit(logRecord) {
16
+ if (logRecord.attributes[ATTR_SESSION_ID] === undefined) {
17
+ logRecord.setAttribute(ATTR_SESSION_ID, getSessionId());
18
+ }
19
+ },
20
+ forceFlush: () => Promise.resolve(),
21
+ shutdown: () => Promise.resolve(),
22
+ };
23
+ }
24
+ /** Sets `session.id` on each span as it starts */
25
+ export function createSessionSpanProcessor(getSessionId) {
26
+ return {
27
+ onStart(span) {
28
+ if (span.attributes[ATTR_SESSION_ID] === undefined) {
29
+ span.setAttribute(ATTR_SESSION_ID, getSessionId());
30
+ }
31
+ },
32
+ onEnd() { },
33
+ forceFlush: () => Promise.resolve(),
34
+ shutdown: () => Promise.resolve(),
35
+ };
36
+ }
37
+ //# sourceMappingURL=session-processors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-processors.js","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAKjD;;;;;;;;;GASG;AAEH,4DAA4D;AAC5D,MAAM,UAAU,+BAA+B,CAC7C,YAA6B;IAE7B,OAAO;QACL,MAAM,CAAC,SAAS;YACd,IAAI,SAAS,CAAC,UAAU,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE,CAAC;gBACxD,SAAS,CAAC,YAAY,CAAC,eAAe,EAAE,YAAY,EAAE,CAAC,CAAC;YAC1D,CAAC;QACH,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;QACnC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;KAClC,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,0BAA0B,CACxC,YAA6B;IAE7B,OAAO;QACL,OAAO,CAAC,IAAI;YACV,IAAI,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE,CAAC;gBACnD,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,YAAY,EAAE,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;QACD,KAAK,KAAI,CAAC;QACV,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;QACnC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;KAClC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Returns a function that reports the current session ID. Log records and
3
+ * spans call it as they are created, so a session rotation shows up on the
4
+ * next record.
5
+ *
6
+ * Each call counts as activity: it resumes the session stored in
7
+ * sessionStorage and refreshes its timestamp, or starts a new session once
8
+ * `ttlMs` has passed without activity. A session that another tracker in the
9
+ * same tab started or rotated is adopted, so all of them agree.
10
+ *
11
+ * Where sessionStorage is missing, blocked or full (Web Workers, sandboxed
12
+ * iframes), the session lives in this tracker's memory, with the same TTL.
13
+ */
14
+ export declare function createSessionTracker(ttlMs: number): () => string;
15
+ /**
16
+ * Resumes the session stored in sessionStorage and refreshes its timestamp,
17
+ * or starts a new session if there is none or it is older than `ttlMs`.
18
+ * Where sessionStorage is missing or blocked, returns a new ID on every call.
19
+ */
20
+ export declare function getOrCreateSessionId(ttlMs: number): string;
21
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AA4CA;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,MAAM,CAmBhE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE1D"}
@@ -0,0 +1,76 @@
1
+ import { SESSION_STORAGE_KEY } from "./constants.js";
2
+ import { randomUuid } from "./id.js";
3
+ /** sessionStorage, or undefined where it doesn't exist (e.g. Web Workers) */
4
+ function getSessionStorage() {
5
+ try {
6
+ return typeof sessionStorage === "undefined" ? undefined : sessionStorage;
7
+ }
8
+ catch {
9
+ // Reading it throws where storage is blocked (e.g. sandboxed iframes)
10
+ return undefined;
11
+ }
12
+ }
13
+ function isStoredSession(value) {
14
+ if (typeof value !== "object" || value === null)
15
+ return false;
16
+ const { id, timestamp } = value;
17
+ return typeof id === "string" && id !== "" && typeof timestamp === "number";
18
+ }
19
+ function readSession(storage) {
20
+ try {
21
+ const raw = storage.getItem(SESSION_STORAGE_KEY);
22
+ if (!raw)
23
+ return undefined;
24
+ const stored = JSON.parse(raw);
25
+ return isStoredSession(stored) ? stored : undefined;
26
+ }
27
+ catch {
28
+ // sessionStorage unavailable or corrupt — treat as no session
29
+ return undefined;
30
+ }
31
+ }
32
+ function writeSession(storage, session) {
33
+ try {
34
+ storage.setItem(SESSION_STORAGE_KEY, JSON.stringify(session));
35
+ }
36
+ catch {
37
+ // Storage full or unavailable — proceed without persistence
38
+ }
39
+ }
40
+ /**
41
+ * Returns a function that reports the current session ID. Log records and
42
+ * spans call it as they are created, so a session rotation shows up on the
43
+ * next record.
44
+ *
45
+ * Each call counts as activity: it resumes the session stored in
46
+ * sessionStorage and refreshes its timestamp, or starts a new session once
47
+ * `ttlMs` has passed without activity. A session that another tracker in the
48
+ * same tab started or rotated is adopted, so all of them agree.
49
+ *
50
+ * Where sessionStorage is missing, blocked or full (Web Workers, sandboxed
51
+ * iframes), the session lives in this tracker's memory, with the same TTL.
52
+ */
53
+ export function createSessionTracker(ttlMs) {
54
+ // The session this tracker last reported
55
+ let current;
56
+ return () => {
57
+ const now = Date.now();
58
+ const storage = getSessionStorage();
59
+ const stored = storage ? readSession(storage) : undefined;
60
+ // Prefer storage: it is shared with the tab's other trackers
61
+ const live = [stored, current].find((session) => session !== undefined && now - session.timestamp < ttlMs);
62
+ current = { id: live?.id ?? randomUuid(), timestamp: now };
63
+ if (storage)
64
+ writeSession(storage, current);
65
+ return current.id;
66
+ };
67
+ }
68
+ /**
69
+ * Resumes the session stored in sessionStorage and refreshes its timestamp,
70
+ * or starts a new session if there is none or it is older than `ttlMs`.
71
+ * Where sessionStorage is missing or blocked, returns a new ID on every call.
72
+ */
73
+ export function getOrCreateSessionId(ttlMs) {
74
+ return createSessionTracker(ttlMs)();
75
+ }
76
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAOrC,6EAA6E;AAC7E,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,OAAO,OAAO,cAAc,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACP,sEAAsE;QACtE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,GAAG,KAA+B,CAAC;IAC1D,OAAO,OAAO,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,EAAE,IAAI,OAAO,SAAS,KAAK,QAAQ,CAAC;AAC9E,CAAC;AAED,SAAS,WAAW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GAAG,EAAE,CAAC;QAC3D,IAAI,OAAO;YAAE,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE5C,OAAO,OAAO,CAAC,EAAE,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,OAAO,oBAAoB,CAAC,KAAK,CAAC,EAAE,CAAC;AACvC,CAAC"}
@@ -0,0 +1,60 @@
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 { type Attributes, type Tracer } from "@opentelemetry/api";
12
+ /**
13
+ * The W3C trace context to pass on: the context of the active span when the
14
+ * SDK operates, else the `traceparent` header of the request.
15
+ */
16
+ export declare function outgoingTraceparent(header: unknown): string | undefined;
17
+ /** A store of the trace contexts of the writes, until their echoes arrive */
18
+ export interface TraceEcho {
19
+ /** Keep the trace of a write to (`scope`, `id`). It ignores an empty trace. */
20
+ remember(scope: string, id: unknown, traceparent: string | undefined, now?: number): void;
21
+ /** The trace of the write that caused this echo, one time. Undefined when none or expired. */
22
+ take(scope: string, id: unknown, now?: number): string | undefined;
23
+ /** The count of the kept traces */
24
+ readonly size: number;
25
+ }
26
+ /** A trace-echo store: each trace lives `ttlMs` (default 10 s), `maxEntries` at most (default 10,000). */
27
+ export declare function createTraceEcho(options?: {
28
+ ttlMs?: number;
29
+ maxEntries?: number;
30
+ }): TraceEcho;
31
+ /** The options of `runInRemoteTrace` */
32
+ export interface RemoteTraceOptions {
33
+ /** The name of the span. Default: `remote.apply`. */
34
+ name?: string;
35
+ /** The attributes of the span, for example the collection and the kind of the change. */
36
+ attributes?: Attributes;
37
+ /** The tracer of the span. Default: the global tracer `@mark1russell7/otel-ts`. */
38
+ tracer?: Tracer;
39
+ }
40
+ /**
41
+ * The other end of the trace echo: run `fn` inside the trace that a message
42
+ * carries. A message (for example a change on a live connection) can carry the
43
+ * `traceparent` of the write that caused it. This function starts a consumer
44
+ * span whose parent is that trace, and runs `fn` with the span active. Thus one
45
+ * trace shows the action, the write, the server and each client that applies
46
+ * the change. Without a valid `traceparent`, it only runs `fn`.
47
+ *
48
+ * The span ends when `fn` returns, or when the promise of `fn` settles. An
49
+ * error of `fn` sets the status of the span to ERROR, and passes through.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * socket.onChange((msg) => runInRemoteTrace(msg.traceparent, () => store.apply(msg), {
54
+ * name: "realtime.echo",
55
+ * attributes: { "app.collection": msg.collection },
56
+ * }));
57
+ * ```
58
+ */
59
+ export declare function runInRemoteTrace<T>(traceparent: string | undefined, fn: () => T, options?: RemoteTraceOptions): T;
60
+ //# sourceMappingURL=trace-echo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-echo.d.ts","sourceRoot":"","sources":["../src/trace-echo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAA6F,KAAK,UAAU,EAAE,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAQ7J;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAKvE;AAED,6EAA6E;AAC7E,MAAM,WAAW,SAAS;IACxB,+EAA+E;IAC/E,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1F,8FAA8F;IAC9F,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACnE,mCAAmC;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,0GAA0G;AAC1G,wBAAgB,eAAe,CAAC,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,SAAS,CAiChG;AAED,wCAAwC;AACxC,MAAM,WAAW,kBAAkB;IACjC,qDAAqD;IACrD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,yFAAyF;IACzF,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,mFAAmF;IACnF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,OAAO,GAAE,kBAAuB,GAAG,CAAC,CAgCrH"}
@@ -0,0 +1,118 @@
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 } from "@opentelemetry/api";
12
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
13
+ /** The W3C propagator of runInRemoteTrace: it reads the traceparent also when no global propagator is set. */
14
+ const W3C = new W3CTraceContextPropagator();
15
+ const TRACEPARENT = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
16
+ /**
17
+ * The W3C trace context to pass on: the context of the active span when the
18
+ * SDK operates, else the `traceparent` header of the request.
19
+ */
20
+ export function outgoingTraceparent(header) {
21
+ const carrier = {};
22
+ propagation.inject(context.active(), carrier);
23
+ const value = carrier["traceparent"] ?? (typeof header === "string" ? header : undefined);
24
+ return value && TRACEPARENT.test(value) ? value : undefined;
25
+ }
26
+ /** A trace-echo store: each trace lives `ttlMs` (default 10 s), `maxEntries` at most (default 10,000). */
27
+ export function createTraceEcho(options = {}) {
28
+ const ttl = options.ttlMs ?? 10_000;
29
+ const max = options.maxEntries ?? 10_000;
30
+ const pending = new Map();
31
+ const keyOf = (scope, id) => `${scope}\u0000${String(id)}`;
32
+ /** Drop the expired entries, and when the store is full, the oldest half */
33
+ const sweep = (now) => {
34
+ for (const [k, v] of pending)
35
+ if (now - v.at > ttl)
36
+ pending.delete(k);
37
+ if (pending.size >= max) {
38
+ let drop = Math.floor(pending.size / 2);
39
+ for (const k of pending.keys()) {
40
+ if (drop-- <= 0)
41
+ break;
42
+ pending.delete(k);
43
+ }
44
+ }
45
+ };
46
+ return {
47
+ remember(scope, id, traceparent, now = Date.now()) {
48
+ if (!traceparent)
49
+ return;
50
+ if (pending.size >= max)
51
+ sweep(now);
52
+ pending.set(keyOf(scope, id), { traceparent, at: now });
53
+ },
54
+ take(scope, id, now = Date.now()) {
55
+ const key = keyOf(scope, id);
56
+ const hit = pending.get(key);
57
+ if (!hit)
58
+ return undefined;
59
+ pending.delete(key);
60
+ return now - hit.at <= ttl ? hit.traceparent : undefined;
61
+ },
62
+ get size() {
63
+ return pending.size;
64
+ },
65
+ };
66
+ }
67
+ /**
68
+ * The other end of the trace echo: run `fn` inside the trace that a message
69
+ * carries. A message (for example a change on a live connection) can carry the
70
+ * `traceparent` of the write that caused it. This function starts a consumer
71
+ * span whose parent is that trace, and runs `fn` with the span active. Thus one
72
+ * trace shows the action, the write, the server and each client that applies
73
+ * the change. Without a valid `traceparent`, it only runs `fn`.
74
+ *
75
+ * The span ends when `fn` returns, or when the promise of `fn` settles. An
76
+ * error of `fn` sets the status of the span to ERROR, and passes through.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * socket.onChange((msg) => runInRemoteTrace(msg.traceparent, () => store.apply(msg), {
81
+ * name: "realtime.echo",
82
+ * attributes: { "app.collection": msg.collection },
83
+ * }));
84
+ * ```
85
+ */
86
+ export function runInRemoteTrace(traceparent, fn, options = {}) {
87
+ if (!traceparent || !TRACEPARENT.test(traceparent))
88
+ return fn();
89
+ const parent = W3C.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
90
+ const tracer = options.tracer ?? trace.getTracer("@mark1russell7/otel-ts");
91
+ const span = tracer.startSpan(options.name ?? "remote.apply", { kind: SpanKind.CONSUMER, ...(options.attributes ? { attributes: options.attributes } : {}) }, parent);
92
+ const fail = (error) => {
93
+ span.recordException(error instanceof Error ? error : String(error));
94
+ span.setStatus({ code: SpanStatusCode.ERROR });
95
+ };
96
+ let result;
97
+ try {
98
+ result = context.with(trace.setSpan(parent, span), fn);
99
+ }
100
+ catch (error) {
101
+ fail(error);
102
+ span.end();
103
+ throw error;
104
+ }
105
+ if (result && typeof result.then === "function") {
106
+ return result.then((value) => {
107
+ span.end();
108
+ return value;
109
+ }, (error) => {
110
+ fail(error);
111
+ span.end();
112
+ throw error;
113
+ });
114
+ }
115
+ span.end();
116
+ return result;
117
+ }
118
+ //# sourceMappingURL=trace-echo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-echo.js","sourceRoot":"","sources":["../src/trace-echo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,KAAK,EAAgC,MAAM,oBAAoB,CAAC;AAC7J,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAEhE,8GAA8G;AAC9G,MAAM,GAAG,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAE5C,MAAM,WAAW,GAAG,qDAAqD,CAAC;AAE1E;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAe;IACjD,MAAM,OAAO,GAA2B,EA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KAAK,CAAC,CAAC;YACZ,IAAI,CAAC,GAAG,EAAE,CAAC;YACX,MAAM,KAAK,CAAC;QACd,CAAC,CACG,CAAC;IACT,CAAC;IACD,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
3
+ import type { ContextManager } from "@opentelemetry/api";
4
+ import type { ResolvedConfig } from "./types.js";
5
+ import { type SessionIdReader } from "./session-processors.js";
6
+ export declare function setupTracing(resource: Resource, config: ResolvedConfig, getSessionId: SessionIdReader, contextManager: ContextManager): WebTracerProvider;
7
+ //# sourceMappingURL=tracing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing.d.ts","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAMzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AAEjC,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,eAAe,EAC7B,cAAc,EAAE,cAAc,GAC7B,iBAAiB,CA2CnB"}
@@ -0,0 +1,48 @@
1
+ import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
2
+ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
3
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
4
+ import { getWebAutoInstrumentations } from "@opentelemetry/auto-instrumentations-web";
5
+ import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-task";
6
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
7
+ import { hasDom } from "./env.js";
8
+ import { createSessionSpanProcessor, } from "./session-processors.js";
9
+ export function setupTracing(resource, config, getSessionId, contextManager) {
10
+ // Document-load and user-interaction need a DOM; skip them in Web Workers
11
+ const dom = hasDom();
12
+ const exporter = new OTLPTraceExporter({
13
+ url: `${config.endpoint}/v1/traces`,
14
+ });
15
+ const provider = new WebTracerProvider({
16
+ resource,
17
+ spanProcessors: [
18
+ createSessionSpanProcessor(getSessionId),
19
+ new BatchSpanProcessor(exporter),
20
+ ],
21
+ });
22
+ provider.register({ contextManager });
23
+ registerInstrumentations({
24
+ instrumentations: [
25
+ getWebAutoInstrumentations({
26
+ "@opentelemetry/instrumentation-document-load": {
27
+ enabled: config.instrumentDocumentLoad && dom,
28
+ },
29
+ "@opentelemetry/instrumentation-fetch": {
30
+ enabled: config.instrumentFetch,
31
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls,
32
+ },
33
+ "@opentelemetry/instrumentation-xml-http-request": {
34
+ enabled: config.instrumentXhr,
35
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls,
36
+ },
37
+ "@opentelemetry/instrumentation-user-interaction": {
38
+ enabled: config.instrumentUserInteraction && dom,
39
+ },
40
+ }),
41
+ ...(config.instrumentLongTask
42
+ ? [new LongTaskInstrumentation()]
43
+ : []),
44
+ ],
45
+ });
46
+ return provider;
47
+ }
48
+ //# sourceMappingURL=tracing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing.js","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CA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,CAAC;gBACjC,CAAC,CAAC,EAAE,CAAC;SACR;KACF,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,210 @@
1
+ import type { ContextManager } from "@opentelemetry/api";
2
+ import type { StateTransition } from "page-lifecycle-tracker";
3
+ export type MetricsTemporality = "cumulative" | "delta";
4
+ /**
5
+ * The names of the context managers of otel-ts. Each entry has some of them:
6
+ * - "async": the `AsyncContextManager` of async-browser-context. Only in
7
+ * `@mark1russell7/otel-ts`, where it is the default. Its runtime patches
8
+ * `Promise.prototype.then`, the timers, the event listeners and other
9
+ * callback APIs, so their callbacks keep the active span. After a native
10
+ * `await`, the span stays only in code that the Vite plugin or the Babel
11
+ * preset of async-browser-context transforms. On Node.js, it uses the
12
+ * native `AsyncLocalStorage`.
13
+ * - "zone": `ZoneContextManager` (zone.js). Only in
14
+ * `@mark1russell7/otel-ts/zone`, where it is the default. It keeps the
15
+ * active span across timers, events and `then` callbacks, but not after a
16
+ * native `await`.
17
+ * - "stack": `StackContextManager`. In each entry, and the default of
18
+ * `@mark1russell7/otel-ts/core`. It patches nothing, and it keeps the active
19
+ * span only in synchronous code.
20
+ */
21
+ export type ContextManagerName = "async" | "stack" | "zone";
22
+ /**
23
+ * A value of the `contextManager` option: a name, or a `ContextManager`
24
+ * instance of the app. `Name` is the names that the entry has.
25
+ */
26
+ export type ContextManagerOption<Name extends ContextManagerName = ContextManagerName> = Name | ContextManager;
27
+ /** How histogram instruments aggregate their measurements */
28
+ export type HistogramAggregation = "explicit" | "exponential";
29
+ /**
30
+ * The configuration of `init()`. `Name` is the context manager names that the
31
+ * entry has. Each entry exports `OtelTsConfig` with its own names.
32
+ */
33
+ export interface OtelTsConfig<Name extends ContextManagerName = ContextManagerName> {
34
+ /** OTLP HTTP endpoint. Default: "http://localhost:4318" */
35
+ endpoint?: string;
36
+ /** Service name for resource identification. Default: "frontend-app" */
37
+ serviceName?: string;
38
+ /** Service version. Default: "0.0.0" */
39
+ serviceVersion?: string;
40
+ /**
41
+ * Sets the `service.instance.id` resource attribute, which Prometheus and
42
+ * Mimir turn into the `instance` label. Every SDK instance must have its
43
+ * own value, or many browsers write to the same metric series.
44
+ * Default: a new random UUID v4 for every `init()` call (see
45
+ * `createInstanceId()`), shared by the metrics, logs and traces resources.
46
+ * Never persisted, never derived from the session ID.
47
+ */
48
+ serviceInstanceId?: string;
49
+ /** Additional resource attributes */
50
+ resourceAttributes?: Record<string, string>;
51
+ /**
52
+ * Put the browser attributes of the semantic conventions on the resource:
53
+ * `browser.brands`, `browser.platform`, `browser.mobile`,
54
+ * `browser.language` and `user_agent.original`, from `navigator`.
55
+ * Default: true
56
+ */
57
+ browserAttributes?: boolean;
58
+ /** Enable tracing. Default: true */
59
+ tracing?: boolean;
60
+ /**
61
+ * The context manager of the tracer provider. Default: "async" in
62
+ * `@mark1russell7/otel-ts`, "zone" in `@mark1russell7/otel-ts/zone` and
63
+ * "stack" in `@mark1russell7/otel-ts/core`.
64
+ */
65
+ contextManager?: ContextManagerOption<Name>;
66
+ /** Propagate trace context to these origins. Default: all origins */
67
+ propagateTraceHeaderCorsUrls?: Array<string | RegExp>;
68
+ /** Enable metrics. Default: true */
69
+ metrics?: boolean;
70
+ /**
71
+ * Metrics export interval in ms. Default: 15000. Telemetry is also flushed
72
+ * whenever the page is hidden.
73
+ */
74
+ metricsExportIntervalMs?: number;
75
+ /**
76
+ * Aggregation temporality requested from the OTLP metrics exporter.
77
+ * "cumulative" exports running totals; "delta" exports counters and
78
+ * histograms as the change since the previous export (up-down counters stay
79
+ * cumulative). Default: "cumulative"
80
+ */
81
+ metricsTemporality?: MetricsTemporality;
82
+ /**
83
+ * Aggregation for histogram instruments.
84
+ * "explicit": explicit-bucket histograms, with the boundaries from the
85
+ * instrument's advice or the SDK defaults. Every backend stores these.
86
+ * "exponential": base-2 exponential histograms, for every histogram
87
+ * instrument (advice boundaries are ignored). Mimir stores each one as a
88
+ * single native-histogram series; this needs native-histogram ingestion
89
+ * turned on (`native_histograms_ingestion_enabled`), or the data is lost.
90
+ * Default: "explicit"
91
+ */
92
+ histogramAggregation?: HistogramAggregation;
93
+ /** Enable logs. Default: true */
94
+ logs?: boolean;
95
+ /** Enable document-load instrumentation. Default: true. Needs a DOM. */
96
+ instrumentDocumentLoad?: boolean;
97
+ /** Enable fetch instrumentation. Default: true */
98
+ instrumentFetch?: boolean;
99
+ /** Enable XMLHttpRequest instrumentation. Default: true */
100
+ instrumentXhr?: boolean;
101
+ /** Enable user-interaction instrumentation. Default: true. Needs a DOM. */
102
+ instrumentUserInteraction?: boolean;
103
+ /** Enable long-task instrumentation. Default: true */
104
+ instrumentLongTask?: boolean;
105
+ /**
106
+ * Enable Grafana Faro integration. Default: true. Faro starts only when
107
+ * `faroCollectorUrl` is set and there is a DOM.
108
+ */
109
+ faro?: boolean;
110
+ /**
111
+ * Faro collector URL. Faro has nowhere to send data without it, so it does
112
+ * not start. Omit for local OTLP-only mode.
113
+ */
114
+ faroCollectorUrl?: string;
115
+ /** Faro app name. Defaults to serviceName. */
116
+ faroAppName?: string;
117
+ /**
118
+ * Enable session tracking. Default: true. The session ID lives in
119
+ * sessionStorage (in memory where there is none) and rotates after 30
120
+ * minutes without activity. When false, each `init()` call gets a new
121
+ * random session ID that is not stored.
122
+ *
123
+ * The session ID is set as the `session.id` attribute of every log record
124
+ * and span, never on the resource.
125
+ */
126
+ sessionTracking?: boolean;
127
+ /** Enable console debug output. Default: false */
128
+ debug?: boolean;
129
+ }
130
+ export interface ResolvedConfig {
131
+ endpoint: string;
132
+ serviceName: string;
133
+ serviceVersion: string;
134
+ serviceInstanceId: string;
135
+ resourceAttributes: Record<string, string>;
136
+ browserAttributes: boolean;
137
+ tracing: boolean;
138
+ contextManager: ContextManagerOption;
139
+ propagateTraceHeaderCorsUrls: Array<string | RegExp>;
140
+ metrics: boolean;
141
+ metricsExportIntervalMs: number;
142
+ metricsTemporality: MetricsTemporality;
143
+ histogramAggregation: HistogramAggregation;
144
+ logs: boolean;
145
+ instrumentDocumentLoad: boolean;
146
+ instrumentFetch: boolean;
147
+ instrumentXhr: boolean;
148
+ instrumentUserInteraction: boolean;
149
+ instrumentLongTask: boolean;
150
+ faro: boolean;
151
+ faroCollectorUrl: string | undefined;
152
+ faroAppName: string | undefined;
153
+ sessionTracking: boolean;
154
+ debug: boolean;
155
+ }
156
+ /** What started a flush */
157
+ export interface FlushCause {
158
+ /**
159
+ * The lifecycle transition that started the flush: to `hidden`, `frozen`
160
+ * or `terminated` (page-lifecycle-tracker). Undefined for a call of
161
+ * `forceFlush()` or `shutdown()`.
162
+ */
163
+ readonly transition?: StateTransition;
164
+ /**
165
+ * @deprecated otel-ts no longer passes the page event. It flushes in the
166
+ * `export` phase of the shared lifecycle tracker, after the monitors of the
167
+ * page recorded the transition, so a listener does not need the event.
168
+ */
169
+ readonly event?: Event;
170
+ }
171
+ export interface OtelTsInstance {
172
+ /**
173
+ * Flush pending telemetry and shut down all providers. Runs once; later
174
+ * calls return the same promise.
175
+ */
176
+ shutdown(): Promise<void>;
177
+ /**
178
+ * Export pending telemetry now; providers keep running. Also runs
179
+ * automatically whenever the page is hidden.
180
+ */
181
+ forceFlush(): Promise<void>;
182
+ /**
183
+ * Register a function that runs synchronously just before each flush:
184
+ * every page hide, the shutdown when the page is discarded, and every
185
+ * manual `forceFlush()` or `shutdown()`. Values it records go out in that
186
+ * flush, whatever order the page's `pagehide` listeners run in (Chromium
187
+ * runs window listeners in registration order). Listeners run in
188
+ * registration order; one that throws doesn't stop the others or the
189
+ * flush, and only the first error is logged. They don't run after
190
+ * shutdown, and a returned promise isn't awaited.
191
+ *
192
+ * The listener gets the cause of the flush. For a page hide it has the
193
+ * `visibilitychange` or `pagehide` event, so a listener can handle that
194
+ * event before the flush even when its own listener of that event would
195
+ * run too late, as in Chromium.
196
+ *
197
+ * @returns A function that removes the listener
198
+ */
199
+ onBeforeFlush(listener: (cause: FlushCause) => void): () => void;
200
+ /**
201
+ * Get the current session ID: the value the next log record or span gets.
202
+ * Counts as activity, like emitting a log record or starting a span.
203
+ */
204
+ getSessionId(): string;
205
+ /** Get a named Meter for creating instruments (histograms, gauges, counters) */
206
+ getMeter(name: string): import("@opentelemetry/api").Meter;
207
+ /** Get a named Logger for emitting log records */
208
+ getLogger(name: string): import("@opentelemetry/api-logs").Logger;
209
+ }
210
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,MAAM,MAAM,kBAAkB,GAAG,YAAY,GAAG,OAAO,CAAC;AAExD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAE5D;;;GAGG;AACH,MAAM,MAAM,oBAAoB,CAAC,IAAI,SAAS,kBAAkB,GAAG,kBAAkB,IACjF,IAAI,GACJ,cAAc,CAAC;AAEnB,6DAA6D;AAC7D,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,aAAa,CAAC;AAE9D;;;GAGG;AACH,MAAM,WAAW,YAAY,CAAC,IAAI,SAAS,kBAAkB,GAAG,kBAAkB;IAChF,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,wEAAwE;IACxE,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,wCAAwC;IACxC,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B,qCAAqC;IACrC,kBAAkB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE5C;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAI5B,oCAAoC;IACpC,OAAO,CA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S,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,yBAAyB,EAAE,MAAM,CAAC;CACnE"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}