@utk09/ui-observability 0.6.0 → 0.8.0

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 (123) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +189 -25
  3. package/dist/bus/bus.d.ts +30 -0
  4. package/dist/bus-CUXRY0JR.cjs +2 -0
  5. package/dist/bus-CUXRY0JR.cjs.map +1 -0
  6. package/dist/{bus-BTMuVkDk.js → bus-DPDrlUBY.js} +96 -50
  7. package/dist/bus-DPDrlUBY.js.map +1 -0
  8. package/dist/capture/console.d.ts +37 -0
  9. package/dist/capture/errors.d.ts +2 -4
  10. package/dist/capture/long-frames.d.ts +31 -0
  11. package/dist/capture/storm.d.ts +17 -0
  12. package/dist/capture/types.d.ts +2 -0
  13. package/dist/console-CNljJict.js +81 -0
  14. package/dist/console-CNljJict.js.map +1 -0
  15. package/dist/console-PKzc-FmR.cjs +2 -0
  16. package/dist/console-PKzc-FmR.cjs.map +1 -0
  17. package/dist/constants-B28fDv2F.cjs +2 -0
  18. package/dist/constants-B28fDv2F.cjs.map +1 -0
  19. package/dist/constants-Bu49bm39.js +93 -0
  20. package/dist/constants-Bu49bm39.js.map +1 -0
  21. package/dist/constants.d.ts +35 -5
  22. package/dist/core/breadcrumbs.d.ts +1 -1
  23. package/dist/core/pipeline.d.ts +2 -2
  24. package/dist/core/record.d.ts +3 -0
  25. package/dist/core/remote-rules.d.ts +17 -0
  26. package/dist/core/remote-sampling.d.ts +65 -0
  27. package/dist/core/runtime.d.ts +10 -4
  28. package/dist/core/sampling.d.ts +5 -2
  29. package/dist/core/sender.d.ts +3 -0
  30. package/dist/errors-C78ZTjet.cjs +3 -0
  31. package/dist/errors-C78ZTjet.cjs.map +1 -0
  32. package/dist/{errors-Dwm2SzBa.js → errors-Dnc-X4Ec.js} +19 -20
  33. package/dist/errors-Dnc-X4Ec.js.map +1 -0
  34. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  35. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  36. package/dist/global-scope-dp2jADRl.js +19 -0
  37. package/dist/global-scope-dp2jADRl.js.map +1 -0
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +307 -241
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
  44. package/dist/{indexeddb-storage-B5dwq4hW.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
  45. package/dist/{indexeddb-storage-DjY4Ml6t.js → indexeddb-storage-uD4oaRMc.js} +10 -10
  46. package/dist/{indexeddb-storage-DjY4Ml6t.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
  47. package/dist/{interactions-DVom6eYn.cjs → interactions-CsE2y_fQ.cjs} +2 -2
  48. package/dist/{interactions-DVom6eYn.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
  49. package/dist/{interactions-DZmLu7l2.js → interactions-igKTAJvj.js} +2 -2
  50. package/dist/{interactions-DZmLu7l2.js.map → interactions-igKTAJvj.js.map} +1 -1
  51. package/dist/library-request-Br_T09Bn.cjs +2 -0
  52. package/dist/library-request-Br_T09Bn.cjs.map +1 -0
  53. package/dist/library-request-Dt0fXhcn.js +14 -0
  54. package/dist/library-request-Dt0fXhcn.js.map +1 -0
  55. package/dist/long-frames-6pnjWSSR.js +65 -0
  56. package/dist/long-frames-6pnjWSSR.js.map +1 -0
  57. package/dist/long-frames-DahhqM6u.cjs +2 -0
  58. package/dist/long-frames-DahhqM6u.cjs.map +1 -0
  59. package/dist/models/bus.d.ts +16 -0
  60. package/dist/models/config.d.ts +120 -6
  61. package/dist/network-CZ0aFUsy.cjs +2 -0
  62. package/dist/network-CZ0aFUsy.cjs.map +1 -0
  63. package/dist/{network-C4d2uw2Z.js → network-aSNbwpue.js} +16 -15
  64. package/dist/network-aSNbwpue.js.map +1 -0
  65. package/dist/{platform-CY8S3hUs.js → platform-BwbMRwHm.js} +7 -7
  66. package/dist/{platform-CY8S3hUs.js.map → platform-BwbMRwHm.js.map} +1 -1
  67. package/dist/{platform-CXio0W2n.cjs → platform-D_XkVIF6.cjs} +2 -2
  68. package/dist/{platform-CXio0W2n.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
  69. package/dist/remote-rules-5UA23alm.js +86 -0
  70. package/dist/remote-rules-5UA23alm.js.map +1 -0
  71. package/dist/remote-rules-rJJZKVG8.cjs +2 -0
  72. package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
  73. package/dist/sampling-E4x92Nn2.cjs +2 -0
  74. package/dist/sampling-E4x92Nn2.cjs.map +1 -0
  75. package/dist/sampling-J1eahbfT.js +160 -0
  76. package/dist/sampling-J1eahbfT.js.map +1 -0
  77. package/dist/sanitize-BMhh8ghJ.cjs +2 -0
  78. package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
  79. package/dist/sanitize-UJ-4Lb0n.js +114 -0
  80. package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
  81. package/dist/sender-B6ufz26f.cjs +3 -0
  82. package/dist/sender-B6ufz26f.cjs.map +1 -0
  83. package/dist/{sender-dpvR_bHM.js → sender-G6v4Uqi4.js} +304 -219
  84. package/dist/sender-G6v4Uqi4.js.map +1 -0
  85. package/dist/storm-BtzgLOCX.cjs +2 -0
  86. package/dist/storm-BtzgLOCX.cjs.map +1 -0
  87. package/dist/storm-DJkEZP_8.js +10 -0
  88. package/dist/storm-DJkEZP_8.js.map +1 -0
  89. package/dist/transport/custom-transport.d.ts +20 -0
  90. package/dist/transport/errors.d.ts +2 -1
  91. package/dist/transport/exit-flush.d.ts +15 -0
  92. package/dist/transport/http-transport.d.ts +2 -24
  93. package/dist/transport/memory-transport.d.ts +30 -0
  94. package/dist/transport/retry-engine.d.ts +2 -2
  95. package/dist/transport/serializers/select.d.ts +12 -1
  96. package/dist/transport/status-transport.d.ts +72 -0
  97. package/dist/utils/console.d.ts +7 -6
  98. package/dist/utils/deadline.d.ts +7 -0
  99. package/dist/utils/global-scope.d.ts +20 -0
  100. package/dist/utils/library-console.d.ts +11 -0
  101. package/dist/utils/library-request.d.ts +12 -0
  102. package/package.json +4 -2
  103. package/dist/bus-BTMuVkDk.js.map +0 -1
  104. package/dist/bus-ChIXDAWD.cjs +0 -2
  105. package/dist/bus-ChIXDAWD.cjs.map +0 -1
  106. package/dist/constants-0-YchbAL.js +0 -75
  107. package/dist/constants-0-YchbAL.js.map +0 -1
  108. package/dist/constants-TUFcy95w.cjs +0 -2
  109. package/dist/constants-TUFcy95w.cjs.map +0 -1
  110. package/dist/errors-DRXBRqvm.cjs +0 -3
  111. package/dist/errors-DRXBRqvm.cjs.map +0 -1
  112. package/dist/errors-Dwm2SzBa.js.map +0 -1
  113. package/dist/indexeddb-storage-B5dwq4hW.cjs +0 -2
  114. package/dist/network-C4d2uw2Z.js.map +0 -1
  115. package/dist/network-CuqWadNn.cjs +0 -2
  116. package/dist/network-CuqWadNn.cjs.map +0 -1
  117. package/dist/sampling-CEthcmEX.cjs +0 -2
  118. package/dist/sampling-CEthcmEX.cjs.map +0 -1
  119. package/dist/sampling-CJsI_24L.js +0 -251
  120. package/dist/sampling-CJsI_24L.js.map +0 -1
  121. package/dist/sender-ByFAkXVd.cjs +0 -3
  122. package/dist/sender-ByFAkXVd.cjs.map +0 -1
  123. package/dist/sender-dpvR_bHM.js.map +0 -1
@@ -0,0 +1,72 @@
1
+ import type { Diagnostics } from "../core/diagnostics";
2
+ import type { LogBatch } from "../models/batch";
3
+ import type { ResolvedConfig } from "../models/config";
4
+ import type { SerializedBatch } from "../models/serializer";
5
+ import { TransportError } from "./errors";
6
+ /** The two operations that the pipeline and the retry engine use. */
7
+ export interface BatchTransport {
8
+ /**
9
+ * Sends one batch.
10
+ * @param batch Batch to send.
11
+ * @throws TransportError when the batch is not accepted.
12
+ */
13
+ send(batch: LogBatch): Promise<void>;
14
+ /**
15
+ * Returns the remaining throttle delay.
16
+ * @returns Milliseconds until the throttle ends, or 0.
17
+ */
18
+ throttledForMs(): number;
19
+ }
20
+ /** Hints that come with a rejected batch. */
21
+ export interface RejectHints {
22
+ /** Delay that the server asks for, in milliseconds. */
23
+ retryAfterMs?: number;
24
+ /** Largest payload that the server accepts, from a 413 answer. */
25
+ maxBytes?: number;
26
+ /** Extra advice for a 401 or a 403 answer. */
27
+ advice?: string;
28
+ }
29
+ /** Base class of the HTTP transport and the custom transport. */
30
+ export declare abstract class StatusTransport implements BatchTransport {
31
+ protected readonly config: ResolvedConfig;
32
+ protected readonly diagnostics: Diagnostics;
33
+ private readonly onSampling;
34
+ /** Epoch time in milliseconds when the server throttle ends. */
35
+ private throttledUntil;
36
+ /**
37
+ * @param config Active configuration instance.
38
+ * @param diagnostics Diagnostics reporter.
39
+ * @param onSampling Receives the sampling rules of an accepted batch, before validation.
40
+ */
41
+ constructor(config: ResolvedConfig, diagnostics: Diagnostics, onSampling?: (raw: unknown) => void);
42
+ /**
43
+ * Sends one batch.
44
+ * @param batch Batch to send.
45
+ * @throws TransportError when the batch is not accepted.
46
+ */
47
+ abstract send(batch: LogBatch): Promise<void>;
48
+ /**
49
+ * Returns the remaining throttle delay in milliseconds.
50
+ * @returns Milliseconds remaining in throttle window, or 0 if unthrottled.
51
+ */
52
+ throttledForMs(): number;
53
+ /**
54
+ * Serializes a batch with the configured serializer. It reports a serializer that throws.
55
+ * @param batch Batch to serialize.
56
+ * @returns The serialized batch, or undefined if the serializer threw.
57
+ */
58
+ protected serialize(batch: LogBatch): SerializedBatch | undefined;
59
+ /**
60
+ * Records an accepted batch. It ends a server throttle.
61
+ * @param sampling Sampling rules of the answer, as text or as an object.
62
+ */
63
+ protected accept(sampling: unknown): void;
64
+ /**
65
+ * Converts a status code that is not 2xx into a classified TransportError.
66
+ * @param status Status code of the answer.
67
+ * @param batchId Identifier of the rejected batch.
68
+ * @param hints Delay, size limit and advice that come with the answer.
69
+ * @returns Classified TransportError instance.
70
+ */
71
+ protected reject(status: number, batchId: string, hints: RejectHints): TransportError;
72
+ }
@@ -1,19 +1,20 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
+ import type { ResolvedConsole } from "../models/config";
2
3
  import type { LogLevel } from "../models/log-record";
3
4
  /** Mirrors log records directly to browser or Node console methods based on severity. */
4
5
  export declare class ConsoleSink {
5
- private minLevel;
6
+ private settings;
6
7
  private diagnostics;
7
8
  /**
8
- * @param minLevel Minimum log level required to emit, or null to mirror nothing.
9
+ * @param settings Console level and styles. A null level prints nothing.
9
10
  * @param diagnostics Diagnostics reporter.
10
11
  */
11
- constructor(minLevel: LogLevel | null, diagnostics: Diagnostics);
12
+ constructor(settings: ResolvedConsole, diagnostics: Diagnostics);
12
13
  /**
13
- * Updates the console mirroring threshold.
14
- * @param minLevel Minimum log level required to emit, or null to mirror nothing.
14
+ * Replaces the console level and styles.
15
+ * @param settings Console level and styles. A null level prints nothing.
15
16
  */
16
- update(minLevel: LogLevel | null): void;
17
+ update(settings: ResolvedConsole): void;
17
18
  /**
18
19
  * Tests whether a level clears the console threshold.
19
20
  * @param level Severity level of the record.
@@ -1,3 +1,10 @@
1
+ /** Error of a promise that did not settle before its deadline. */
2
+ export declare class DeadlineError extends Error {
3
+ /**
4
+ * @param ms Deadline in milliseconds.
5
+ */
6
+ constructor(ms: number);
7
+ }
1
8
  /**
2
9
  * Rejects when a promise does not settle within a deadline.
3
10
  * @param work Promise to bound.
@@ -0,0 +1,20 @@
1
+ /** Scope that a function runs inside. */
2
+ export interface GlobalScope {
3
+ /**
4
+ * Runs a function inside the scope. The scope covers only the synchronous part of the function.
5
+ * @param fn Function to run.
6
+ * @returns The return value of the function.
7
+ */
8
+ run<T>(fn: () => T): T;
9
+ /**
10
+ * Tests whether a scope is open.
11
+ * @returns True while a function runs inside the scope.
12
+ */
13
+ open(): boolean;
14
+ }
15
+ /**
16
+ * Makes a scope whose count is on a global symbol.
17
+ * @param key Key of the global symbol.
18
+ * @returns The scope.
19
+ */
20
+ export declare function globalScope(key: string): GlobalScope;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Runs a function inside the library console scope.
3
+ * @param fn Function that writes to the console.
4
+ * @returns The return value of the function.
5
+ */
6
+ export declare function runAsLibraryConsole<T>(fn: () => T): T;
7
+ /**
8
+ * Tests whether a library console scope is open.
9
+ * @returns True while the library writes to the console.
10
+ */
11
+ export declare function isLibraryConsole(): boolean;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Runs a function inside the library request scope. The scope covers only the synchronous part
3
+ * of the function. A request that starts after an await is outside the scope.
4
+ * @param fn Function that starts the request.
5
+ * @returns The return value of the function.
6
+ */
7
+ export declare function runAsLibraryRequest<T>(fn: () => T): T;
8
+ /**
9
+ * Tests whether a library request scope is open.
10
+ * @returns True while the library starts a request.
11
+ */
12
+ export declare function isLibraryRequest(): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@utk09/ui-observability",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "UI observability and logging for browser, OpenFin and webview applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -75,7 +75,9 @@
75
75
  "typecheck": "tsc --noEmit",
76
76
  "check:version": "node tools/check-version-sync.mjs",
77
77
  "check:peers": "node tools/check-peer-imports.mjs",
78
- "verify": "npm run format:check && npm run check:version && npm run typecheck && npm run lint && npm run build && npm run check:peers && npm run test:coverage",
78
+ "check:size": "node tools/check-size.mjs",
79
+ "check:dev": "node tools/check-dev-server.mjs",
80
+ "verify": "npm run format:check && npm run check:version && npm run typecheck && npm run lint && npm run build && npm run check:peers && npm run check:size && npm run check:dev && npm run test:coverage",
79
81
  "prepublishOnly": "npm run verify"
80
82
  },
81
83
  "peerDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"bus-BTMuVkDk.js","names":["RUNTIME_GLOBAL_KEY","BUS_PROTOCOL","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","unrefTimer","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","createDirectLink","host","target","open","diagnostics","receive","createParentLink","onMessage","event","createChildrenLink","trusted","trustedOrigins","sources","source","origin","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"],"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 { Journey } from \"../core/journey\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role indicating whether this context sends records directly or forwards 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 /** Broadcast update announcing a new or ended journey state. */\n | { t: \"journey\"; from: string; journey: Journey | null }\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\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 { 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/**\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 the parent window.\n * @param receive Callback for incoming parent messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to parent window, or null if running in top-level window.\n */\nexport function createParentLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n // This context trusts the parent because it selected the parent as its upstream.\n if (message && event.source === window.parent) {\n receive(message, { link: \"parent\", origin: event.origin });\n }\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 // An outbound \"*\" target is safe. The payload holds only this context's records.\n // The parent already gets these records by another path.\n // For inbound trust, see createChildrenLink.\n window.parent.postMessage(envelope(message), \"*\");\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 const trusted = new Set([window.location.origin, ...trustedOrigins]);\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(\n \"bus.untrusted_origin\",\n `The bus ignored a message from ${event.origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin: event.origin, type: message.t },\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} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { Journey } from \"../core/journey\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { 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}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\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 /** Indicates whether this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Indicates whether role resolution has completed. */\n private resolved = false;\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 whether role resolution has completed. */\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) {\n reply({ t: \"journey\", from: this.contextId, journey: current }, source);\n }\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 * Broadcasts journey state changes to all connected links.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.post({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = 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 /** Broadcasts a message across all open links. */\n private post(message: BusMessage): void {\n for (const link of this.allLinks()) {\n link.post(message);\n }\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 /** 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 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 this.handlers.onJourney(message.journey);\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n journey: current,\n });\n }\n break;\n }\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 whether 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 whether this context can accept ownership over 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 /** Resolves whether this context represents 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 whether the parent window is inaccessible due to cross-origin boundaries. */\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.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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AAK,kBAAkB,MACvB,aAAaE,CAAK,GAClBC,EAAQC,CAAM;GAChB;GAEA,KAAK,kBAAkB;IAAE,MAAMd,EAAU;IAAM,QAAQW;GAAO;GAG9D,IAAMC,IAAQ,iBAAiB;IAC7B,EAAO,EAAK;GACd,GAAG,KAAK,iBAAiB,SAAS;GAElC,AADA5D,EAAW4D,CAAK,GAChBZ,EAAU,KAAK;IAAE,GAAG;IAAS,MAAM,KAAK;IAAW,OAAO,KAAK;GAAM,CAAC;EACxE,CAAC;CACH;CAGA,WAAyB;EAMvB,AALA,KAAK,SAAS,aAAa;GACzB,GAAG;GACH,MAAM,KAAK;GACX,OAAO,KAAK;EACd,CAAC,GACD,KAAK,KAAK;GAAE,GAAG;GAAY,MAAM,KAAK;EAAU,CAAC;CACnD;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-TUFcy95w.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(t){return{p:e.S,m:t}}function r(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 i=Symbol.for(e.Rt);function a(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[i]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,a=!0;return{kind:`direct`,post(n){a&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e)})},close(){a=!1}}}function o(e,t){if(typeof window>`u`||window.parent===window)return null;let i=t=>{let n=r(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,i),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(n(e),`*`)})},close(){removeEventListener(`message`,i)}}}function s(e,t,i){if(typeof window>`u`)return null;let a=new Set([window.location.origin,...t]),o=new Map,s=t=>{let n=r(t.data);n&&(a.has(t.origin)?(t.source&&o.set(t.source,t.origin),e(n,{link:`children`,origin:t.origin})):i.report(`bus.untrusted_origin`,`The bus ignored a message from ${t.origin}. If you own this origin, add it to bus.trustedOrigins.`,{origin:t.origin,type:n.t}))};return addEventListener(`message`,s),{kind:`children`,post(e){for(let[t,r]of o){let a=t;a.closed?o.delete(t):i.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{a.postMessage(n(e),r)})}},close(){removeEventListener(`message`,s),o.clear()}}}function c(e,t,i){let a=globalThis.BroadcastChannel;if(a===void 0)return null;let o=i.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new a(e));return o?(o.onmessage=e=>{let n=r(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){i.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{o.postMessage(n(e))})},close(){i.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{o.close()})}}):null}function l(e,t,i,a){let o=globalThis.fin?.InterApplicationBus;if(!o)return null;if(!t)return a.report(`openfin.unavailable`,`OpenFin gives no application uuid. The InterApplicationBus link stays closed.`),null;let s=`${e}.${t}`;return a.guardAsync(`bus.send_failed`,`The InterApplicationBus.subscribe call failed.`,()=>o.subscribe({uuid:t},s,e=>{let t=r(e);t&&i(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){a.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>o.publish(s,n(e)))},close(){}}}function u(e,t){let i=globalThis,a=i.postMessage;return i.WorkerGlobalScope===void 0||!a?null:(i.addEventListener?.(`message`,t=>{let n=r(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.`,()=>{a(n(e))})},close(){}})}function d(e,t,i){let a=e=>{let n=r(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,a),e.start?.(),{kind:`worker`,post(t){i.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(n(t))})},close(){e.removeEventListener(`message`,a)}}}var f={timeoutMs:e.x,maxAttempts:3},p=[`children`,`direct`,`worker`],m=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=f){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=a(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 e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n)}else this.receive(e,n)}attachWorker(e){this.links.push(d(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}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.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.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});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:p.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?u(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:o(this.receive,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(s(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(c(e.b,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=l(e.b,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.t(a),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId})}};exports.Bus=m;
2
- //# sourceMappingURL=bus-ChIXDAWD.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bus-ChIXDAWD.cjs","names":["BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_HANDSHAKE_TIMEOUT_MS","BUS_CHANNEL_NAME","require_constants","require_unref","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","createDirectLink","host","target","open","diagnostics","receive","createParentLink","onMessage","event","createChildrenLink","trusted","trustedOrigins","sources","source","origin","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"],"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 { Journey } from \"../core/journey\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role indicating whether this context sends records directly or forwards 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 /** Broadcast update announcing a new or ended journey state. */\n | { t: \"journey\"; from: string; journey: Journey | null }\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\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 { 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/**\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 the parent window.\n * @param receive Callback for incoming parent messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to parent window, or null if running in top-level window.\n */\nexport function createParentLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n // This context trusts the parent because it selected the parent as its upstream.\n if (message && event.source === window.parent) {\n receive(message, { link: \"parent\", origin: event.origin });\n }\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 // An outbound \"*\" target is safe. The payload holds only this context's records.\n // The parent already gets these records by another path.\n // For inbound trust, see createChildrenLink.\n window.parent.postMessage(envelope(message), \"*\");\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 const trusted = new Set([window.location.origin, ...trustedOrigins]);\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(\n \"bus.untrusted_origin\",\n `The bus ignored a message from ${event.origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin: event.origin, type: message.t },\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} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { Journey } from \"../core/journey\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { 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}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\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 /** Indicates whether this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Indicates whether role resolution has completed. */\n private resolved = false;\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 whether role resolution has completed. */\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) {\n reply({ t: \"journey\", from: this.contextId, journey: current }, source);\n }\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 * Broadcasts journey state changes to all connected links.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.post({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = 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 /** Broadcasts a message across all open links. */\n private post(message: BusMessage): void {\n for (const link of this.allLinks()) {\n link.post(message);\n }\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 /** 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 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 this.handlers.onJourney(message.journey);\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n journey: current,\n });\n }\n break;\n }\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 whether 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 whether this context can accept ownership over 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 /** Resolves whether this context represents 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 whether the parent window is inaccessible due to cross-origin boundaries. */\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.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.post({ t: \"journey?\", from: this.contextId });\n }\n}\n"],"mappings":"8EAwEA,SAAgBM,EAAS,EAAkC,CACzD,MAAO,CAAE,EAAGN,EAAAA,EAAc,EAAGO,CAAQ,CACvC,CAUA,SAAgBC,EAAO,EAAkC,CACvD,GAAI,OAAOC,GAAS,WAAYA,EAC9B,OAAO,KAIT,IAAMC,EAAUD,EAChB,GAAI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CAGA,UAAyB,CACvB,KAAK,SAAS,YAAa,CACzB,EAAG,MACH,KAAM,KAAK,UACX,MAAO,KAAK,KACd,CAAC,EACD,KAAK,KAAK,CAAE,EAAG,WAAY,KAAM,KAAK,SAAU,CAAC,CACnD,CACF"}
@@ -1,75 +0,0 @@
1
- //#region src/constants.ts
2
- var ee = "[ui-observability]", te = 1e3, e = "ui-observability.session", t = "ui-observability.tab", n = 18e5, r = 6e4, i = /OpenFin/i, a = /\bwv\b/, o = /\b(iPhone|iPad|iPod)\b/, s = /\bMacintosh\b/, c = /\bMobile\b/, l = "AppleWebKit", u = "Safari/", d = 55296, f = 56319, p = 2048, m = {
3
- TRACE: 1,
4
- DEBUG: 5,
5
- INFO: 9,
6
- WARN: 13,
7
- ERROR: 17,
8
- FATAL: 21
9
- }, h = m, g = "log.type", _ = "log.seq", v = "app.namespace", y = "page.url", b = "url.full", x = "journey.id", S = "journey.name", C = "journey.parent_id", w = "uiobs.sanitize_failed", T = "uiobs.attributes_dropped", E = "uiobs.attributes_bytes", D = "service.name", O = "service.version", k = "deployment.environment", A = "telemetry.sdk.name", j = "telemetry.sdk.version", M = "telemetry.sdk.language", N = "host.platform", P = "session.id", F = "tab.id", I = "context.id", L = "browser.user_agent", R = "openfin.uuid", z = "openfin.name", B = "@utk09/ui-observability", V = "0.6.0", H = "webjs", U = "otlp", W = { WARN: "warning" }, G = "application/json", K = "application/x-ndjson", q = 1000000n, J = /^\d+$/, Y = "Content-Type", X = "Content-Encoding", Z = "Retry-After", Q = "X-UiObs-Batch-Id", ne = "X-UiObs-Attempt", re = "gzip", ie = 1e3, ae = 6e4, oe = "text/plain;charset=UTF-8", se = "uiobs_batch_id", ce = "uiobs_exit", le = "ui-observability.batch.", ue = "ui-observability.emergency.", $ = "ui-observability.probe", de = "QuotaExceededError", fe = "batches", pe = "createdAt", me = "indexeddb", he = "localstorage", ge = "memory", _e = "none", ve = "ui-observability.drain", ye = "ui-observability.emergency", be = "ui-observability.journey", xe = 2e3, Se = "uiObsJourney", Ce = /\+/g, we = /\//g, Te = /=+$/, Ee = /-/g, De = /_/g, Oe = 3e5, ke = "traceparent", Ae = 2166136261, je = 16777619, Me = 4294967295, Ne = "metric", Pe = "ui-observability/1", Fe = "ui-observability.runtime", Ie = "ui-observability.stopped", Le = 1e4, Re = "color:#888", ze = 1e3, Be = 6e4, Ve = "uiobs.capture", He = "uiobs.storage", Ue = "count", We = "unknown-service", Ge = [
10
- "redact",
11
- "onDiagnostic",
12
- "headers",
13
- "serializer",
14
- "otelLoader"
15
- ], Ke = [
16
- "sampling",
17
- "bus",
18
- "capture"
19
- ], qe = {
20
- sampling: [],
21
- bus: [],
22
- capture: ["webVitalsLoader"]
23
- }, Je = {
24
- endpoint: "",
25
- serviceName: "",
26
- serviceVersion: "",
27
- environment: "",
28
- enabled: !0,
29
- minLevel: "INFO",
30
- compression: "gzip",
31
- credentials: "omit",
32
- storage: "auto",
33
- identity: "storage",
34
- sampling: {
35
- defaultRate: 1,
36
- rates: {},
37
- alwaysSampleTypes: ["action"]
38
- },
39
- bus: {
40
- mode: "auto",
41
- trustedOrigins: [],
42
- openFinRole: "auto"
43
- },
44
- capture: {
45
- errors: !0,
46
- rejections: !0,
47
- resourceErrors: !1,
48
- fetch: !1,
49
- xhr: !1,
50
- interactions: !1,
51
- navigation: !1,
52
- webVitals: !1,
53
- fullUrls: !1,
54
- ignoreUrls: [],
55
- propagateTraceHeaderTo: []
56
- },
57
- console: null
58
- }, Ye = "DEBUG", Xe = 2e3, Ze = 1e4, Qe = 15e3, $e = 1024, et = "UiObservability", tt = {
59
- maxBatches: 500,
60
- maxAgeMs: 864e5,
61
- maxAttempts: 5
62
- }, nt = 1e4, rt = 2e3, it = 6e4, at = 3e4, ot = 18e5, st = "__uiobs_journey", ct = "ui_observability_control", lt = 1500, ut = 5e3, dt = {
63
- maxBodyChars: 4096,
64
- maxAttributeChars: 8192,
65
- maxAttributeCount: 128,
66
- maxStackChars: 8192,
67
- maxDepth: 6,
68
- maxArrayLength: 100,
69
- maxNodes: 1e4,
70
- maxRecordBytes: 32768
71
- };
72
- //#endregion
73
- export { fe as $, _e as $t, oe as A, P as At, ut as B, u as Bt, Ve as C, I as Ct, Re as D, R as Dt, Ye as E, z as Et, ze as F, rt as Ft, ne as G, m as Gt, Ae as H, n as Ht, W as I, at as It, Y as J, tt as Jt, Q as K, et as Kt, ye as L, it as Lt, Ue as M, M as Mt, te as N, A as Nt, G as O, D as Ot, ve as P, j as Pt, pe as Q, ge as Qt, ue as R, Fe as Rt, Pe as S, L as St, Ke as T, N as Tt, je as U, e as Ut, Le as V, U as Vt, Be as W, r as Wt, f as X, me as Xt, Z as Y, He as Yt, d as Z, he as Zt, we as _, se as _t, x as a, ke as an, ee as at, ct as b, dt as bt, _ as c, Ge as cn, s as ct, w as d, p as dn, c as dt, $ as en, o as et, b as f, l as fn, J as ft, Ce as g, i as gt, Te as h, xe as ht, T as i, V as in, h as it, Je as j, F as jt, K as k, O as kt, g as l, qe as ln, Ze as lt, De as m, Se as mt, v as n, H as nn, be as nt, S as o, Oe as on, Xe as ot, Ee as p, q as pt, X as q, nt as qt, E as r, B as rn, st as rt, C as s, Me as sn, Ne as st, a as t, t as tn, ot as tt, y as u, We as un, ie as ut, le as v, ce as vt, $e as w, k as wt, lt as x, Qe as xt, ae as y, de as yt, re as z, Ie as zt };
74
-
75
- //# sourceMappingURL=constants-0-YchbAL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-0-YchbAL.js","names":["LIBRARY_LOG_PREFIX","DIAGNOSTIC_THROTTLE_MS","SESSION_ID_KEY","TAB_ID_KEY","SESSION_IDLE_MS","SESSION_TOUCH_MS","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","WEBKIT_UA_TOKEN","SAFARI_UA_TOKEN","HIGH_SURROGATE_MIN","HIGH_SURROGATE_MAX","UTF8_TWO_BYTE_CEILING","SEVERITY_NUMBER","LEVEL_ORDER","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_URL_FULL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","ATTR_SANITIZE_FAILED","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","TELEMETRY_SDK_LANGUAGE","SERIALIZER_NAME_OTLP","ECS_LEVEL_NAMES","CONTENT_TYPE_JSON","CONTENT_TYPE_NDJSON","NANOS_PER_MILLI","NANOS_PATTERN","HEADER_CONTENT_TYPE","HEADER_CONTENT_ENCODING","HEADER_RETRY_AFTER","HEADER_BATCH_ID","HEADER_ATTEMPT","ENCODING_GZIP","MILLIS_PER_SECOND","BEACON_LIMIT_BYTES","CONTENT_TYPE_TEXT_PLAIN","QUERY_PARAM_BATCH_ID","QUERY_PARAM_EXIT_REASON","BATCH_STORAGE_KEY_PREFIX","EMERGENCY_STORAGE_KEY_PREFIX","STORAGE_PROBE_KEY","QUOTA_EXCEEDED_ERROR","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","STORAGE_NAME_LOCAL","STORAGE_NAME_MEMORY","STORAGE_NAME_NONE","DRAIN_LOCK_NAME","EMERGENCY_LOCK_NAME","JOURNEY_STORAGE_KEY","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LOG_TYPE_METRIC","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","ERROR_STORM_WINDOW_MS","CONSOLE_PREFIX_STYLE","DURATION_PRECISION","GAP_REPORT_THROTTLE_MS","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DEFAULT_METRIC_UNIT","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","DEFAULT_CONFIG","CONSOLE_DEFAULT_LEVEL","LOG_FLUSH_INTERVAL_MS","METRIC_FLUSH_INTERVAL_MS","REQUEST_TIMEOUT_MS","COMPRESSION_THRESHOLD_BYTES","STORAGE_DB_NAME","STORAGE_LIMITS","STORAGE_DEADLINE_MS","RETRY_BASE_DELAY_MS","RETRY_MAX_DELAY_MS","RETRY_IDLE_DELAY_MS","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","ERROR_DEDUPE_MS","RECORD_LIMITS"],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// Defines all limits, thresholds, timing windows, storage keys, patterns, and\n// defaults that the library uses.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\nimport type { StorageLimits } from \"./models/storage\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/**\n * Throttle window for each diagnostic code, in milliseconds. It limits how often an error\n * loop calls the handler.\n */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Maps each log level to its OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names that records carry in the payload. The names\n// follow OpenTelemetry conventions. The `uiobs.` prefix marks the fields of this library.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number in its context. It starts at 1. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key. Network capture sets it. Do not reuse `ATTR_PAGE_URL`.\n * The page URL overwrites the request target under that key.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record when the library drops its attributes because they exceed the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. The code does not read it from package.json.\n * Change it by hand when you change the version in package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.6.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/**\n * ECS `log.level` names that differ from the lowercase severity text. ECS spells\n * the warning level in full. All other levels match in lowercase.\n * @see {@link SERIALIZER_NAME_ECS}\n */\nexport const ECS_LEVEL_NAMES: Partial<Record<LogLevel, string>> = { WARN: \"warning\" };\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. The transport can retry. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large. The transport must split the batch. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. It is CORS-safelisted and does not cause a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a stored batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch that exit flush stores. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store to evict on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/**\n * Native IndexedDB version. It starts at 11. Dexie, the previous adapter, opened the\n * same database at ten times its declared version. A version below 11 makes open()\n * fail with VersionError for an existing installation. Then no code can read the\n * batches in that database.\n */\nexport const INDEXEDDB_SCHEMA_VERSION = 11;\n\n/** IndexedDB object store that holds batches. Dexie set this name before the library removed it. */\nexport const INDEXEDDB_STORE_NAME = \"batches\";\n\n/** Index on the batch store that orders reads by creation time. */\nexport const INDEXEDDB_CREATED_AT_INDEX = \"createdAt\";\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. It rejects an oversized token. It does not\n * validate the token content.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * Time to wait for `fin.me.getOptions()`, in milliseconds. After this time, the\n * runtime continues without a seeded journey.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/**\n * W3C trace context header name\n * @see {@link TRACEPARENT_VERSION}\n */\nexport const TRACEPARENT_HEADER = \"traceparent\";\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants. The sampler uses them to change a sampling key into a\n// stable 0-1 fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. The bus drops an envelope with a different version. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n/** Global key of the runtime that shutdown() stopped. Calls go to it until the next configure(). */\nexport const RUNTIME_STOPPED_KEY = \"ui-observability.stopped\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/**\n * Max ERROR and FATAL records that the pipeline admits in each storm window.\n * It is a safety limit for a render loop. It does not shape normal traffic.\n * ERROR and FATAL records skip sampling. A direct logger.error call has no other limit.\n */\nexport const ERROR_CEILING_MAX_PER_WINDOW = 500;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\n \"redact\",\n \"onDiagnostic\",\n \"headers\",\n \"serializer\",\n \"otelLoader\",\n] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\"sampling\", \"bus\", \"capture\"] as const;\n\n/**\n * Section keys with no default, excluded from their section of `DEFAULT_CONFIG`.\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const UNDEFAULTED_SECTION_KEYS: Record<(typeof CONFIG_SECTIONS)[number], string[]> = {\n sampling: [],\n bus: [],\n capture: [\"webVitalsLoader\"],\n};\n\n/**\n * Default runtime config before the consumer calls `configure()`. It excludes `serializer`.\n * `resolveConfig` supplies that default to prevent a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n compression: \"gzip\",\n credentials: \"omit\",\n storage: \"auto\",\n identity: \"storage\",\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n bus: { mode: \"auto\", trustedOrigins: [], openFinRole: \"auto\" },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n fullUrls: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n },\n console: null,\n};\n\n/** Console mirroring level used when a consumer passes `console: true`. */\nexport const CONSOLE_DEFAULT_LEVEL: LogLevel = \"DEBUG\";\n\n// ----------------------------------\n// Batching\n// ----------------------------------\n\n/** Max time a partial log batch waits before the pipeline sends it, in milliseconds. */\nexport const LOG_FLUSH_INTERVAL_MS = 2000;\n\n/** Max records per log batch. At this count, the pipeline sends the batch early. */\nexport const LOG_BATCH_SIZE = 100;\n\n/**\n * Max time a partial metric batch waits before the pipeline sends it, in milliseconds.\n * Metric batches wait longer than log batches. Metrics have a higher volume, and no\n * caller waits for them.\n */\nexport const METRIC_FLUSH_INTERVAL_MS = 10_000;\n\n/** Max records per metric batch. At this count, the pipeline sends the batch early. */\nexport const METRIC_BATCH_SIZE = 500;\n\n/** Max concurrent ingest requests, across both streams. */\nexport const MAX_CONCURRENT_REQUESTS = 2;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Max time for one ingest request, in milliseconds. Then the transport aborts and retries it. */\nexport const REQUEST_TIMEOUT_MS = 15_000;\n\n/** Min payload size to compress, in bytes. */\nexport const COMPRESSION_THRESHOLD_BYTES = 1024;\n\n// ----------------------------------\n// Storage retention\n// ----------------------------------\n\n/** IndexedDB database name. */\nexport const STORAGE_DB_NAME = \"UiObservability\";\n\n/** Capacity and retention thresholds every storage adapter enforces. */\nexport const STORAGE_LIMITS: StorageLimits = {\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n};\n\n/**\n * Max time for one storage call, in milliseconds. Then the library treats the call as failed.\n * A call that does not settle keeps a dispatch slot or the drain flag.\n */\nexport const STORAGE_DEADLINE_MS = 10_000;\n\n// ----------------------------------\n// Retry backoff\n// ----------------------------------\n\n/** First backoff step, in milliseconds. Each attempt doubles it. */\nexport const RETRY_BASE_DELAY_MS = 2000;\n\n/** Backoff ceiling, in milliseconds. */\nexport const RETRY_MAX_DELAY_MS = 60_000;\n\n/** How often to check for stored work when nothing has failed recently, in milliseconds. */\nexport const RETRY_IDLE_DELAY_MS = 30_000;\n\n// ----------------------------------\n// Journey lifetime\n// ----------------------------------\n\n/** Max time a journey stays open, in milliseconds. Then the library treats it as abandoned. */\nexport const JOURNEY_MAX_AGE_MS = 30 * 60 * 1000;\n\n/** Whether closing the owning context ends the journey for everyone. */\nexport const JOURNEY_END_ON_OWNER_CLOSE = false;\n\n/** Query parameter checked at boot for a seeded journey token. */\nexport const JOURNEY_URL_PARAM = \"__uiobs_journey\";\n\n// ----------------------------------\n// Bus handshake\n// ----------------------------------\n\n/** BroadcastChannel name for the control plane. */\nexport const BUS_CHANNEL_NAME = \"ui_observability_control\";\n\n/** Max time a forwarder waits for an owner to answer before it promotes itself, in milliseconds. */\nexport const BUS_HANDSHAKE_TIMEOUT_MS = 1500;\n\n/** Handshake attempts allowed before a cross-origin forwarder promotes itself to sender. */\nexport const BUS_MAX_HANDSHAKE_ATTEMPTS = 3;\n\n/** Max records a context buffers before it knows its bus role. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Breadcrumbs kept as context for the next error. */\nexport const MAX_BREADCRUMBS = 50;\n\n/**\n * Time window in which the library counts identical errors but does not send them again,\n * in milliseconds.\n */\nexport const ERROR_DEDUPE_MS = 5000;\n\n// ----------------------------------\n// Per-record size caps\n// ----------------------------------\n\n/** Size caps for every record. The library applies them after sanitize and after redact. */\nexport const RECORD_LIMITS = {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxNodes: 10_000,\n maxRecordBytes: 32_768,\n};\n"],"mappings":";AAcA,IAAaA,KAAqB,sBAUrBC,KAAyB,KAOzBC,IAAiB,4BAGjBC,IAAa,wBAGbC,IAAkB,MAGlBC,IAAmB,KAanBC,IAAqB,YAGrBC,IAA6B,UAG7BC,IAAwB,0BAGxBC,IAAuB,iBAGvBC,IAAoB,cAGpBC,IAAkB,eAGlBC,IAAkB,WAOlBC,IAAqB,OAGrBC,IAAqB,OAMrBC,IAAwB,MA+BxBC,IAA4C;CACvD,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT,GAMaC,IAAwCD,GAUxCE,IAAgB,YAGhBC,IAAe,WAGfC,IAAqB,iBAGrBC,IAAgB,YAOhBC,IAAgB,YAGhBC,IAAkB,cAGlBC,IAAoB,gBAGpBC,IA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