@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/dist/init.js ADDED
@@ -0,0 +1,135 @@
1
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
2
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
3
+ import { buildResource } from "./resource.js";
4
+ import { createSessionTracker } from "./session.js";
5
+ import { createInstanceId, randomUuid } from "./id.js";
6
+ import { setupTracing } from "./tracing.js";
7
+ import { createContextManager, } from "./context-manager.js";
8
+ import { setupMetrics } from "./metrics.js";
9
+ import { setupLogs } from "./logs.js";
10
+ import { setupFaro } from "./faro.js";
11
+ import { registerLifecycleHandlers } from "./lifecycle.js";
12
+ import { createBeforeFlushListeners } from "./before-flush.js";
13
+ import { hasDom } from "./env.js";
14
+ import { DEFAULT_METRICS_EXPORT_INTERVAL_MS, DEFAULT_OTLP_ENDPOINT, DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_VERSION, SESSION_TTL_MS, } from "./constants.js";
15
+ function resolveConfig(config = {}, managers) {
16
+ return {
17
+ endpoint: config.endpoint ?? DEFAULT_OTLP_ENDPOINT,
18
+ serviceName: config.serviceName ?? DEFAULT_SERVICE_NAME,
19
+ serviceVersion: config.serviceVersion ?? DEFAULT_SERVICE_VERSION,
20
+ // A new writer identity for every init(). An empty string would map to
21
+ // an empty `instance` label, which is the same as none, so replace it too.
22
+ serviceInstanceId: config.serviceInstanceId || createInstanceId(),
23
+ resourceAttributes: config.resourceAttributes ?? {},
24
+ browserAttributes: config.browserAttributes ?? true,
25
+ tracing: config.tracing ?? true,
26
+ contextManager: config.contextManager ?? managers.defaultName,
27
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls ?? [/.*/],
28
+ metrics: config.metrics ?? true,
29
+ metricsExportIntervalMs: config.metricsExportIntervalMs ?? DEFAULT_METRICS_EXPORT_INTERVAL_MS,
30
+ metricsTemporality: config.metricsTemporality ?? "cumulative",
31
+ histogramAggregation: config.histogramAggregation ?? "explicit",
32
+ logs: config.logs ?? true,
33
+ instrumentDocumentLoad: config.instrumentDocumentLoad ?? true,
34
+ instrumentFetch: config.instrumentFetch ?? true,
35
+ instrumentXhr: config.instrumentXhr ?? true,
36
+ instrumentUserInteraction: config.instrumentUserInteraction ?? true,
37
+ instrumentLongTask: config.instrumentLongTask ?? true,
38
+ faro: config.faro ?? true,
39
+ faroCollectorUrl: config.faroCollectorUrl,
40
+ faroAppName: config.faroAppName,
41
+ sessionTracking: config.sessionTracking ?? true,
42
+ debug: config.debug ?? false,
43
+ };
44
+ }
45
+ /** Session IDs for this instance: tracked and rotated, or one fixed ID */
46
+ function createSessionIdReader(sessionTracking) {
47
+ if (sessionTracking)
48
+ return createSessionTracker(SESSION_TTL_MS);
49
+ const sessionId = randomUuid();
50
+ return () => sessionId;
51
+ }
52
+ /**
53
+ * The `init()` of each entry. `managers` are the context managers of the
54
+ * entry: the entry imports at most one context library.
55
+ */
56
+ export function initWith(managers, config) {
57
+ const resolved = resolveConfig(config, managers);
58
+ // First, so that a manager that the entry does not have throws before
59
+ // anything starts
60
+ const contextManager = resolved.tracing
61
+ ? createContextManager(resolved.contextManager, managers)
62
+ : undefined;
63
+ // Read again for every log record and span, so they follow rotations
64
+ const getSessionId = createSessionIdReader(resolved.sessionTracking);
65
+ // Start or resume the session now: a page load counts as activity
66
+ const sessionId = getSessionId();
67
+ // One resource, so metrics, logs and traces share the service.instance.id
68
+ const resource = buildResource(resolved);
69
+ const providers = [];
70
+ if (contextManager) {
71
+ providers.push(setupTracing(resource, resolved, getSessionId, contextManager));
72
+ }
73
+ const meterProvider = resolved.metrics
74
+ ? setupMetrics(resource, resolved)
75
+ : new MeterProvider();
76
+ providers.push(meterProvider);
77
+ const loggerProvider = resolved.logs
78
+ ? setupLogs(resource, resolved, getSessionId)
79
+ : new LoggerProvider();
80
+ providers.push(loggerProvider);
81
+ // Faro instruments the page (errors, web vitals, views) and needs a DOM.
82
+ // Without a collector URL it has nowhere to send data and logs an error.
83
+ const faroUrl = resolved.faro && hasDom() ? resolved.faroCollectorUrl : undefined;
84
+ if (faroUrl) {
85
+ setupFaro(resolved, faroUrl);
86
+ }
87
+ // Run synchronously before every flush (page hide, shutdown, manual), so
88
+ // values they record are in it whatever order pagehide listeners run in
89
+ const beforeFlush = createBeforeFlushListeners();
90
+ let shutdownPromise;
91
+ const forceFlush = async (cause = {}) => {
92
+ // Shut-down providers can't flush; wait for their final flush instead
93
+ if (shutdownPromise)
94
+ return shutdownPromise;
95
+ beforeFlush.run(cause);
96
+ await Promise.allSettled(providers.map((p) => p.forceFlush()));
97
+ };
98
+ const shutdown = (cause = {}) => {
99
+ if (!shutdownPromise) {
100
+ beforeFlush.run(cause);
101
+ // ??= in case a listener called shutdown() itself
102
+ shutdownPromise ??= (async () => {
103
+ removeLifecycleHandlers();
104
+ await Promise.allSettled(providers.map((p) => p.shutdown()));
105
+ })();
106
+ }
107
+ return shutdownPromise;
108
+ };
109
+ const removeLifecycleHandlers = registerLifecycleHandlers({
110
+ flush: forceFlush,
111
+ shutdown,
112
+ });
113
+ if (resolved.debug) {
114
+ console.log("[otel-ts] Initialized", {
115
+ endpoint: resolved.endpoint,
116
+ serviceName: resolved.serviceName,
117
+ serviceInstanceId: resolved.serviceInstanceId,
118
+ sessionId,
119
+ tracing: resolved.tracing,
120
+ metrics: resolved.metrics,
121
+ logs: resolved.logs,
122
+ faro: Boolean(faroUrl),
123
+ });
124
+ }
125
+ return {
126
+ // A call of the app has no page event
127
+ shutdown: () => shutdown(),
128
+ forceFlush: () => forceFlush(),
129
+ onBeforeFlush: (listener) => beforeFlush.add(listener),
130
+ getSessionId,
131
+ getMeter: (name) => meterProvider.getMeter(name),
132
+ getLogger: (name) => loggerProvider.getLogger(name),
133
+ };
134
+ }
135
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,oBAAoB,GAErB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,kCAAkC,EAClC,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,GACf,MAAM,gBAAgB,CAAC;AAExB,SAAS,aAAa,CACpB,SAAuB,EAAE,EACzB,QAA8B;IAE9B,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,qBAAqB;QAClD,WAAW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CAAC;QACxD,KAAK,EAAE,UAAU;QACjB,QAAQ;KACT,CAAC,CAAC;IAEH,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO,CAAC,GAAG,CAAC,uBAAuB,EAAE;YACnC,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;YAC7C,SAAS;YACT,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC;SACvB,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,sCAAsC;QACtC,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE;QAC1B,UAAU,EAAE,GAAG,EAAE,CAAC,UAAU,EAAE;QAC9B,aAAa,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC;QACtD,YAAY;QACZ,QAAQ,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC;QACxD,SAAS,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,cAAc,CAAC,SAAS,CAAC,IAAI,CAAC;KAC5D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { FlushCause } from "./types.js";
2
+ export interface LifecycleHandlers {
3
+ /** Export pending telemetry; providers keep running */
4
+ flush(cause: FlushCause): Promise<void>;
5
+ /** Final flush, then stop all providers */
6
+ shutdown(cause: FlushCause): Promise<void>;
7
+ }
8
+ /**
9
+ * Exports telemetry before the page can be frozen or discarded. The handlers
10
+ * subscribe to the lifecycle tracker that the page shares
11
+ * (`getPageLifecycle()` of page-lifecycle-tracker), in its `export` phase:
12
+ *
13
+ * - to `hidden`: flush. Happens on every tab switch, and the user may come
14
+ * back, so providers keep running.
15
+ * - to `frozen` (a freeze, or `pagehide` into the back/forward cache): flush,
16
+ * because the page may be restored.
17
+ * - to `terminated` (`pagehide` without `persisted`): shut down.
18
+ *
19
+ * A subscriber in the `export` phase runs after every subscriber in the
20
+ * `observe` phase of the same transition, so values that monitoring libraries
21
+ * record at the end of the page (on the same shared tracker) go out in that
22
+ * flush, whatever order the scripts registered in. Before, otel-ts listened
23
+ * to `pagehide` itself, and Chromium runs window listeners in registration
24
+ * order: it shut down before monitors that registered later recorded.
25
+ *
26
+ * The tracker does not use `beforeunload` or `unload`: they can make the page
27
+ * ineligible for the back/forward cache. Registers nothing where there is no
28
+ * DOM (e.g. in a Web Worker).
29
+ *
30
+ * @returns A function that removes the subscription
31
+ */
32
+ export declare function registerLifecycleHandlers(handlers: LifecycleHandlers): () => void;
33
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,WAAW,iBAAiB;IAChC,uDAAuD;IACvD,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAExC,2CAA2C;IAC3C,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,iBAAiB,GAC1B,MAAM,IAAI,CAaZ"}
@@ -0,0 +1,39 @@
1
+ import { getPageLifecycle } from "page-lifecycle-tracker";
2
+ import { hasDom } from "./env.js";
3
+ /**
4
+ * Exports telemetry before the page can be frozen or discarded. The handlers
5
+ * subscribe to the lifecycle tracker that the page shares
6
+ * (`getPageLifecycle()` of page-lifecycle-tracker), in its `export` phase:
7
+ *
8
+ * - to `hidden`: flush. Happens on every tab switch, and the user may come
9
+ * back, so providers keep running.
10
+ * - to `frozen` (a freeze, or `pagehide` into the back/forward cache): flush,
11
+ * because the page may be restored.
12
+ * - to `terminated` (`pagehide` without `persisted`): shut down.
13
+ *
14
+ * A subscriber in the `export` phase runs after every subscriber in the
15
+ * `observe` phase of the same transition, so values that monitoring libraries
16
+ * record at the end of the page (on the same shared tracker) go out in that
17
+ * flush, whatever order the scripts registered in. Before, otel-ts listened
18
+ * to `pagehide` itself, and Chromium runs window listeners in registration
19
+ * order: it shut down before monitors that registered later recorded.
20
+ *
21
+ * The tracker does not use `beforeunload` or `unload`: they can make the page
22
+ * ineligible for the back/forward cache. Registers nothing where there is no
23
+ * DOM (e.g. in a Web Worker).
24
+ *
25
+ * @returns A function that removes the subscription
26
+ */
27
+ export function registerLifecycleHandlers(handlers) {
28
+ if (!hasDom())
29
+ return () => { };
30
+ return getPageLifecycle().subscribe((transition) => {
31
+ if (transition.to === "hidden" || transition.to === "frozen") {
32
+ void handlers.flush({ transition });
33
+ }
34
+ else if (transition.to === "terminated") {
35
+ void handlers.shutdown({ transition });
36
+ }
37
+ }, { phase: "export" });
38
+ }
39
+ //# sourceMappingURL=lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.js","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAWlC;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAA2B;IAE3B,IAAI,CAAC,MAAM,EAAE;QAAE,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;IAE/B,OAAO,gBAAgB,EAAE,CAAC,SAAS,CACjC,CAAC,UAAU,EAAE,EAAE;QACb,IAAI,UAAU,CAAC,EAAE,KAAK,QAAQ,IAAI,UAAU,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;YAC7D,KAAK,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;QACtC,CAAC;aAAM,IAAI,UAAU,CAAC,EAAE,KAAK,YAAY,EAAE,CAAC;YAC1C,KAAK,QAAQ,CAAC,QAAQ,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;QACzC,CAAC;IACH,CAAC,EACD,EAAE,KAAK,EAAE,QAAQ,EAAE,CACpB,CAAC;AACJ,CAAC"}
package/dist/logs.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
3
+ import type { ResolvedConfig } from "./types.js";
4
+ import { type SessionIdReader } from "./session-processors.js";
5
+ export declare function setupLogs(resource: Resource, config: ResolvedConfig, getSessionId: SessionIdReader): LoggerProvider;
6
+ //# sourceMappingURL=logs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../src/logs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EACL,cAAc,EAEf,MAAM,yBAAyB,CAAC;AAEjC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AAEjC,wBAAgB,SAAS,CACvB,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,eAAe,GAC5B,cAAc,CAahB"}
package/dist/logs.js ADDED
@@ -0,0 +1,17 @@
1
+ import { LoggerProvider, BatchLogRecordProcessor, } from "@opentelemetry/sdk-logs";
2
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
3
+ import { createSessionLogRecordProcessor, } from "./session-processors.js";
4
+ export function setupLogs(resource, config, getSessionId) {
5
+ const exporter = new OTLPLogExporter({
6
+ url: `${config.endpoint}/v1/logs`,
7
+ });
8
+ return new LoggerProvider({
9
+ resource,
10
+ processors: [
11
+ // Before the exporting processor, so every exported record has it
12
+ createSessionLogRecordProcessor(getSessionId),
13
+ new BatchLogRecordProcessor(exporter),
14
+ ],
15
+ });
16
+ }
17
+ //# sourceMappingURL=logs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logs.js","sourceRoot":"","sources":["../src/logs.ts"],"names":[],"mappings":"AACA,OAAO,EACL,cAAc,EACd,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE,OAAO,EACL,+BAA+B,GAEhC,MAAM,yBAAyB,CAAC;AAEjC,MAAM,UAAU,SAAS,CACvB,QAAkB,EAClB,MAAsB,EACtB,YAA6B;IAE7B,MAAM,QAAQ,GAAG,IAAI,eAAe,CAAC;QACnC,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,UAAU;KAClC,CAAC,CAAC;IAEH,OAAO,IAAI,cAAc,CAAC;QACxB,QAAQ;QACR,UAAU,EAAE;YACV,kEAAkE;YAClE,+BAA+B,CAAC,YAAY,CAAC;YAC7C,IAAI,uBAAuB,CAAC,QAAQ,CAAC;SACtC;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
3
+ import type { ResolvedConfig } from "./types.js";
4
+ export declare function setupMetrics(resource: Resource, config: ResolvedConfig): MeterProvider;
5
+ //# sourceMappingURL=metrics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAGL,aAAa,EAGd,MAAM,4BAA4B,CAAC;AAMpC,OAAO,KAAK,EAAsB,cAAc,EAAE,MAAM,YAAY,CAAC;AAyBrE,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,GACrB,aAAa,CAqBf"}
@@ -0,0 +1,37 @@
1
+ import { AggregationType, InstrumentType, MeterProvider, PeriodicExportingMetricReader, } from "@opentelemetry/sdk-metrics";
2
+ import { AggregationTemporalityPreference, OTLPMetricExporter, } from "@opentelemetry/exporter-metrics-otlp-http";
3
+ const TEMPORALITY_PREFERENCES = {
4
+ cumulative: AggregationTemporalityPreference.CUMULATIVE,
5
+ delta: AggregationTemporalityPreference.DELTA,
6
+ };
7
+ /**
8
+ * Base-2 exponential histograms for histogram instruments; every other
9
+ * instrument keeps its default aggregation. Used as the exporter's
10
+ * aggregation preference — the SDK's equivalent of
11
+ * OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_exponential_bucket_histogram —
12
+ * rather than a View, so it stays the default that any View can override,
13
+ * and there are no overlapping Views producing duplicate streams.
14
+ */
15
+ const selectExponentialHistograms = (instrumentType) => instrumentType === InstrumentType.HISTOGRAM
16
+ ? { type: AggregationType.EXPONENTIAL_HISTOGRAM }
17
+ : { type: AggregationType.DEFAULT };
18
+ export function setupMetrics(resource, config) {
19
+ const options = {
20
+ url: `${config.endpoint}/v1/metrics`,
21
+ temporalityPreference: TEMPORALITY_PREFERENCES[config.metricsTemporality],
22
+ };
23
+ if (config.histogramAggregation === "exponential") {
24
+ options.aggregationPreference = selectExponentialHistograms;
25
+ }
26
+ const exporter = new OTLPMetricExporter(options);
27
+ return new MeterProvider({
28
+ resource,
29
+ readers: [
30
+ new PeriodicExportingMetricReader({
31
+ exporter,
32
+ exportIntervalMillis: config.metricsExportIntervalMs,
33
+ }),
34
+ ],
35
+ });
36
+ }
37
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AACA,OAAO,EACL,eAAe,EACf,cAAc,EACd,aAAa,EACb,6BAA6B,GAE9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gCAAgC,EAChC,kBAAkB,GAEnB,MAAM,2CAA2C,CAAC;AAGnD,MAAM,uBAAuB,GAGzB;IACF,UAAU,EAAE,gCAAgC,CAAC,UAAU;IACvD,KAAK,EAAE,gCAAgC,CAAC,KAAK;CAC9C,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,2BAA2B,GAAwB,CACvD,cAAc,EACd,EAAE,CACF,cAAc,KAAK,cAAc,CAAC,SAAS;IACzC,CAAC,CAAC,EAAE,IAAI,EAAE,eAAe,CAAC,qBAAqB,EAAE;IACjD,CAAC,CAAC,EAAE,IAAI,EAAE,eAAe,CAAC,OAAO,EAAE,CAAC;AAExC,MAAM,UAAU,YAAY,CAC1B,QAAkB,EAClB,MAAsB;IAEtB,MAAM,OAAO,GAA8B;QACzC,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,aAAa;QACpC,qBAAqB,EAAE,uBAAuB,CAAC,MAAM,CAAC,kBAAkB,CAAC;KAC1E,CAAC;IAEF,IAAI,MAAM,CAAC,oBAAoB,KAAK,aAAa,EAAE,CAAC;QAClD,OAAO,CAAC,qBAAqB,GAAG,2BAA2B,CAAC;IAC9D,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAEjD,OAAO,IAAI,aAAa,CAAC;QACvB,QAAQ;QACR,OAAO,EAAE;YACP,IAAI,6BAA6B,CAAC;gBAChC,QAAQ;gBACR,oBAAoB,EAAE,MAAM,CAAC,uBAAuB;aACrD,CAAC;SACH;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,23 @@
1
+ /** A stand-in OTLP/HTTP collector */
2
+ export interface StubCollector {
3
+ /** The endpoint for `OTEL_EXPORTER_OTLP_ENDPOINT`, for example http://127.0.0.1:43211 */
4
+ readonly endpoint: string;
5
+ /** The count of the trace exports that arrived */
6
+ readonly exports: number;
7
+ /** The span names of each instrumentation scope, for example "@opentelemetry/instrumentation-http" */
8
+ spansByScope(): Map<string, Set<string>>;
9
+ /** True when each of these scopes has one span or more */
10
+ has(scopes: readonly string[]): boolean;
11
+ /** The scopes of a list that have no span */
12
+ missing(scopes: readonly string[]): string[];
13
+ /** Wait until each scope has spans, `timeoutMs` at most (default 20 s). It gives the scopes that are still missing. */
14
+ waitFor(scopes: readonly string[], options?: {
15
+ timeoutMs?: number;
16
+ intervalMs?: number;
17
+ poke?: () => Promise<unknown>;
18
+ }): Promise<string[]>;
19
+ close(): Promise<void>;
20
+ }
21
+ /** Start a stand-in OTLP/HTTP collector on a free port of 127.0.0.1 */
22
+ export declare function startStubCollector(): Promise<StubCollector>;
23
+ //# sourceMappingURL=node-testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-testing.d.ts","sourceRoot":"","sources":["../src/node-testing.ts"],"names":[],"mappings":"AAgBA,qCAAqC;AACrC,MAAM,WAAW,aAAa;IAC5B,yFAAyF;IACzF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,kDAAkD;IAClD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,sGAAsG;IACtG,YAAY,IAAI,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IACzC,0DAA0D;IAC1D,GAAG,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC;IACxC,6CAA6C;IAC7C,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAC7C,uHAAuH;IACvH,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5I,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,uEAAuE;AACvE,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,aAAa,CAAC,CAqDjE"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `@mark1russell7/otel-ts/node/testing`: a stand-in OTLP collector for the CI
3
+ * check of a Node service. A change of the load order (for example a move to
4
+ * ES modules) breaks the instrumentations without an error: the service
5
+ * operates, and some spans are not there. A check starts the service with
6
+ * `OTEL_EXPORTER_OTLP_ENDPOINT` set to `collector.endpoint`, sends requests,
7
+ * and waits until each instrumentation that it expects has spans.
8
+ *
9
+ * The collector reads OTLP/HTTP JSON, the default of
10
+ * `@opentelemetry/exporter-trace-otlp-http`.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ import { createServer } from "node:http";
15
+ /** Start a stand-in OTLP/HTTP collector on a free port of 127.0.0.1 */
16
+ export async function startStubCollector() {
17
+ const seen = new Map();
18
+ let exports = 0;
19
+ const server = createServer((req, res) => {
20
+ let body = "";
21
+ req.on("data", (chunk) => {
22
+ body += chunk;
23
+ });
24
+ req.on("end", () => {
25
+ if (req.url === "/v1/traces") {
26
+ exports++;
27
+ try {
28
+ const parsed = JSON.parse(body);
29
+ for (const rs of parsed.resourceSpans ?? []) {
30
+ for (const ss of rs.scopeSpans ?? []) {
31
+ const scope = ss.scope?.name ?? "?";
32
+ const names = seen.get(scope) ?? new Set();
33
+ for (const span of ss.spans ?? [])
34
+ names.add(span.name ?? "?");
35
+ seen.set(scope, names);
36
+ }
37
+ }
38
+ }
39
+ catch {
40
+ // an export that is not JSON (protobuf): the check expects JSON
41
+ }
42
+ }
43
+ res.writeHead(200, { "Content-Type": "application/json" });
44
+ res.end("{}");
45
+ });
46
+ });
47
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
48
+ const { port } = server.address();
49
+ const missing = (scopes) => scopes.filter((s) => !(seen.get(s)?.size));
50
+ return {
51
+ endpoint: `http://127.0.0.1:${port}`,
52
+ get exports() {
53
+ return exports;
54
+ },
55
+ spansByScope: () => seen,
56
+ has: (scopes) => missing(scopes).length === 0,
57
+ missing,
58
+ async waitFor(scopes, options = {}) {
59
+ const until = Date.now() + (options.timeoutMs ?? 20_000);
60
+ while (Date.now() < until) {
61
+ await options.poke?.().catch(() => undefined);
62
+ if (missing(scopes).length === 0)
63
+ return [];
64
+ await new Promise((r) => setTimeout(r, options.intervalMs ?? 500));
65
+ }
66
+ return missing(scopes);
67
+ },
68
+ close: () => new Promise((resolve) => server.close(() => resolve())),
69
+ };
70
+ }
71
+ //# sourceMappingURL=node-testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-testing.js","sourceRoot":"","sources":["../src/node-testing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAC;AAoBtD,uEAAuE;AACvE,MAAM,CAAC,KAAK,UAAU,kBAAkB;IACtC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC5C,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,MAAM,MAAM,GAAW,YAAY,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QAC/C,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YACvB,IAAI,IAAI,KAAK,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACjB,IAAI,GAAG,CAAC,GAAG,KAAK,YAAY,EAAE,CAAC;gBAC7B,OAAO,EAAE,CAAC;gBACV,IAAI,CAAC;oBACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAE7B,CAAC;oBACF,KAAK,MAAM,EAAE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AO,CAAC;QACjB,CAAC;QACD,YAAY,EAAE,GAAG,EAAE,CAAC,IAAI;QACxB,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;QAC7C,OAAO;QACP,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,GAAG,EAAE;YAChC,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,SAAS,IAAI,MAAM,CAAC,CAAC;YACzD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;gBAC1B,MAAM,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;gBAC9C,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;oBAAE,OAAO,EAAE,CAAC;gBAC5C,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,OAAO,CAAC,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC;YACrE,CAAC;YACD,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;QACzB,CAAC;QACD,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;KAC3E,CAAC;AACJ,CAAC"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
2
+ export { outgoingTraceparent, createTraceEcho, runInRemoteTrace, type RemoteTraceOptions, type TraceEcho } from "./trace-echo.js";
3
+ /** The configuration of `startNodeTelemetry()` */
4
+ export interface NodeTelemetryOptions {
5
+ /** The service name. Default: `OTEL_SERVICE_NAME`, else "node-service". */
6
+ serviceName?: string;
7
+ /**
8
+ * The `import.meta.url` of the module that calls this function. The loader
9
+ * hook resolves from it, so it is the instance of the service's
10
+ * instrumentations. Without it, no loader hook is registered.
11
+ */
12
+ importMetaUrl?: string;
13
+ /** The instrumentations, from the dependencies of the service */
14
+ instrumentations?: NodeSDKConfiguration["instrumentations"];
15
+ /** The trace exporter. Default: the exporter that the SDK makes from the `OTEL_*` variables. */
16
+ traceExporter?: NodeSDKConfiguration["traceExporter"];
17
+ /** The metric readers. Default: none. */
18
+ metricReaders?: NodeSDKConfiguration["metricReaders"];
19
+ /** On or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a value. */
20
+ enabled?: boolean;
21
+ /** Stop the SDK (and flush) at SIGTERM and SIGINT. Default: true. */
22
+ stopOnSignals?: boolean;
23
+ /** The environment. Default: `process.env`. */
24
+ env?: NodeJS.ProcessEnv;
25
+ }
26
+ /** The result of `startNodeTelemetry()` */
27
+ export interface NodeTelemetry {
28
+ /** True when the SDK started */
29
+ readonly enabled: boolean;
30
+ /** True when the loader hook was registered */
31
+ readonly esmHook: boolean;
32
+ /** Stop the SDK and flush the spans and metrics. It does nothing when the SDK did not start. */
33
+ shutdown(): Promise<void>;
34
+ }
35
+ /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
36
+ export declare function startNodeTelemetry(options?: NodeTelemetryOptions): NodeTelemetry;
37
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAW,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE7E,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElI,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACnC,2EAA2E;IAC3E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iEAAiE;IACjE,gBAAgB,CAAC,EAAE,oBAAoB,CAAC,kBAAkB,CAAC,CAAC;IAC5D,gGAAgG;IAChG,aAAa,CAAC,EAAE,oBAAoB,CAAC,eAAe,CAAC,CAAC;IACtD,yCAAyC;IACzC,aAAa,CAAC,EAAE,oBAAoB,CAAC,eAAe,CAAC,CAAC;IACtD,6EAA6E;IAC7E,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,qEAAqE;IACrE,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,+CAA+C;IAC/C,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB;AAED,2CAA2C;AAC3C,MAAM,WAAW,aAAa;IAC5B,gCAAgC;IAChC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,+CAA+C;IAC/C,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,gGAAgG;IAChG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED,mFAAmF;AACnF,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,oBAAyB,GAAG,aAAa,CA+BpF"}
package/dist/node.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The Node.js entry, `@mark1russell7/otel-ts/node`: OpenTelemetry for a Node
3
+ * service, with the order that an ES module service needs.
4
+ *
5
+ * Load the module that calls `startNodeTelemetry()` with `node --import`,
6
+ * before the service: the instrumentations patch `http`, `express` and the
7
+ * database drivers when those modules load. In an ES module service, the
8
+ * require hook does not see a package that an ES module imports. The loader
9
+ * hook of OpenTelemetry (`@opentelemetry/instrumentation/hook.mjs`) patches
10
+ * those imports. `startNodeTelemetry()` registers it before the SDK starts.
11
+ *
12
+ * The SDK, the exporters and the instrumentations come from the dependencies
13
+ * of the service (the OpenTelemetry packages must have one version line), so
14
+ * `@opentelemetry/sdk-node` is a peer dependency of this entry.
15
+ *
16
+ * @packageDocumentation
17
+ */
18
+ import { register } from "node:module";
19
+ import { NodeSDK } from "@opentelemetry/sdk-node";
20
+ export { outgoingTraceparent, createTraceEcho, runInRemoteTrace } from "./trace-echo.js";
21
+ /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
22
+ export function startNodeTelemetry(options = {}) {
23
+ const env = options.env ?? process.env;
24
+ const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
25
+ if (!enabled)
26
+ return { enabled: false, esmHook: false, shutdown: async () => { } };
27
+ let esmHook = false;
28
+ if (options.importMetaUrl) {
29
+ register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
30
+ esmHook = true;
31
+ }
32
+ const sdk = new NodeSDK({
33
+ serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
34
+ ...(options.traceExporter ? { traceExporter: options.traceExporter } : {}),
35
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
36
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
37
+ });
38
+ sdk.start();
39
+ let stopped = false;
40
+ const shutdown = async () => {
41
+ if (stopped)
42
+ return;
43
+ stopped = true;
44
+ await sdk.shutdown().catch(() => {
45
+ // a flush that fails at the stop loses its spans, and nothing else
46
+ });
47
+ };
48
+ if (options.stopOnSignals ?? true) {
49
+ process.once("SIGTERM", () => void shutdown());
50
+ process.once("SIGINT", () => void shutdown());
51
+ }
52
+ return { enabled: true, esmHook, shutdown };
53
+ }
54
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAA6B,MAAM,yBAAyB,CAAC;AAE7E,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,gBAAgB,EAA2C,MAAM,iBAAiB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AE,OAAO;QACpB,OAAO,GAAG,IAAI,CAAC;QACf,MAAM,GAAG,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE;YAC9B,mEAAmE;QACrE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,IAAI,OAAO,CAAC,aAAa,IAAI,IAAI,EAAE,CAAC;QAClC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK,QAAQ,EAAE,CAAC,CAAC;QAC/C,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,QAAQ,EAAE,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,38 @@
1
+ import type { AttributeValue } from "@opentelemetry/api";
2
+ import type { ResolvedConfig } from "./types.js";
3
+ /** The parts of `navigator` that the browser attributes use, in a page or a worker */
4
+ interface NavigatorLike {
5
+ userAgent?: string;
6
+ language?: string;
7
+ userAgentData?: {
8
+ brands?: ReadonlyArray<{
9
+ brand: string;
10
+ version: string;
11
+ }>;
12
+ mobile?: boolean;
13
+ platform?: string;
14
+ };
15
+ }
16
+ /**
17
+ * The browser attributes of the OpenTelemetry semantic conventions, from
18
+ * `navigator`: `browser.brands`, `browser.platform` and `browser.mobile`
19
+ * (User-Agent Client Hints, only Chromium has them), `browser.language` and
20
+ * `user_agent.original`. A page and a worker both have `navigator`; where
21
+ * there is none (Node.js), there are no attributes. The `browser.*` names are
22
+ * in the incubating conventions, thus they are written here and not imported.
23
+ */
24
+ export declare function browserAttributes(nav: NavigatorLike | undefined): Record<string, AttributeValue>;
25
+ /**
26
+ * The resource shared by the metrics, logs and traces providers. It holds no
27
+ * `session.id`: that is set on each log record and span instead (see
28
+ * session-processors.ts), because the resource can't follow a session
29
+ * rotation and on metrics it would inflate `target_info`.
30
+ *
31
+ * With `browserAttributes` (the default), it has the browser attributes of
32
+ * the semantic conventions (see `browserAttributes()`), from the global `navigator`. They do not change
33
+ * during the life of a page, thus they fit the resource. The attributes of
34
+ * the config have priority over them.
35
+ */
36
+ export declare function buildResource(config: ResolvedConfig): import("@opentelemetry/resources").Resource;
37
+ export {};
38
+ //# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAOzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,sFAAsF;AACtF,UAAU,aAAa;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE;QACd,MAAM,CAAC,EAAE,aAAa,CAAC;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC3D,MAAM,CAAC,EAAE,OAAO,CAAC;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;CACH;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,aAAa,GAAG,SAAS,GAC7B,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAkBhC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,cAAc,+CAUnD"}
@@ -0,0 +1,54 @@
1
+ import { resourceFromAttributes } from "@opentelemetry/resources";
2
+ import { ATTR_SERVICE_INSTANCE_ID, ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, ATTR_USER_AGENT_ORIGINAL, } from "@opentelemetry/semantic-conventions";
3
+ /**
4
+ * The browser attributes of the OpenTelemetry semantic conventions, from
5
+ * `navigator`: `browser.brands`, `browser.platform` and `browser.mobile`
6
+ * (User-Agent Client Hints, only Chromium has them), `browser.language` and
7
+ * `user_agent.original`. A page and a worker both have `navigator`; where
8
+ * there is none (Node.js), there are no attributes. The `browser.*` names are
9
+ * in the incubating conventions, thus they are written here and not imported.
10
+ */
11
+ export function browserAttributes(nav) {
12
+ if (!nav)
13
+ return {};
14
+ const attributes = {};
15
+ const hints = nav.userAgentData;
16
+ if (hints?.brands && hints.brands.length > 0) {
17
+ attributes["browser.brands"] = hints.brands.map(({ brand, version }) => `${brand} ${version}`);
18
+ }
19
+ if (typeof hints?.platform === "string" && hints.platform !== "") {
20
+ attributes["browser.platform"] = hints.platform;
21
+ }
22
+ if (typeof hints?.mobile === "boolean")
23
+ attributes["browser.mobile"] = hints.mobile;
24
+ if (typeof nav.language === "string" && nav.language !== "") {
25
+ attributes["browser.language"] = nav.language;
26
+ }
27
+ if (typeof nav.userAgent === "string" && nav.userAgent !== "") {
28
+ attributes[ATTR_USER_AGENT_ORIGINAL] = nav.userAgent;
29
+ }
30
+ return attributes;
31
+ }
32
+ /**
33
+ * The resource shared by the metrics, logs and traces providers. It holds no
34
+ * `session.id`: that is set on each log record and span instead (see
35
+ * session-processors.ts), because the resource can't follow a session
36
+ * rotation and on metrics it would inflate `target_info`.
37
+ *
38
+ * With `browserAttributes` (the default), it has the browser attributes of
39
+ * the semantic conventions (see `browserAttributes()`), from the global `navigator`. They do not change
40
+ * during the life of a page, thus they fit the resource. The attributes of
41
+ * the config have priority over them.
42
+ */
43
+ export function buildResource(config) {
44
+ return resourceFromAttributes({
45
+ ...(config.browserAttributes
46
+ ? browserAttributes(globalThis.navigator)
47
+ : {}),
48
+ [ATTR_SERVICE_NAME]: config.serviceName,
49
+ [ATTR_SERVICE_VERSION]: config.serviceVersion,
50
+ [ATTR_SERVICE_INSTANCE_ID]: config.serviceInstanceId,
51
+ ...config.resourceAttributes,
52
+ });
53
+ }
54
+ //# sourceMappingURL=resource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.js","sourceRoot":"","sources":["../src/resource.ts"],"names":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