@utk09/ui-observability 0.9.1 → 0.9.3

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 (172) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +75 -64
  3. package/dist/batch-D5qvsMQ_.cjs +2 -0
  4. package/dist/batch-D5qvsMQ_.cjs.map +1 -0
  5. package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
  6. package/dist/batch-DDgxg16_.js.map +1 -0
  7. package/dist/bus/bus.d.ts +0 -4
  8. package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
  9. package/dist/bus-C6RwKzPW.js.map +1 -0
  10. package/dist/bus-WPVDFw2y.cjs +2 -0
  11. package/dist/bus-WPVDFw2y.cjs.map +1 -0
  12. package/dist/capture/network.d.ts +2 -0
  13. package/dist/capture/storm.d.ts +2 -7
  14. package/dist/capture/types.d.ts +3 -0
  15. package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
  16. package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
  17. package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
  18. package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
  19. package/dist/constants-Cb92egPS.cjs +2 -0
  20. package/dist/constants-Cb92egPS.cjs.map +1 -0
  21. package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
  22. package/dist/constants-DhH6VI5a.js.map +1 -0
  23. package/dist/constants.d.ts +28 -3
  24. package/dist/core/breadcrumbs.d.ts +1 -3
  25. package/dist/core/context.d.ts +0 -8
  26. package/dist/core/diagnostics.d.ts +1 -3
  27. package/dist/core/meter.d.ts +45 -0
  28. package/dist/core/pipeline.d.ts +5 -12
  29. package/dist/core/record.d.ts +7 -0
  30. package/dist/core/runtime.d.ts +17 -0
  31. package/dist/core/sampling.d.ts +3 -3
  32. package/dist/core/sender.d.ts +2 -0
  33. package/dist/deadline-CUrH0Hd8.cjs +2 -0
  34. package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
  35. package/dist/deadline-DeqXEliN.js +31 -0
  36. package/dist/deadline-DeqXEliN.js.map +1 -0
  37. package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
  38. package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
  39. package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
  40. package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
  41. package/dist/fixed-window-BR0bu32Y.cjs +2 -0
  42. package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
  43. package/dist/fixed-window-Re7jIRJH.js +9 -0
  44. package/dist/fixed-window-Re7jIRJH.js.map +1 -0
  45. package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
  46. package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
  47. package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
  48. package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
  49. package/dist/index.cjs +1 -1
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +522 -369
  53. package/dist/index.js.map +1 -1
  54. package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
  55. package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
  56. package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
  57. package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
  58. package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
  59. package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
  60. package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
  61. package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
  62. package/dist/journey-BRUj0hqD.cjs +2 -0
  63. package/dist/journey-BRUj0hqD.cjs.map +1 -0
  64. package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
  65. package/dist/journey-yALMEWF7.js.map +1 -0
  66. package/dist/library-request-BcAxuwsf.cjs +2 -0
  67. package/dist/library-request-BcAxuwsf.cjs.map +1 -0
  68. package/dist/library-request-CQD4HUiP.js +25 -0
  69. package/dist/library-request-CQD4HUiP.js.map +1 -0
  70. package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
  71. package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
  72. package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
  73. package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
  74. package/dist/models/batch.d.ts +6 -0
  75. package/dist/models/config.d.ts +23 -0
  76. package/dist/models/metric.d.ts +50 -0
  77. package/dist/network--GoE7_Or.js +211 -0
  78. package/dist/network--GoE7_Or.js.map +1 -0
  79. package/dist/network-DcuS2H1P.cjs +2 -0
  80. package/dist/network-DcuS2H1P.cjs.map +1 -0
  81. package/dist/openfin-BwEN0uj4.js +8 -0
  82. package/dist/openfin-BwEN0uj4.js.map +1 -0
  83. package/dist/openfin-DtH2f7zX.cjs +2 -0
  84. package/dist/openfin-DtH2f7zX.cjs.map +1 -0
  85. package/dist/platform-GaM6h7XM.js +52 -0
  86. package/dist/platform-GaM6h7XM.js.map +1 -0
  87. package/dist/platform-kIL5AZB7.cjs +2 -0
  88. package/dist/platform-kIL5AZB7.cjs.map +1 -0
  89. package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
  90. package/dist/remote-rules-6ePq8CrI.js.map +1 -0
  91. package/dist/remote-rules-CI3gbRCL.cjs +2 -0
  92. package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
  93. package/dist/sampling-C-M8p3FK.cjs +2 -0
  94. package/dist/sampling-C-M8p3FK.cjs.map +1 -0
  95. package/dist/sampling-Ud_WiuU9.js +65 -0
  96. package/dist/sampling-Ud_WiuU9.js.map +1 -0
  97. package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
  98. package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
  99. package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
  100. package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
  101. package/dist/sender-BESHz6my.cjs +3 -0
  102. package/dist/sender-BESHz6my.cjs.map +1 -0
  103. package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
  104. package/dist/sender-BUBWLn5i.js.map +1 -0
  105. package/dist/storage/gap.d.ts +20 -0
  106. package/dist/storage/indexeddb-storage.d.ts +1 -7
  107. package/dist/storage/keys.d.ts +9 -0
  108. package/dist/storage/local-storage.d.ts +0 -6
  109. package/dist/storage/memory-storage.d.ts +1 -1
  110. package/dist/storm-DhHGHhOc.cjs +2 -0
  111. package/dist/storm-DhHGHhOc.cjs.map +1 -0
  112. package/dist/storm-OD5J6Ylm.js +10 -0
  113. package/dist/storm-OD5J6Ylm.js.map +1 -0
  114. package/dist/transport/custom-transport.d.ts +3 -2
  115. package/dist/transport/exit-flush.d.ts +13 -2
  116. package/dist/transport/http-transport.d.ts +6 -4
  117. package/dist/transport/retry-engine.d.ts +3 -1
  118. package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
  119. package/dist/transport/serializers/otlp.d.ts +30 -0
  120. package/dist/transport/serializers/select.d.ts +20 -4
  121. package/dist/transport/status-transport.d.ts +19 -11
  122. package/dist/utils/fixed-window.d.ts +15 -0
  123. package/dist/utils/guards.d.ts +6 -0
  124. package/dist/utils/library-request.d.ts +12 -0
  125. package/dist/utils/openfin.d.ts +48 -0
  126. package/dist/utils/platform.d.ts +5 -0
  127. package/package.json +2 -3
  128. package/dist/batch-DEK4bv9N.js.map +0 -1
  129. package/dist/batch-DEVFs28i.cjs +0 -2
  130. package/dist/batch-DEVFs28i.cjs.map +0 -1
  131. package/dist/bus-DNFvTkif.cjs +0 -2
  132. package/dist/bus-DNFvTkif.cjs.map +0 -1
  133. package/dist/bus-HVQ8E72V.js.map +0 -1
  134. package/dist/constants-N99w84xy.js.map +0 -1
  135. package/dist/constants-X86IDwkC.cjs +0 -2
  136. package/dist/constants-X86IDwkC.cjs.map +0 -1
  137. package/dist/deadline-5_PecIl5.js +0 -26
  138. package/dist/deadline-5_PecIl5.js.map +0 -1
  139. package/dist/deadline-XSnm95pg.cjs +0 -2
  140. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  141. package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
  142. package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
  143. package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
  144. package/dist/journey-DjvDzHyp.js.map +0 -1
  145. package/dist/journey-DxlfdFJV.cjs +0 -2
  146. package/dist/journey-DxlfdFJV.cjs.map +0 -1
  147. package/dist/library-request-BZ1ekVtl.cjs +0 -2
  148. package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
  149. package/dist/library-request-C8kc5YWv.js +0 -14
  150. package/dist/library-request-C8kc5YWv.js.map +0 -1
  151. package/dist/network-51iicpLl.js +0 -174
  152. package/dist/network-51iicpLl.js.map +0 -1
  153. package/dist/network-jBbjyAJP.cjs +0 -2
  154. package/dist/network-jBbjyAJP.cjs.map +0 -1
  155. package/dist/platform-Cjts-8k8.js +0 -48
  156. package/dist/platform-Cjts-8k8.js.map +0 -1
  157. package/dist/platform-DW3GFIUE.cjs +0 -2
  158. package/dist/platform-DW3GFIUE.cjs.map +0 -1
  159. package/dist/remote-rules-ByS34k4e.cjs +0 -2
  160. package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
  161. package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
  162. package/dist/sampling-BN3Oi6SV.js +0 -63
  163. package/dist/sampling-BN3Oi6SV.js.map +0 -1
  164. package/dist/sampling-b2ck5X98.cjs +0 -2
  165. package/dist/sampling-b2ck5X98.cjs.map +0 -1
  166. package/dist/sender-BBY0IcUo.js.map +0 -1
  167. package/dist/sender-BXoAZKum.cjs +0 -3
  168. package/dist/sender-BXoAZKum.cjs.map +0 -1
  169. package/dist/storm-CKuaBp7i.cjs +0 -2
  170. package/dist/storm-CKuaBp7i.cjs.map +0 -1
  171. package/dist/storm-DhtL2eVr.js +0 -10
  172. package/dist/storm-DhtL2eVr.js.map +0 -1
@@ -10,8 +10,8 @@ export interface ExitFlushDeps {
10
10
  config: ResolvedConfig;
11
11
  /** This field holds the diagnostics reporter. */
12
12
  diagnostics: Diagnostics;
13
- /** This callback drains all buffered and unconfirmed batches into one LogBatch. */
14
- drainForExit: () => LogBatch | null;
13
+ /** This callback drains all buffered and unconfirmed records into one batch for each kind. */
14
+ drainForExit: () => LogBatch[];
15
15
  /**
16
16
  * This callback runs a normal flush with headers, gzip and retry. A hidden document uses it.
17
17
  * It does not touch an in-flight batch.
@@ -24,6 +24,8 @@ export interface ExitFlushDeps {
24
24
  exitHeaders: () => Record<string, string> | undefined;
25
25
  /** This callback receives the records that the exit flush loses. */
26
26
  onLoss?: LossReporter;
27
+ /** This callback sends the points of the open metric interval into the buffers. */
28
+ beforeExit?: () => void;
27
29
  }
28
30
  /**
29
31
  * This class flushes pending telemetry on document unload. It uses sendBeacon, a keepalive
@@ -33,6 +35,8 @@ export declare class ExitFlush {
33
35
  private readonly deps;
34
36
  /** This flag is true while the library listens for the unload events. */
35
37
  private installed;
38
+ /** Bytes of the keepalive fetches of the current exit flush. All batches share one budget. */
39
+ private keepaliveBytes;
36
40
  /** This listener flushes on visibilitychange when the document becomes hidden. */
37
41
  private readonly onVisibility;
38
42
  /** This listener flushes on the window pagehide event. */
@@ -56,6 +60,13 @@ export declare class ExitFlush {
56
60
  * @param reason Reason code of the flush.
57
61
  */
58
62
  flush(reason: ExitReason): void;
63
+ /**
64
+ * Sends one exit batch with a beacon, a keepalive fetch or emergency storage.
65
+ * @param batch Batch to send.
66
+ * @param reason Reason code of the flush.
67
+ * @param url Endpoint of the batch.
68
+ */
69
+ private flushBatch;
59
70
  /** Runs the normal flush of a hidden document. It reports a flush that throws or rejects. */
60
71
  private flushAlive;
61
72
  /**
@@ -7,12 +7,12 @@ import { StatusTransport } from "./status-transport";
7
7
  export declare class HttpTransport extends StatusTransport {
8
8
  /**
9
9
  * Headers that the headers() function gave last. The exit flush sends them only while that
10
- * function and the endpoint are in force. A tenant switch must not send the old token to the
11
- * new endpoint.
10
+ * function and the two endpoints are in force. A tenant switch must not send the old token to
11
+ * the new endpoint.
12
12
  */
13
13
  private cachedHeaders;
14
14
  /**
15
- * Sends one log batch over HTTP.
15
+ * Sends one log batch over HTTP. A metrics batch goes to metricsEndpoint.
16
16
  * @param batch Batch to send.
17
17
  * @param onKeepalive Runs when a request of the batch starts with keepalive.
18
18
  * @throws TransportError on transient, throttled, 413, or permanent network failures.
@@ -27,6 +27,7 @@ export declare class HttpTransport extends StatusTransport {
27
27
  * Serializes, encodes and sends a batch. It throws a classified TransportError
28
28
  * on failure.
29
29
  * @param batch Batch to deliver.
30
+ * @param kind Kind of the batch. The caller reads it with the endpoint.
30
31
  * @param endpoint Ingest URL. The caller reads it one time. A reconfigure during the send
31
32
  * cannot change it.
32
33
  * @param onKeepalive Runs when a request of the batch starts with keepalive.
@@ -53,12 +54,14 @@ export declare class HttpTransport extends StatusTransport {
53
54
  * Waits for a step until the deadline.
54
55
  * @param work Step to wait for. It does not reject. Only the deadline rejects here.
55
56
  * @param deadline Epoch time in milliseconds at which the request times out.
57
+ * @param endpoint Ingest URL of the request, for the timeout report.
56
58
  * @returns Promise that resolves to the value of the step.
57
59
  * @throws TransportError of kind "timeout" at the deadline.
58
60
  */
59
61
  private before;
60
62
  /**
61
63
  * Reports a timeout and builds its error.
64
+ * @param endpoint Ingest URL of the request.
62
65
  * @returns TransportError of kind "timeout".
63
66
  */
64
67
  private timeout;
@@ -97,7 +100,6 @@ export declare class HttpTransport extends StatusTransport {
97
100
  /**
98
101
  * Resolves the configured static or dynamic request headers. It keeps the headers that
99
102
  * headers() gave, for the exit flush.
100
- * @param endpoint Ingest URL of the send.
101
103
  * @returns Promise that resolves to resolved header map.
102
104
  */
103
105
  private resolveHeaders;
@@ -12,6 +12,7 @@ export declare class RetryEngine {
12
12
  private readonly storage;
13
13
  private readonly transport;
14
14
  private readonly diagnostics;
15
+ private readonly config;
15
16
  private readonly batchesPerDrain;
16
17
  private readonly onLoss;
17
18
  /** This field holds the active retry timer handle. It is null when no timer runs. */
@@ -82,7 +83,8 @@ export declare class RetryEngine {
82
83
  * Tries to deliver one batch. It removes the batch on success. On failure, it applies the
83
84
  * rule for the failure kind.
84
85
  * @param batch Log batch to deliver.
85
- * @returns True to continue with the next batch. False to stop the current drain.
86
+ * @returns "next" to continue with the next batch. "stop" to stop the current drain. A delay
87
+ * in milliseconds blocks the kind of the batch until the next drain.
86
88
  */
87
89
  private deliver;
88
90
  /**
@@ -0,0 +1,3 @@
1
+ import type { LogSerializer } from "../../models/serializer";
2
+ /** This serializer writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */
3
+ export declare const otlpMetricsSerializer: LogSerializer;
@@ -1,3 +1,33 @@
1
+ import type { LogRecord } from "../../models/log-record";
1
2
  import type { LogSerializer } from "../../models/serializer";
3
+ /** This type holds an OTLP AnyValue with typed value wrappers. */
4
+ type AnyValue = Record<string, unknown>;
5
+ /** This interface holds an OTLP KeyValue pair. */
6
+ export interface KeyValue {
7
+ /** This field holds the attribute key. */
8
+ key: string;
9
+ /** This field holds the typed AnyValue. */
10
+ value: AnyValue;
11
+ }
12
+ /** This interface holds the records that share resource attributes. */
13
+ export interface ResourceGroup {
14
+ /** This field holds the resource attribute map. */
15
+ resource: Record<string, unknown>;
16
+ /** This field holds the log records of the resource. */
17
+ records: LogRecord[];
18
+ }
19
+ /**
20
+ * Converts a plain object to an array of OTLP KeyValue pairs.
21
+ * @param source Key-value attribute object.
22
+ * @returns Array of valid KeyValue pairs.
23
+ */
24
+ export declare function toKeyValues(source: Record<string, unknown>): KeyValue[];
25
+ /**
26
+ * Groups records by their resource attributes. It keeps the record order in each group.
27
+ * @param records Records to group.
28
+ * @returns One group for each resource.
29
+ */
30
+ export declare function groupByResource(records: LogRecord[]): ResourceGroup[];
2
31
  /** This serializer writes log records as OTLP/JSON payloads. */
3
32
  export declare const otlpSerializer: LogSerializer;
33
+ export {};
@@ -1,6 +1,6 @@
1
1
  import type { Diagnostics } from "../../core/diagnostics";
2
- import type { LogBatch } from "../../models/batch";
3
- import type { SerializerChoice } from "../../models/config";
2
+ import { type LogBatch } from "../../models/batch";
3
+ import type { BatchKind, ResolvedConfig, SerializerChoice } from "../../models/config";
4
4
  import type { LogSerializer, SerializedBatch } from "../../models/serializer";
5
5
  /**
6
6
  * Returns the implementation for a resolved serializer option.
@@ -8,12 +8,28 @@ import type { LogSerializer, SerializedBatch } from "../../models/serializer";
8
8
  * @returns Serializer implementation.
9
9
  */
10
10
  export declare function serializerFor(choice: SerializerChoice): LogSerializer;
11
+ /**
12
+ * Gives the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A stored
13
+ * record can be corrupt. It then is not a metric.
14
+ * @param batch Batch to test.
15
+ * @param config Active configuration.
16
+ * @returns "metrics" with metricsEndpoint set and only metric records, else "logs".
17
+ */
18
+ export declare function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind;
19
+ /**
20
+ * Gives the endpoint of a batch kind.
21
+ * @param kind Kind of the batch.
22
+ * @param config Active configuration.
23
+ * @returns metricsEndpoint for a metrics batch, else endpoint.
24
+ */
25
+ export declare function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null;
11
26
  /**
12
27
  * Serializes a batch. It reports a serializer that throws, and the caller drops the batch.
13
- * @param choice Serializer name, or a custom implementation.
28
+ * A metrics batch gets the OTLP metrics format.
29
+ * @param config Active configuration.
14
30
  * @param batch Batch to serialize.
15
31
  * @param diagnostics Diagnostics reporter.
16
32
  * @param message ASD-STE100 sentence for the report.
17
33
  * @returns The serialized batch, or undefined if the serializer threw.
18
34
  */
19
- export declare function serializeBatch(choice: SerializerChoice, batch: LogBatch, diagnostics: Diagnostics, message: string): SerializedBatch | undefined;
35
+ export declare function serializeBatch(config: ResolvedConfig, batch: LogBatch, diagnostics: Diagnostics, message: string): SerializedBatch | undefined;
@@ -1,6 +1,6 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
2
  import type { LogBatch } from "../models/batch";
3
- import type { ResolvedConfig } from "../models/config";
3
+ import type { BatchKind, ResolvedConfig } from "../models/config";
4
4
  import type { LossReporter } from "../models/drop";
5
5
  import type { SerializedBatch } from "../models/serializer";
6
6
  import { TransportError } from "./errors";
@@ -14,10 +14,11 @@ export interface BatchTransport {
14
14
  */
15
15
  send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;
16
16
  /**
17
- * Returns the remaining throttle delay.
17
+ * Returns the remaining throttle delay of the endpoint of a batch.
18
+ * @param batch Batch to send.
18
19
  * @returns Milliseconds until the throttle ends, or 0.
19
20
  */
20
- throttledForMs(): number;
21
+ throttledForMs(batch: LogBatch): number;
21
22
  }
22
23
  /** Hints that come with a rejected batch. */
23
24
  export interface RejectHints {
@@ -34,8 +35,11 @@ export declare abstract class StatusTransport implements BatchTransport {
34
35
  protected readonly diagnostics: Diagnostics;
35
36
  private readonly onSampling;
36
37
  private readonly onLoss;
37
- /** Epoch time in milliseconds when the server throttle ends. */
38
- private throttledUntil;
38
+ /**
39
+ * Epoch time in milliseconds when the server throttle ends, for each endpoint. A 429 from
40
+ * metricsEndpoint must not stop the log batches.
41
+ */
42
+ private readonly throttledUntil;
39
43
  /**
40
44
  * @param config Active configuration instance.
41
45
  * @param diagnostics Diagnostics reporter.
@@ -51,27 +55,31 @@ export declare abstract class StatusTransport implements BatchTransport {
51
55
  */
52
56
  abstract send(batch: LogBatch, onKeepalive?: () => void): Promise<void>;
53
57
  /**
54
- * Returns the remaining throttle delay in milliseconds.
58
+ * Returns the remaining throttle delay of the endpoint of a batch, in milliseconds.
59
+ * @param batch Batch to send.
55
60
  * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.
56
61
  */
57
- throttledForMs(): number;
62
+ throttledForMs(batch: LogBatch): number;
58
63
  /**
59
- * Serializes a batch with the configured serializer. It reports a serializer that throws.
64
+ * Serializes a batch with the configured serializer. A metrics batch gets the OTLP metrics
65
+ * format. It reports a serializer that throws.
60
66
  * @param batch Batch to serialize.
61
67
  * @returns The serialized batch, or undefined if the serializer threw.
62
68
  */
63
69
  protected serialize(batch: LogBatch): SerializedBatch | undefined;
64
70
  /**
65
- * Records an accepted batch. It ends a server throttle.
71
+ * Records an accepted batch. It ends the server throttle of the endpoint of the batch.
72
+ * @param kind Kind of the accepted batch.
66
73
  * @param sampling Sampling rules of the answer, as text or as an object.
67
74
  */
68
- protected accept(sampling: unknown): void;
75
+ protected accept(kind: BatchKind, sampling: unknown): void;
69
76
  /**
70
77
  * Converts a status code that is not 2xx into a classified TransportError.
71
78
  * @param status Status code of the answer.
72
79
  * @param batchId Identifier of the rejected batch.
80
+ * @param kind Kind of the rejected batch. A throttle applies only to its endpoint.
73
81
  * @param hints Delay, size limit and advice that come with the answer.
74
82
  * @returns Classified TransportError instance.
75
83
  */
76
- protected reject(status: number, batchId: string, hints: RejectHints): TransportError;
84
+ protected reject(status: number, batchId: string, kind: BatchKind, hints: RejectHints): TransportError;
77
85
  }
@@ -0,0 +1,15 @@
1
+ /** State of one fixed window. Counters that share a limit share one object. */
2
+ export interface StormWindow {
3
+ /** Start of the current window, in epoch milliseconds. */
4
+ start: number;
5
+ /** Events counted in the current window. */
6
+ count: number;
7
+ }
8
+ /**
9
+ * Counts one event in a fixed window.
10
+ * @param window Window state to change.
11
+ * @param limit Maximum events in each window.
12
+ * @param windowMs Length of the window, in milliseconds.
13
+ * @returns False when the window has no allowance left. The caller must drop the event.
14
+ */
15
+ export declare function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Tests if a value is an object that is not null and not an array.
3
+ * @param value Value to test.
4
+ * @returns True for an object with string keys.
5
+ */
6
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
@@ -10,3 +10,15 @@ export declare function runAsLibraryRequest<T>(fn: () => T): T;
10
10
  * @returns True while the library starts a request.
11
11
  */
12
12
  export declare function isLibraryRequest(): boolean;
13
+ /**
14
+ * Runs a custom transport call and counts it until it settles. The count includes the time after
15
+ * each await, which the library request scope does not cover.
16
+ * @param fn Function that calls the custom transport.
17
+ * @returns Promise that settles with the result of the call.
18
+ */
19
+ export declare function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T>;
20
+ /**
21
+ * Tests if a custom transport call waits for an answer.
22
+ * @returns True while a call has not settled.
23
+ */
24
+ export declare function isTransportPending(): boolean;
@@ -0,0 +1,48 @@
1
+ /** The InterApplicationBus operations that the bus link uses. */
2
+ export interface FinIab {
3
+ /**
4
+ * Publishes a message to all topic subscribers.
5
+ * @param topic Topic name.
6
+ * @param message Message payload.
7
+ */
8
+ publish(topic: string, message: unknown): Promise<void>;
9
+ /**
10
+ * Subscribes a listener to a topic for matching application identities.
11
+ * @param identity Target application identity.
12
+ * @param topic Topic name.
13
+ * @param listener Message callback.
14
+ */
15
+ subscribe(identity: {
16
+ uuid: string;
17
+ }, topic: string, listener: (message: unknown) => void): Promise<void>;
18
+ }
19
+ /** The members of fin.me that the library reads. */
20
+ export interface FinMe {
21
+ /** True in an OpenFin view. */
22
+ isView?: boolean;
23
+ /** Identity of the window or view. */
24
+ identity?: {
25
+ uuid?: string;
26
+ name?: string;
27
+ };
28
+ /** Resolves the creation options of the window, with customData. */
29
+ getOptions?: () => Promise<{
30
+ customData?: Record<string, unknown>;
31
+ }>;
32
+ /** Adds a window event listener. */
33
+ on?: (event: string, listener: () => void) => void;
34
+ /** Removes a window event listener. */
35
+ removeListener?: (event: string, listener: () => void) => void;
36
+ }
37
+ /** The members of the OpenFin global that the library reads. */
38
+ export interface FinLike {
39
+ /** The window or view of this document. */
40
+ me?: FinMe;
41
+ /** The message bus of the OpenFin runtime. */
42
+ InterApplicationBus?: FinIab;
43
+ }
44
+ /**
45
+ * Gives the OpenFin global.
46
+ * @returns The fin global, or undefined outside OpenFin.
47
+ */
48
+ export declare function getFin(): FinLike | undefined;
@@ -41,5 +41,10 @@ export declare function currentUrl(diagnostics: Diagnostics): string;
41
41
  * @returns The URL up to the first "?" or "#".
42
42
  */
43
43
  export declare function stripUrlQuery(url: string): string;
44
+ /**
45
+ * Tests if the browser can reach the network. A host without navigator.onLine counts as online.
46
+ * @returns False only when navigator.onLine is false.
47
+ */
48
+ export declare function isOnline(): boolean;
44
49
  /** Resets the cached platform metadata for testing. */
45
50
  export declare function resetPlatformCache(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@utk09/ui-observability",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
4
4
  "description": "UI observability and logging for browser, OpenFin and webview applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -73,11 +73,10 @@
73
73
  "test:watch": "vitest",
74
74
  "test:coverage": "vitest run --coverage",
75
75
  "typecheck": "tsc --noEmit",
76
- "check:version": "node tools/check-version-sync.mjs",
77
76
  "check:peers": "node tools/check-peer-imports.mjs",
78
77
  "check:size": "node tools/check-size.mjs",
79
78
  "check:dev": "node tools/check-dev-server.mjs",
80
- "verify": "npm run format:check && npm run check:version && npm run typecheck && npm run build && npm run lint && npm run check:peers && npm run check:size && npm run check:dev && npm run test:coverage",
79
+ "verify": "npm run format:check && npm run typecheck && npm run build && npm run lint && npm run check:peers && npm run check:size && npm run check:dev && npm run test:coverage",
81
80
  "prepublishOnly": "npm run verify"
82
81
  },
83
82
  "peerDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"batch-DEK4bv9N.js","names":["ATTR_LOG_TYPE","LOG_TYPE_ACTION","newId","isLogBatch","value","id","createdAt","attempts","records","splitBatch","batch","middle","halve","diagnostics","attributeOf","record","attributes","key","isActionRecord"],"sources":["../src/models/batch.ts"],"sourcesContent":["// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport { ATTR_LOG_TYPE, LOG_TYPE_ACTION } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. It stays the same across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Tells if a value from storage has all fields of a batch. `keyOf` cannot match\n * an entry without `id` after delivery. The library then retries that entry with no\n * end, and the entry blocks each batch behind it. An entry without `attempts` counts\n * as NaN. That count never reaches `maxAttempts`. Thus the library never drops the\n * entry as a dead letter.\n * @param value Parsed storage entry.\n * @returns True when each required field is present and has the correct type.\n */\nexport function isLogBatch(value: unknown): value is LogBatch {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const id: unknown = Reflect.get(value, \"id\");\n const createdAt: unknown = Reflect.get(value, \"createdAt\");\n const attempts: unknown = Reflect.get(value, \"attempts\");\n const records: unknown = Reflect.get(value, \"records\");\n\n return (\n typeof id === \"string\" &&\n typeof createdAt === \"number\" &&\n typeof attempts === \"number\" &&\n Array.isArray(records)\n );\n}\n\n/**\n * Splits a batch that the server rejected as too large into two halves.\n * Each half gets a new id. Each half keeps the age and attempts of the original batch.\n * @param batch The rejected batch.\n * @param diagnostics Diagnostics reporter for the new batch ids.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch, diagnostics: Diagnostics): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(diagnostics),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n\n/**\n * Reads one attribute of a record. A record from storage can be corrupt. It can be null or have\n * no attributes.\n * @param record Record to read.\n * @param key Attribute key.\n * @returns The attribute value, or undefined for a corrupt record.\n */\nexport function attributeOf(record: LogRecord, key: string): unknown {\n const value: unknown = record;\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const attributes: unknown = Reflect.get(value, \"attributes\");\n if (typeof attributes !== \"object\" || attributes === null) {\n return undefined;\n }\n\n return Reflect.get(attributes, key);\n}\n\n/**\n * Tests if a record is an action. A corrupt record from storage is not an action.\n * @param record Record to test.\n * @returns True for an action record.\n */\nexport function isActionRecord(record: LogRecord): boolean {\n return attributeOf(record, ATTR_LOG_TYPE) === LOG_TYPE_ACTION;\n}\n"],"mappings":";;;AAiCA,SAAgBG,EAAW,GAAmC;CAC5D,IAAI,OAAOC,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAMC,IAAc,QAAQ,IAAID,GAAO,IAAI,GACrCE,IAAqB,QAAQ,IAAIF,GAAO,WAAW,GACnDG,IAAoB,QAAQ,IAAIH,GAAO,UAAU,GACjDI,IAAmB,QAAQ,IAAIJ,GAAO,SAAS;CAErD,OACE,OAAOC,KAAO,YACd,OAAOC,KAAc,YACrB,OAAOC,KAAa,YACpB,MAAM,QAAQC,CAAO;AAEzB;AASA,SAAgBC,EAAW,GAAiB,GAAuD;CACjG,IAAIC,EAAM,QAAQ,SAAS,GACzB,OAAO;CAGT,IAAMC,IAAS,KAAK,MAAMD,EAAM,QAAQ,SAAS,CAAC,GAC5CE,KAAS,OAAoC;EACjD,IAAIV,EAAMW,CAAW;EACrB;EACA,WAAWH,EAAM;EACjB,UAAUA,EAAM;CAClB;CAEA,OAAO,CAACE,EAAMF,EAAM,QAAQ,MAAM,GAAGC,CAAM,CAAC,GAAGC,EAAMF,EAAM,QAAQ,MAAMC,CAAM,CAAC,CAAC;AACnF;AASA,SAAgBG,EAAY,GAAmB,GAAsB;CACnE,IAAMV,IAAiBW;CACvB,IAAI,OAAOX,KAAU,aAAYA,GAC/B;CAGF,IAAMY,IAAsB,QAAQ,IAAIZ,GAAO,YAAY;CAC3D,IAAI,OAAOY,KAAe,YAAYA,GAItC,OAAO,QAAQ,IAAIA,GAAYC,CAAG;AACpC;AAOA,SAAgBC,EAAe,GAA4B;CACzD,OAAOJ,EAAYC,GAAQf,CAAa,MAAMC;AAChD"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-X86IDwkC.cjs"),t=require("./identity-B1GDS1Tb.cjs");function n(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function r(e,n){if(e.records.length<2)return null;let r=Math.floor(e.records.length/2),i=r=>({id:t.i(n),records:r,createdAt:e.createdAt,attempts:e.attempts});return[i(e.records.slice(0,r)),i(e.records.slice(r))]}function i(e,t){let n=e;if(typeof n!=`object`||!n)return;let r=Reflect.get(n,`attributes`);if(typeof r==`object`&&r)return Reflect.get(r,t)}function a(t){return i(t,e.d)===e.pt}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return i}});
2
- //# sourceMappingURL=batch-DEVFs28i.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"batch-DEVFs28i.cjs","names":["newId","ATTR_LOG_TYPE","LOG_TYPE_ACTION","require_constants","require_identity","isLogBatch","value","id","createdAt","attempts","records","splitBatch","batch","middle","halve","diagnostics","attributeOf","record","attributes","key","isActionRecord"],"sources":["../src/models/batch.ts"],"sourcesContent":["// src/models/batch.ts\n//\n// A batch of log records for delivery to the ingest endpoint.\n\nimport { ATTR_LOG_TYPE, LOG_TYPE_ACTION } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { newId } from \"../utils/identity\";\nimport type { LogRecord } from \"./log-record\";\n\n/**\n * A batch of records with a stable id used for server-side deduplication across retries.\n * @see {@link splitBatch}\n */\nexport interface LogBatch {\n /** Deduplication key. It stays the same across retries and reloads. */\n id: string;\n /** Records to deliver, in log order. */\n records: LogRecord[];\n /** Batch creation time, in epoch milliseconds. */\n createdAt: number;\n /** Delivery attempts so far. */\n attempts: number;\n}\n\n/**\n * Tells if a value from storage has all fields of a batch. `keyOf` cannot match\n * an entry without `id` after delivery. The library then retries that entry with no\n * end, and the entry blocks each batch behind it. An entry without `attempts` counts\n * as NaN. That count never reaches `maxAttempts`. Thus the library never drops the\n * entry as a dead letter.\n * @param value Parsed storage entry.\n * @returns True when each required field is present and has the correct type.\n */\nexport function isLogBatch(value: unknown): value is LogBatch {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const id: unknown = Reflect.get(value, \"id\");\n const createdAt: unknown = Reflect.get(value, \"createdAt\");\n const attempts: unknown = Reflect.get(value, \"attempts\");\n const records: unknown = Reflect.get(value, \"records\");\n\n return (\n typeof id === \"string\" &&\n typeof createdAt === \"number\" &&\n typeof attempts === \"number\" &&\n Array.isArray(records)\n );\n}\n\n/**\n * Splits a batch that the server rejected as too large into two halves.\n * Each half gets a new id. Each half keeps the age and attempts of the original batch.\n * @param batch The rejected batch.\n * @param diagnostics Diagnostics reporter for the new batch ids.\n * @returns Two batches, or `null` if a single record is already over the limit.\n */\nexport function splitBatch(batch: LogBatch, diagnostics: Diagnostics): [LogBatch, LogBatch] | null {\n if (batch.records.length < 2) {\n return null;\n }\n\n const middle = Math.floor(batch.records.length / 2);\n const halve = (records: LogRecord[]): LogBatch => ({\n id: newId(diagnostics),\n records,\n createdAt: batch.createdAt,\n attempts: batch.attempts,\n });\n\n return [halve(batch.records.slice(0, middle)), halve(batch.records.slice(middle))];\n}\n\n/**\n * Reads one attribute of a record. A record from storage can be corrupt. It can be null or have\n * no attributes.\n * @param record Record to read.\n * @param key Attribute key.\n * @returns The attribute value, or undefined for a corrupt record.\n */\nexport function attributeOf(record: LogRecord, key: string): unknown {\n const value: unknown = record;\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const attributes: unknown = Reflect.get(value, \"attributes\");\n if (typeof attributes !== \"object\" || attributes === null) {\n return undefined;\n }\n\n return Reflect.get(attributes, key);\n}\n\n/**\n * Tests if a record is an action. A corrupt record from storage is not an action.\n * @param record Record to test.\n * @returns True for an action record.\n */\nexport function isActionRecord(record: LogRecord): boolean {\n return attributeOf(record, ATTR_LOG_TYPE) === LOG_TYPE_ACTION;\n}\n"],"mappings":"iFAiCA,SAAgBK,EAAW,EAAmC,CAC5D,GAAI,OAAOC,GAAU,WAAYA,EAC/B,MAAO,GAGT,IAAMC,EAAc,QAAQ,IAAID,EAAO,IAAI,EACrCE,EAAqB,QAAQ,IAAIF,EAAO,WAAW,EACnDG,EAAoB,QAAQ,IAAIH,EAAO,UAAU,EACjDI,EAAmB,QAAQ,IAAIJ,EAAO,SAAS,EAErD,OACE,OAAOC,GAAO,UACd,OAAOC,GAAc,UACrB,OAAOC,GAAa,UACpB,MAAM,QAAQC,CAAO,CAEzB,CASA,SAAgBC,EAAW,EAAiB,EAAuD,CACjG,GAAIC,EAAM,QAAQ,OAAS,EACzB,OAAO,KAGT,IAAMC,EAAS,KAAK,MAAMD,EAAM,QAAQ,OAAS,CAAC,EAC5CE,EAAS,IAAoC,CACjD,GAAId,EAAAA,EAAMe,CAAW,EACrB,UACA,UAAWH,EAAM,UACjB,SAAUA,EAAM,QAClB,GAEA,MAAO,CAACE,EAAMF,EAAM,QAAQ,MAAM,EAAGC,CAAM,CAAC,EAAGC,EAAMF,EAAM,QAAQ,MAAMC,CAAM,CAAC,CAAC,CACnF,CASA,SAAgBG,EAAY,EAAmB,EAAsB,CACnE,IAAMV,EAAiBW,EACvB,GAAI,OAAOX,GAAU,WAAYA,EAC/B,OAGF,IAAMY,EAAsB,QAAQ,IAAIZ,EAAO,YAAY,EAC3D,GAAI,OAAOY,GAAe,UAAYA,EAItC,OAAO,QAAQ,IAAIA,EAAYC,CAAG,CACpC,CAOA,SAAgBC,EAAe,EAA4B,CACzD,OAAOJ,EAAYC,EAAQhB,EAAAA,CAAa,IAAMC,EAAAA,EAChD"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-X86IDwkC.cjs"),t=require("./deadline-XSnm95pg.cjs"),n=require("./journey-DxlfdFJV.cjs"),r=require("./remote-rules-ByS34k4e.cjs");function i(t){return{p:e.T,m:t}}function a(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var o=Symbol.for(e.qt),s=`null`;function c(e,t){return e===s?`The bus ignored ${t} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`:`The bus ignored ${t} from ${e}. If you own this origin, add it to bus.trustedOrigins.`}function l(){let e=location.ancestorOrigins;if(e&&e.length>0)return e.item(0);let t=document.referrer;if(t===``)return null;try{return new URL(t).origin}catch{return null}}function u(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[o]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function d(e,t,n){if(typeof window>`u`||window.parent===window)return null;let r=location.origin;if(r===s)return n.report(`bus.untrusted_origin`,`This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`,{origin:r,type:`parent`}),null;let o=new Set([r,...t]),u=l();if(u===null||!o.has(u))return n.report(`bus.untrusted_origin`,u===null?`The origin of the parent frame is unknown. This context sends its own records.`:`The parent frame is on ${u}. This origin is not in bus.trustedOrigins. This context sends its own records.`,{origin:u??``,type:`parent`}),null;let d=new Set,f=t=>{let r=a(t.data);r&&t.source===window.parent&&(o.has(t.origin)?e(r,{link:`parent`,origin:t.origin}):d.has(t.origin)||(d.add(t.origin),n.report(`bus.untrusted_origin`,c(t.origin,`a message`),{origin:t.origin,type:r.t.slice(0,32)})))};return addEventListener(`message`,f),{kind:`parent`,post(e){n.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(i(e),u)})},close(){removeEventListener(`message`,f)}}}function f(e,t,n){if(typeof window>`u`)return null;let r=new Set([location.origin,...t]);r.delete(s);let o=new Map,l=t=>{let i=a(t.data);i&&(r.has(t.origin)?(t.source&&o.set(t.source,t.origin),e(i,{link:`children`,origin:t.origin})):n.report(`bus.untrusted_origin`,c(t.origin,`a message`),{origin:t.origin,type:i.t.slice(0,32)}))};return addEventListener(`message`,l),{kind:`children`,post(e){for(let[t,r]of o){let a=t;a.closed?o.delete(t):n.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{a.postMessage(i(e),r)})}},close(){removeEventListener(`message`,l),o.clear()}}}function p(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let o=n.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new r(e));return o?(o.onmessage=e=>{let n=a(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{o.postMessage(i(e))})},close(){n.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{o.close()})}}):null}function m(e,t,n,r){let o=globalThis.fin?.InterApplicationBus;if(!o)return null;if(!t)return r.report(`openfin.unavailable`,`OpenFin gives no application uuid. The InterApplicationBus link stays closed.`),null;let s=`${e}.${t}`;return r.guardAsync(`bus.send_failed`,`The InterApplicationBus.subscribe call failed.`,()=>o.subscribe({uuid:t},s,e=>{let t=a(e);t&&n(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){r.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>o.publish(s,i(e)))},close(){}}}function h(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=a(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`The postMessage call of the worker failed.`,()=>{r(i(e))})},close(){}})}function g(e,t,n){let r=e=>{let n=a(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(i(t))})},close(){e.removeEventListener(`message`,r)}}}var _={timeoutMs:e.C,maxAttempts:3},v=[`children`,`direct`,`worker`],y=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;rulesPoll;destroyed=!1;ownerId=null;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=_){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a,this.handshakeOptions=o}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;if(this.isOpenFinProvider=this.resolveOpenFinProvider(),e.mode===`sender`||e.mode===`forwarder`)return this.role=e.mode,this.openControlLinks(),this.role===`forwarder`&&(this.upstream=this.candidateUpstream(),this.upstream||this.diagnostics.report(`bus.no_owner`,`bus.mode is "forwarder". No owner exists. The library drops the records of this context.`)),this.resolved=!0,this.announce(),this.role;this.openControlLinks();let t=u(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`This context attached directly to the runtime of its same-origin parent.`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`No owner exists. This context sends its own records.`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.handshakeOptions.maxAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`No owner answered after ${String(r)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`The bus role is ${this.role}.`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`)this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);else if(e.t===`journey?`){let r=this.handlers.onJourneyRequest();r&&this.journeyLink(`direct`)&&t({t:`journey`,from:this.contextId,to:e.from,journey:r},n)}else e.t===`sampling?`?t(this.rulesAnswer(e.from),n):this.receive(e,n)}attachWorker(e){this.links.push(g(e,this.receive,this.diagnostics))}broadcastJourney(e){this.postJourney({t:`journey`,from:this.contextId,journey:e})}destroy(){this.destroyed=!0,clearInterval(this.rulesPoll),this.rulesPoll=void 0;for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.ownerId=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}postJourney(e){for(let t of this.allLinks())this.journeyLink(t.kind)&&t.post(e)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&(this.ownerId=e.from,this.awaitingWelcome.settle(!0));break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&this.canRelay(t.link)&&this.upstream.post(e);break;case`journey`:this.acceptsJourney(e,t)&&this.applyJourney(e.journey);break;case`journey?`:{let n=this.handlers.onJourneyRequest();n&&this.journeyLink(t.link)&&this.postOver(t.link,{t:`journey`,from:this.contextId,to:e.from,journey:n});break}case`sampling?`:(this.role===`forwarder`?t.link!==this.upstream?.kind:this.canOwn(t.link))&&this.postOver(t.link,this.rulesAnswer(e.from));break;case`sampling`:this.acceptsRules(e.to,t)&&this.applyRules(e.rules);break;case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canRelay(e){return e===`direct`||e!==this.upstream?.kind}canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:v.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){return this.isCrossOriginFrame()?`retry`:`promote`}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return Reflect.get(window.parent,`location`),!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?h(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:d(this.receive,this.config.bus.trustedOrigins,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(f(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(p(e.S,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=m(e.S,this.platform.openfinUuid,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,this.awaitingWelcome=null,clearTimeout(a),n(e))};this.awaitingWelcome={link:e.kind,settle:i};let a=setTimeout(()=>{i(!1)},this.handshakeOptions.timeoutMs);t.r(a),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.postJourney({t:`journey?`,from:this.contextId}),this.pollRules()}journeyScope(){let{scope:e}=this.config.journey;if(e!==`auto`)return e;let{platform:t}=this.platform;return t===`openfin`||t===`openfin_web`?`origin`:`tab`}journeyLink(e){let t=this.journeyScope();return t===`context`?!1:t===`origin`||e!==`broadcast`}acceptsJourney(e,t){return!this.journeyLink(t.link)||e.to!==void 0&&e.to!==this.contextId?!1:this.journeyScope()===`origin`||this.fromOwner(e.from,t.link)}fromOwner(e,t){return this.role!==`forwarder`||t!==this.upstream?.kind?!1:this.ownerId===null||e===this.ownerId}applyJourney(e){if(e===null){this.handlers.onJourney(null);return}let t=n.r(e);t===null?this.diagnostics.report(`record.dropped_malformed`,`The bus dropped a journey message. Its payload is not a journey.`,{type:`journey`}):this.handlers.onJourney(t)}rulesAnswer(e){let t=this.handlers.remote.sampling?.wire()??null;return{t:`sampling`,from:this.contextId,to:e,rules:t}}acceptsRules(e,t){if(this.role!==`forwarder`||e!==this.contextId||t.link!==this.upstream?.kind)return!1;let{origin:n}=t;return t.link===`parent`&&n!==location.origin&&!this.config.bus.trustedOrigins.includes(n)?(this.diagnostics.report(`bus.untrusted_origin`,`The bus ignored sampling rules from ${n}. If you own this origin, add it to bus.trustedOrigins.`,{origin:n,type:`sampling`}),!1):!0}applyRules(e){if(e===null){r.t(this.handlers.remote,this.config,null);return}let t=r.n(e,this.diagnostics);t&&r.t(this.handlers.remote,this.config,t)}pollRules(){let{upstream:n}=this;if(this.destroyed||this.role!==`forwarder`||!n)return;let r=()=>{this.config.sampling.remote&&n.post({t:`sampling?`,from:this.contextId})};r(),this.rulesPoll=setInterval(r,e.kt),t.r(this.rulesPoll)}};exports.Bus=y;
2
- //# sourceMappingURL=bus-DNFvTkif.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bus-DNFvTkif.cjs","names":["BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_HANDSHAKE_TIMEOUT_MS","BUS_CHANNEL_NAME","parseJourney","parseRemoteRules","REMOTE_SAMPLING_POLL_MS","require_constants","require_deadline","require_journey","require_remote_rules","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","OPAQUE_ORIGIN","untrustedText","origin","what","parentOrigin","ancestors","referrer","createDirectLink","host","target","open","diagnostics","receive","createParentLink","self","trusted","trustedOrigins","reported","onMessage","event","createChildrenLink","sources","source","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","createOwnerLink","scope","send","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","reply","current","link","configured","me","push","settled","finish","timer","resolve","result","from","payload","journey","rules","to","update","upstream","ask"],"sources":["../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL } from \"../constants\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role. It tells if this context sends its records or forwards them upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel. The bus uses it to route incoming and outgoing messages.\n * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe\n * looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Inbound transport channel kind. */\n link: LinkKind;\n /** `event.origin` for `parent` and `children`. Other links use `\"same-origin\"` or `\"openfin\"`. */\n origin: string;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: \"hello\"; from: string; tabId: string }\n /**\n * Handshake response from an upstream owner. The `to` field holds the address.\n * A welcome on InterApplicationBus goes to every subscriber. Without an address,\n * each waiting view accepts the welcome as its own.\n */\n | { t: \"welcome\"; from: string; to: string; tabId: string }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: \"records\"; from: string; records: LogRecord[] }\n /**\n * Journey update, or the answer to a journey question. An answer holds the address of the\n * context that asked in `to`. The payload comes from another realm. The receiver parses it.\n */\n | { t: \"journey\"; from: string; to?: string; journey: unknown }\n /** Query requesting active journey state from connected peers. */\n | { t: \"journey?\"; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: \"tab\"; from: string; tabId: string }\n /** Request of a forwarder for the remote sampling rules in force. */\n | { t: \"sampling?\"; from: string }\n /**\n * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field\n * holds the address of the forwarder that asked. The receiver validates `rules` again.\n * Null rules end the copy of the forwarder.\n */\n | { t: \"sampling\"; from: string; to: string; rules: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A\n * document gets `message` events from all embedded content on the page. This\n * includes analytics tags, video players and extensions. Without the tag check,\n * the bus parses a message from a video player as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { BUS_TYPE_DETAIL_MAX_CHARS, RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\n\n/** Bidirectional communication channel for bus message transport. */\nexport interface Link {\n /** Channel transport kind. */\n readonly kind: LinkKind;\n\n /**\n * Sends a message over the channel without throwing.\n * @param message Bus message to transmit.\n */\n post(message: BusMessage): void;\n\n /** Releases listeners, subscriptions, or channels held open by the link. */\n close(): void;\n}\n\n/**\n * Callback invoked when a bus message arrives on a link.\n * @param message Received bus message.\n * @param source Origin and link metadata.\n */\nexport type Receive = (message: BusMessage, source: MessageSource) => void;\n\n/** Interface that a same-origin parent runtime exposes on a global symbol. */\nexport interface DirectHost {\n /**\n * Accepts a message directly from a child frame and replies synchronously.\n * @param message Child bus message.\n * @param reply Callback for synchronous response.\n */\n busAccept(message: BusMessage, reply: Receive): void;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst OPAQUE_ORIGIN = \"null\";\n\n/** Location with the ancestor list that Chromium and WebKit give. */\ninterface LocationWithAncestors {\n origin: string;\n ancestorOrigins?: { length: number; item: (index: number) => string | null };\n}\n\n/**\n * Builds the message for an ignored message from an untrusted origin.\n * @param origin Origin of the sender.\n * @param what What the bus ignored, for example \"a message\".\n * @returns The message. A sandboxed sender gets the fix for its frame.\n */\nfunction untrustedText(origin: string, what: string): string {\n if (origin === OPAQUE_ORIGIN) {\n return `The bus ignored ${what} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`;\n }\n\n return `The bus ignored ${what} from ${origin}. If you own this origin, add it to bus.trustedOrigins.`;\n}\n\n/**\n * Reads the origin of the parent frame. A cross-origin parent does not give its location.\n * @returns The origin, or null when the browser does not give it.\n */\nfunction parentOrigin(): string | null {\n const ancestors = (location as LocationWithAncestors).ancestorOrigins;\n if (ancestors && ancestors.length > 0) {\n return ancestors.item(0);\n }\n\n // Firefox has no ancestorOrigins. The referrer of a frame is the page that loaded it.\n // A Referrer-Policy of no-referrer gives \"\". The caller reports an unknown origin.\n const referrer = document.referrer;\n if (referrer === \"\") {\n return null;\n }\n\n try {\n return new URL(referrer).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n const target = host;\n let open = true;\n\n return {\n kind: \"direct\",\n post(message) {\n if (!open) {\n return;\n }\n\n // Stops an error in the parent runtime from breaking a logging call in the child.\n diagnostics.guard(\n \"bus.send_failed\",\n \"The direct call into the parent runtime failed.\",\n () => {\n target.busAccept(message, receive);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to a parent window on a trusted origin. Records hold user data.\n * A page on another origin that frames this app must not get them.\n * @param receive Callback for incoming parent messages.\n * @param trustedOrigins Origins of a parent that can get the records, in addition to this origin.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to the parent window, or null at the top level or with an untrusted parent.\n * With null, this context sends its own records.\n */\nexport function createParentLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n // A sandboxed frame has an opaque origin. No parent can list it in its own trust list.\n const self = location.origin;\n if (self === OPAQUE_ORIGIN) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n 'This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.',\n { origin: self, type: \"parent\" },\n );\n return null;\n }\n\n const trusted = new Set([self, ...trustedOrigins]);\n const target = parentOrigin();\n if (target === null || !trusted.has(target)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n target === null\n ? \"The origin of the parent frame is unknown. This context sends its own records.\"\n : `The parent frame is on ${target}. This origin is not in bus.trustedOrigins. This context sends its own records.`,\n { origin: target ?? \"\", type: \"parent\" },\n );\n return null;\n }\n\n // Report each untrusted origin one time. A hostile parent can send many messages.\n const reported = new Set<string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message || event.source !== window.parent) {\n return;\n }\n\n // The parent can navigate to another origin after this frame loads.\n if (!trusted.has(event.origin)) {\n if (!reported.has(event.origin)) {\n reported.add(event.origin);\n // The parent sets message.t. Keep it out of the message text. Cut it in the detail.\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n }\n return;\n }\n\n receive(message, { link: \"parent\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // Target the trusted origin, not \"*\". The browser drops the message if the parent\n // navigated to another origin.\n window.parent.postMessage(envelope(message), target);\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // A sandboxed page has the opaque origin \"null\". Each sandboxed child also has it.\n const trusted = new Set([location.origin, ...trustedOrigins]);\n trusted.delete(OPAQUE_ORIGIN);\n\n // The map keeps the origin of each source.\n // A child that navigates must not get the ids of its previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n if (!trusted.has(event.origin)) {\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n return;\n }\n\n if (event.source) {\n sources.set(event.source, event.origin);\n }\n receive(message, { link: \"children\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n continue;\n }\n diagnostics.guard(\n \"bus.send_failed\",\n \"The postMessage call to a child frame failed.\",\n () => {\n // Targets the last known origin of the child. The browser drops the\n // message if the child navigated to a different origin.\n target.postMessage(envelope(message), origin);\n },\n );\n }\n },\n close() {\n removeEventListener(\"message\", onMessage);\n sources.clear();\n },\n };\n}\n\n/**\n * Creates a same-origin BroadcastChannel link for cross-tab control messages.\n * @param channelName BroadcastChannel identifier.\n * @param receive Callback for incoming cross-tab messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Broadcast link, or null if unsupported.\n */\nexport function createBroadcastLink(\n channelName: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const BC = (globalThis as { BroadcastChannel?: typeof BroadcastChannel }).BroadcastChannel;\n if (typeof BC === \"undefined\") {\n return null;\n }\n\n const channel = diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not open the BroadcastChannel.\",\n () => new BC(channelName),\n );\n if (!channel) {\n return null;\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"broadcast\", origin: \"same-origin\" });\n }\n };\n\n return {\n kind: \"broadcast\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The BroadcastChannel.postMessage call failed.\", () => {\n channel.postMessage(envelope(message));\n });\n },\n close() {\n diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not close the BroadcastChannel.\",\n () => {\n channel.close();\n },\n );\n },\n };\n}\n\n/** Structural interface for OpenFin InterApplicationBus operations. */\ninterface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/**\n * Creates an OpenFin InterApplicationBus link scoped to one application.\n * @param topic InterApplicationBus topic prefix.\n * @param appUuid OpenFin application uuid owning this context.\n * @param receive Callback for received topic messages.\n * @param diagnostics Diagnostics reporter.\n * @returns OpenFin link, or null if InterApplicationBus or the identity is unavailable.\n */\nexport function createOpenFinLink(\n topic: string,\n appUuid: string | undefined,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const fin = (globalThis as { fin?: { InterApplicationBus?: FinIab } }).fin;\n const iab = fin?.InterApplicationBus;\n if (!iab) {\n return null;\n }\n if (!appUuid) {\n // publish() sends to every subscriber on the runtime. Without a uuid scope,\n // this link shares the bus of this app with all other apps.\n diagnostics.report(\n \"openfin.unavailable\",\n \"OpenFin gives no application uuid. The InterApplicationBus link stays closed.\",\n );\n return null;\n }\n\n // The topic and the subscriber identity both contain the uuid. The topic keeps\n // messages of this app from other apps. The identity rejects messages from other apps.\n const scoped = `${topic}.${appUuid}`;\n\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.subscribe call failed.\",\n () =>\n iab.subscribe({ uuid: appUuid }, scoped, (raw) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, { link: \"openfin\", origin: \"openfin\" });\n }\n }),\n );\n\n return {\n kind: \"openfin\",\n post(message) {\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.publish call failed.\",\n () => iab.publish(scoped, envelope(message)),\n );\n },\n close() {\n // OpenFin removes the subscriptions when the context closes.\n },\n };\n}\n\n/**\n * Creates the worker-side link pointing at the document that created this\n * worker. Emits `kind: \"owner\"`.\n * @param receive Callback for incoming messages from the owning document.\n * @param diagnostics Diagnostics reporter.\n * @returns Owner link, or null outside a DedicatedWorkerGlobalScope.\n */\nexport function createOwnerLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n const scope = globalThis as unknown as {\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: string, listener: (event: MessageEvent) => void) => void;\n WorkerGlobalScope?: unknown;\n };\n const send = scope.postMessage;\n if (typeof scope.WorkerGlobalScope === \"undefined\" || !send) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"owner\", origin: \"same-origin\" });\n }\n };\n scope.addEventListener?.(\"message\", onMessage);\n\n return {\n kind: \"owner\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call of the worker failed.\", () => {\n send(envelope(message));\n });\n },\n close() {\n // Worker scope listeners stop when the worker stops.\n },\n };\n}\n\n/**\n * Creates the document-side link pointing at one attached worker or port.\n * Emits `kind: \"worker\"`.\n * @param worker Target worker instance or MessagePort.\n * @param receive Callback for messages from the worker.\n * @param diagnostics Diagnostics reporter.\n * @returns Document-to-worker link.\n */\nexport function createWorkerLink(\n worker: WorkerLike,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link {\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"worker\", origin: \"same-origin\" });\n }\n };\n worker.addEventListener(\"message\", onMessage);\n\n // Starts delivery on a MessagePort. A Worker has no start method.\n worker.start?.();\n\n return {\n kind: \"worker\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a worker failed.\", () => {\n worker.postMessage(envelope(message));\n });\n },\n close() {\n worker.removeEventListener(\"message\", onMessage);\n },\n };\n}\n","// src/bus/bus.ts\n//\n// Resolves the bus role and routes messages between realms.\n\nimport {\n BUS_CHANNEL_NAME,\n BUS_HANDSHAKE_TIMEOUT_MS,\n BUS_MAX_HANDSHAKE_ATTEMPTS,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type Journey, parseJourney } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { JourneyScope, ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport {\n createBroadcastLink,\n createChildrenLink,\n createDirectLink,\n createOpenFinLink,\n createOwnerLink,\n createParentLink,\n createWorkerLink,\n type Link,\n type Receive,\n type WorkerLike,\n} from \"./links\";\n\n/** Handshake timing for a forwarder waiting on an owner. */\nexport interface HandshakeOptions {\n /** Maximum time that a forwarder waits for an owner to answer, in milliseconds. */\n timeoutMs: number;\n /** Attempts allowed before a cross-origin forwarder promotes itself to sender. */\n maxAttempts: number;\n}\n\n/** Default handshake timing. Tests build a bus with shorter values. */\nexport const HANDSHAKE_OPTIONS: HandshakeOptions = {\n timeoutMs: BUS_HANDSHAKE_TIMEOUT_MS,\n maxAttempts: BUS_MAX_HANDSHAKE_ATTEMPTS,\n};\n\n/** Callbacks for handling records and journey events from connected realms. */\nexport interface BusHandlers {\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Journey scope after the bus resolves \"auto\". */\ntype ResolvedScope = Exclude<JourneyScope, \"auto\">;\n\n/** Structural shape of fin.me identity metadata. */\ninterface OpenFinMe {\n isView?: boolean;\n identity?: { uuid?: string; name?: string };\n}\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Current bus role. The default is \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** True if this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** True if role resolution is complete. */\n private resolved = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(). A handshake that ends later must not start a timer. */\n private destroyed = false;\n /** Context id of the owner that answered the handshake. Null with no handshake. */\n private ownerId: string | null = null;\n /** Active handshake state awaiting welcome response. */\n private awaitingWelcome: {\n link: LinkKind;\n settle: (ok: boolean) => void;\n } | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param platform Platform runtime metadata.\n * @param contextId Unique context identifier for loop prevention.\n * @param tabId Tab identifier announced on broadcast channels.\n * @param handlers Callbacks for routed bus events.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n private readonly platform: PlatformMetadata,\n private readonly contextId: string,\n private readonly tabId: string,\n private readonly handlers: BusHandlers,\n private readonly handshakeOptions: HandshakeOptions = HANDSHAKE_OPTIONS,\n ) {}\n\n /** Returns the resolved bus role. */\n getRole(): BusRole {\n return this.role;\n }\n\n /** Returns true if role resolution is complete. */\n isResolved(): boolean {\n return this.resolved;\n }\n\n /**\n * Resolves bus role and establishes control links.\n * @returns Resolved role.\n */\n async start(): Promise<BusRole> {\n const { bus } = this.config;\n\n if (bus.mode === \"off\") {\n this.role = \"sender\";\n this.resolved = true;\n return this.role;\n }\n\n this.isOpenFinProvider = this.resolveOpenFinProvider();\n\n if (bus.mode === \"sender\" || bus.mode === \"forwarder\") {\n this.role = bus.mode;\n this.openControlLinks();\n if (this.role === \"forwarder\") {\n this.upstream = this.candidateUpstream();\n if (!this.upstream) {\n this.diagnostics.report(\n \"bus.no_owner\",\n 'bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.',\n );\n }\n }\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n this.openControlLinks();\n\n // A same-origin parent runtime accepts a direct synchronous link.\n const direct = createDirectLink(this.receive, this.diagnostics);\n if (direct) {\n this.role = \"forwarder\";\n this.upstream = direct;\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"This context attached directly to the runtime of its same-origin parent.\",\n {\n role: \"forwarder\",\n via: \"direct\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const candidate = this.candidateUpstream();\n\n if (!candidate) {\n this.role = \"sender\";\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"No owner exists. This context sends its own records.\",\n {\n role: \"sender\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const attempts = this.orphanPolicy() === \"retry\" ? this.handshakeOptions.maxAttempts : 1;\n\n let welcomed = false;\n for (let attempt = 0; attempt < attempts && !welcomed; attempt++) {\n welcomed = await this.handshake(candidate);\n }\n\n this.role = welcomed ? \"forwarder\" : \"sender\";\n this.upstream = welcomed ? candidate : null;\n if (!welcomed) {\n // OpenFin link remains open for control messages.\n if (candidate !== this.openFinLink) {\n candidate.close();\n }\n this.diagnostics.report(\n \"bus.handshake_timeout\",\n `No owner answered after ${String(attempts)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,\n { via: candidate.kind, crossOrigin: this.isCrossOriginFrame() },\n );\n }\n this.diagnostics.report(\"bus.role_resolved\", `The bus role is ${this.role}.`, {\n role: this.role,\n via: welcomed ? candidate.kind : \"none\",\n });\n\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n /**\n * Forwards records to the upstream owner if configured.\n * @param records Batch of log records to send.\n */\n sendRecords(records: LogRecord[]): void {\n this.upstream?.post({ t: \"records\", from: this.contextId, records });\n }\n\n /**\n * Synchronously processes direct messages from same-origin child contexts.\n * @param message Received bus message.\n * @param reply Direct response callback.\n */\n acceptDirect(message: BusMessage, reply: Receive): void {\n if (message.from === this.contextId) {\n return;\n }\n const source: MessageSource = { link: \"direct\", origin: \"same-origin\" };\n\n if (message.t === \"hello\") {\n if (this.canOwn(\"direct\")) {\n reply(\n {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n },\n source,\n );\n }\n return;\n }\n if (message.t === \"journey?\") {\n const current = this.handlers.onJourneyRequest();\n if (current && this.journeyLink(\"direct\")) {\n reply({ t: \"journey\", from: this.contextId, to: message.from, journey: current }, source);\n }\n return;\n }\n // A direct link has no channel from the parent to the child. The parent answers here.\n if (message.t === \"sampling?\") {\n reply(this.rulesAnswer(message.from), source);\n return;\n }\n this.receive(message, source);\n }\n\n /**\n * Connects a worker instance to the bus control plane.\n * @param worker Worker instance.\n */\n attachWorker(worker: WorkerLike): void {\n this.links.push(createWorkerLink(worker, this.receive, this.diagnostics));\n }\n\n /**\n * Sends journey state changes over each link of the journey scope.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.postJourney({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.ownerId = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Sends a journey message over each link of the journey scope. */\n private postJourney(message: BusMessage): void {\n for (const link of this.allLinks()) {\n if (this.journeyLink(link.kind)) {\n link.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case \"hello\":\n if (this.canOwn(source.link)) {\n this.postOver(source.link, {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n });\n }\n break;\n\n case \"welcome\":\n if (message.to !== this.contextId) {\n break;\n }\n if (this.awaitingWelcome?.link === source.link) {\n // Keep the owner. Only it can set the journey of this context on a shared link.\n this.ownerId = message.from;\n this.awaitingWelcome.settle(true);\n }\n break;\n\n case \"records\":\n if (this.role === \"sender\") {\n this.handlers.onRecords(message.records);\n } else if (this.upstream && this.canRelay(source.link)) {\n // Relays records upstream in nested frame chains.\n this.upstream.post(message);\n }\n break;\n\n case \"journey\":\n if (this.acceptsJourney(message, source)) {\n this.applyJourney(message.journey);\n }\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n // Address the answer. On a shared link, each other context ignores it.\n if (current && this.journeyLink(source.link)) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n to: message.from,\n journey: current,\n });\n }\n break;\n }\n\n case \"sampling?\":\n // A forwarder answers only its own children. A sibling on its upstream link asks too.\n // A sibling answer on OpenFin gives N squared messages, and a stale copy can win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.postOver(source.link, this.rulesAnswer(message.from));\n }\n break;\n\n case \"sampling\":\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case \"tab\":\n // A collision applies only to two different contexts on the broadcast channel.\n // The id comparison selects one context of the pair.\n // Without it, both contexts report the conflict and rename.\n if (\n source.link === \"broadcast\" &&\n message.tabId === this.tabId &&\n this.contextId > message.from\n ) {\n this.handlers.onTabConflict();\n }\n break;\n }\n };\n\n /**\n * Tells if records from a link can go upstream. Records that go back on\n * their arrival link return to their sender. A direct link is an exception.\n * Each direct link is one call into one parent. Thus two direct links in a\n * chain are different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Returns true if this context can be the owner of the given link type. */\n private canOwn(link: LinkKind): boolean {\n if (this.role !== \"sender\") {\n return false;\n }\n if (link === \"openfin\") {\n return this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Finds if this context is the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = (globalThis as { fin?: { me?: OpenFinMe } }).fin?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests if a cross-origin boundary blocks access to the parent window. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. Lint rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (this.platform.isTopLevelDocument) {\n push(createChildrenLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics));\n push(createBroadcastLink(BUS_CHANNEL_NAME, this.receive, this.diagnostics));\n }\n if (this.platform.platform === \"openfin\" || this.platform.platform === \"openfin_web\") {\n push(this.ensureOpenFinLink());\n }\n }\n\n /** Returns the singleton OpenFin InterApplicationBus link. */\n private ensureOpenFinLink(): Link | null {\n this.openFinLink ??= createOpenFinLink(\n BUS_CHANNEL_NAME,\n this.platform.openfinUuid,\n this.receive,\n this.diagnostics,\n );\n return this.openFinLink;\n }\n\n /**\n * Executes a hello/welcome handshake over candidate link.\n * @param candidate Upstream link candidate.\n * @returns True if welcome response arrived before timeout.\n */\n private handshake(candidate: Link): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (result: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n this.awaitingWelcome = null;\n clearTimeout(timer);\n resolve(result);\n };\n\n this.awaitingWelcome = { link: candidate.kind, settle: finish };\n // finish reads timer, which the code declares after finish. This order is safe.\n // finish can run only after the post below. The timer exists at that time.\n const timer = setTimeout(() => {\n finish(false);\n }, this.handshakeOptions.timeoutMs);\n unrefTimer(timer);\n candidate.post({ t: \"hello\", from: this.contextId, tabId: this.tabId });\n });\n }\n\n /** Broadcasts tab claim and queries existing journey state. */\n private announce(): void {\n this.postOver(\"broadcast\", {\n t: \"tab\",\n from: this.contextId,\n tabId: this.tabId,\n });\n this.postJourney({ t: \"journey?\", from: this.contextId });\n this.pollRules();\n }\n\n /**\n * Resolves the journey scope. \"auto\" gives \"origin\" in OpenFin and \"tab\" in a browser.\n * @returns The scope in force.\n */\n private journeyScope(): ResolvedScope {\n const { scope } = this.config.journey;\n if (scope !== \"auto\") {\n return scope;\n }\n\n const { platform } = this.platform;\n return platform === \"openfin\" || platform === \"openfin_web\" ? \"origin\" : \"tab\";\n }\n\n /**\n * Tests if a link carries journey messages in the scope in force.\n * Only \"origin\" uses the broadcast link. That link reaches each tab of the origin.\n * @param link Link kind.\n * @returns True if the link carries journey messages.\n */\n private journeyLink(link: LinkKind): boolean {\n const scope = this.journeyScope();\n if (scope === \"context\") {\n return false;\n }\n\n return scope === \"origin\" || link !== \"broadcast\";\n }\n\n /**\n * Tests if this context adopts a journey message.\n * @param message Journey message.\n * @param source Link and origin of the message.\n * @returns True for a message on a journey link, to this context, from an accepted sender.\n * In \"tab\" scope, only the owner of a forwarder is an accepted sender.\n */\n private acceptsJourney(\n message: Extract<BusMessage, { t: \"journey\" }>,\n source: MessageSource,\n ): boolean {\n if (!this.journeyLink(source.link)) {\n return false;\n }\n\n if (message.to !== undefined && message.to !== this.contextId) {\n return false;\n }\n\n return this.journeyScope() === \"origin\" || this.fromOwner(message.from, source.link);\n }\n\n /**\n * Tests if a message comes from the upstream owner of this forwarder.\n * @param from Context id of the sender.\n * @param link Link kind of the message.\n * @returns True for the upstream link and, after a handshake, the owner that answered it.\n */\n private fromOwner(from: string, link: LinkKind): boolean {\n if (this.role !== \"forwarder\" || link !== this.upstream?.kind) {\n return false;\n }\n\n return this.ownerId === null || from === this.ownerId;\n }\n\n /**\n * Parses a journey payload from another realm and gives it to the runtime.\n * @param payload Journey, or null when the journey ended.\n */\n private applyJourney(payload: unknown): void {\n if (payload === null) {\n this.handlers.onJourney(null);\n return;\n }\n\n const journey = parseJourney(payload);\n if (journey === null) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n \"The bus dropped a journey message. Its payload is not a journey.\",\n { type: \"journey\" },\n );\n return;\n }\n\n this.handlers.onJourney(journey);\n }\n\n /**\n * Builds the answer to a sampling question. Null rules end the copy of the forwarder.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: \"sampling\", from: this.contextId, to, rules };\n }\n\n /**\n * Tests if this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link is not trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. It must not lower minLevel and read the records.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== location.origin &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Applies the rules of an answer. It ignores rules that are not valid.\n * @param raw Rules of the answer, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then at each poll interval.\n * A direct link cannot push the rules to a child. A poll works on each link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config at each poll. A later configure() can turn remote sampling on or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: \"sampling?\", from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":"8JAkFA,SAAgBW,EAAS,EAAkC,CACzD,MAAO,CAAE,EAAGX,EAAAA,EAAc,EAAGY,CAAQ,CACvC,CAUA,SAAgBC,EAAO,EAAkC,CACvD,GAAI,OAAOC,GAAS,WAAYA,EAC9B,OAAO,KAIT,IAAMC,EAAUD,EAChB,GAAIC,EAAQ,IAAA,sBAAsB,OAAOA,EAAQ,GAAM,UAAYA,EAAQ,IAAM,KAC/E,OAAO,KAGT,IAAMH,EAAUG,EAAQ,EAKxB,OAJI,OAAOH,EAAQ,GAAM,SAIlBA,EAHE,IAIX,CCtCA,IAAMI,EAAc,OAAO,IAAIf,EAAAA,EAAkB,EAG3CgB,EAAgB,OActB,SAASC,EAAc,EAAgB,EAAsB,CAK3D,OAJIC,IAAWF,EACN,mBAAmBG,EAAK,+KAG1B,mBAAmBA,EAAK,QAAQD,EAAO,wDAChD,CAMA,SAASE,GAA8B,CACrC,IAAMC,EAAa,SAAmC,gBACtD,GAAIA,GAAaA,EAAU,OAAS,EAClC,OAAOA,EAAU,KAAK,CAAC,EAKzB,IAAMC,EAAW,SAAS,SAC1B,GAAIA,IAAa,GACf,OAAO,KAGT,GAAI,CACF,OAAO,IAAI,IAAIA,CAAQ,CAAC,CAAC,MAC3B,MAAQ,CACN,OAAO,IACT,CACF,CAQA,SAAgBC,EAAiB,EAAkB,EAAuC,CACxF,GAAI,OAAO,OAAW,KAAe,OAAO,SAAW,OACrD,OAAO,KAGT,IAAIC,EACJ,GAAI,CAEF,EADqB,OAAO,OACRT,EACtB,MAAQ,CAEN,OAAO,IACT,CACA,GAAI,OAAOS,GAAM,WAAc,WAC7B,OAAO,KAGT,IAAMC,EAASD,EACXE,EAAO,GAEX,MAAO,CACL,KAAM,SACN,KAAK,EAAS,CACPA,GAKLC,E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