@utk09/ui-observability 0.9.5 → 0.11.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 (259) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +315 -99
  3. package/bin/uiobs.mjs +8 -0
  4. package/dist/{batch-BQFtb3i5.cjs → batch-C8OcWR2L.cjs} +2 -2
  5. package/dist/{batch-BQFtb3i5.cjs.map → batch-C8OcWR2L.cjs.map} +1 -1
  6. package/dist/{batch-BUJh-1jZ.js → batch-CL9uWYY3.js} +5 -6
  7. package/dist/{batch-BUJh-1jZ.js.map → batch-CL9uWYY3.js.map} +1 -1
  8. package/dist/bus/bus.d.ts +15 -0
  9. package/dist/{bus-DeOPHWaD.js → bus-BZ0GldpT.js} +125 -112
  10. package/dist/bus-BZ0GldpT.js.map +1 -0
  11. package/dist/bus-VWlmM5xs.cjs +2 -0
  12. package/dist/bus-VWlmM5xs.cjs.map +1 -0
  13. package/dist/capture/interactions.d.ts +18 -0
  14. package/dist/capture/lifecycle.d.ts +20 -0
  15. package/dist/capture/reports.d.ts +17 -0
  16. package/dist/capture/resource-timing.d.ts +14 -0
  17. package/dist/capture/server-timing.d.ts +19 -0
  18. package/dist/capture/types.d.ts +13 -0
  19. package/dist/capture/unclean-exit.d.ts +31 -0
  20. package/dist/capture/user-timing.d.ts +22 -0
  21. package/dist/console-BPZCuSLc.cjs +2 -0
  22. package/dist/console-BPZCuSLc.cjs.map +1 -0
  23. package/dist/{console-DbAZYJuy.js → console-BeCF7n59.js} +20 -20
  24. package/dist/{console-DbAZYJuy.js.map → console-BeCF7n59.js.map} +1 -1
  25. package/dist/constants-DqKJH_MP.cjs +2 -0
  26. package/dist/constants-DqKJH_MP.cjs.map +1 -0
  27. package/dist/constants-zyrqveN4.js +304 -0
  28. package/dist/constants-zyrqveN4.js.map +1 -0
  29. package/dist/constants.d.ts +58 -2
  30. package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
  31. package/dist/{context-storage-DxZf4Gfh.js → context-storage-BzkoHzkQ.js} +2 -3
  32. package/dist/{context-storage-DxZf4Gfh.js.map → context-storage-BzkoHzkQ.js.map} +1 -1
  33. package/dist/core/debug-buffer.d.ts +34 -0
  34. package/dist/core/debug-bundle.d.ts +12 -0
  35. package/dist/core/deferred.d.ts +7 -0
  36. package/dist/core/logger.d.ts +7 -2
  37. package/dist/core/measure.d.ts +19 -0
  38. package/dist/core/pipeline.d.ts +6 -1
  39. package/dist/core/record.d.ts +20 -1
  40. package/dist/core/remote-sampling.d.ts +5 -1
  41. package/dist/core/runtime.d.ts +45 -2
  42. package/dist/core/sampling.d.ts +5 -4
  43. package/dist/core/sender.d.ts +3 -1
  44. package/dist/core/spans.d.ts +5 -0
  45. package/dist/{deadline-5_PecIl5.js → deadline-BOjOxNHj.js} +3 -5
  46. package/dist/{deadline-5_PecIl5.js.map → deadline-BOjOxNHj.js.map} +1 -1
  47. package/dist/deadline-XSnm95pg.cjs.map +1 -1
  48. package/dist/debug-bundle-BzJNpbF0.cjs +2 -0
  49. package/dist/debug-bundle-BzJNpbF0.cjs.map +1 -0
  50. package/dist/debug-bundle-C7UkHZ-q.js +25 -0
  51. package/dist/debug-bundle-C7UkHZ-q.js.map +1 -0
  52. package/dist/doctor.cjs +2 -0
  53. package/dist/doctor.cjs.map +1 -0
  54. package/dist/doctor.d.ts +23 -0
  55. package/dist/doctor.js +98 -0
  56. package/dist/doctor.js.map +1 -0
  57. package/dist/{emergency-queue-Cs1hrjsC.cjs → emergency-queue-CNTRui5t.cjs} +2 -2
  58. package/dist/{emergency-queue-Cs1hrjsC.cjs.map → emergency-queue-CNTRui5t.cjs.map} +1 -1
  59. package/dist/{emergency-queue-BYUyDHGD.js → emergency-queue-Zy6lNafo.js} +17 -19
  60. package/dist/{emergency-queue-BYUyDHGD.js.map → emergency-queue-Zy6lNafo.js.map} +1 -1
  61. package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
  62. package/dist/{error-like-Ywo5uRHo.js.map → error-like-B11pB4aL.js.map} +1 -1
  63. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  64. package/dist/{errors-BhC7HTSt.js → errors-Dh7kef0i.js} +5 -6
  65. package/dist/{errors-BhC7HTSt.js.map → errors-Dh7kef0i.js.map} +1 -1
  66. package/dist/{errors-CgY633cG.cjs → errors-tfEr48bS.cjs} +2 -2
  67. package/dist/{errors-CgY633cG.cjs.map → errors-tfEr48bS.cjs.map} +1 -1
  68. package/dist/{factory-C5TujXlU.js → factory-BonqI3NL.js} +16 -20
  69. package/dist/{factory-C5TujXlU.js.map → factory-BonqI3NL.js.map} +1 -1
  70. package/dist/{factory-CNj4DH3n.cjs → factory-CJXVYp0R.cjs} +2 -2
  71. package/dist/{factory-CNj4DH3n.cjs.map → factory-CJXVYp0R.cjs.map} +1 -1
  72. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  73. package/dist/{fixed-window-CtaFHanJ.js → fixed-window-Dq3MLUUv.js} +2 -3
  74. package/dist/{fixed-window-CtaFHanJ.js.map → fixed-window-Dq3MLUUv.js.map} +1 -1
  75. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  76. package/dist/{global-scope-dp2jADRl.js → global-scope-D9I8s-oN.js} +2 -3
  77. package/dist/{global-scope-dp2jADRl.js.map → global-scope-D9I8s-oN.js.map} +1 -1
  78. package/dist/guards-Cidk71ME.js +7 -0
  79. package/dist/guards-Cidk71ME.js.map +1 -0
  80. package/dist/guards-nJ70syPt.cjs +2 -0
  81. package/dist/guards-nJ70syPt.cjs.map +1 -0
  82. package/dist/{identity-Da9TkuKd.cjs → identity-Cxgj6pZX.cjs} +2 -2
  83. package/dist/{identity-Da9TkuKd.cjs.map → identity-Cxgj6pZX.cjs.map} +1 -1
  84. package/dist/{identity-8vKkyAWm.js → identity-DT5VmvXy.js} +15 -16
  85. package/dist/{identity-8vKkyAWm.js.map → identity-DT5VmvXy.js.map} +1 -1
  86. package/dist/index.cjs +1 -1
  87. package/dist/index.cjs.map +1 -1
  88. package/dist/index.d.ts +27 -7
  89. package/dist/index.js +980 -604
  90. package/dist/index.js.map +1 -1
  91. package/dist/{indexeddb-storage-CCA1LvtO.js → indexeddb-storage-BJVtiQKm.js} +29 -30
  92. package/dist/{indexeddb-storage-CCA1LvtO.js.map → indexeddb-storage-BJVtiQKm.js.map} +1 -1
  93. package/dist/{indexeddb-storage-BTfIFRHF.cjs → indexeddb-storage-CIoW21Xd.cjs} +2 -2
  94. package/dist/{indexeddb-storage-BTfIFRHF.cjs.map → indexeddb-storage-CIoW21Xd.cjs.map} +1 -1
  95. package/dist/interactions-DTgKy_6K.js +119 -0
  96. package/dist/interactions-DTgKy_6K.js.map +1 -0
  97. package/dist/interactions-fEN6FbVo.cjs +2 -0
  98. package/dist/interactions-fEN6FbVo.cjs.map +1 -0
  99. package/dist/{journey-BUJ4WJxP.js → journey-CuJrHzEg.js} +18 -19
  100. package/dist/{journey-BUJ4WJxP.js.map → journey-CuJrHzEg.js.map} +1 -1
  101. package/dist/{journey-B_tTnvac.cjs → journey-pffMVMfa.cjs} +2 -2
  102. package/dist/{journey-B_tTnvac.cjs.map → journey-pffMVMfa.cjs.map} +1 -1
  103. package/dist/keys-BHhw_0Wh.cjs.map +1 -1
  104. package/dist/{keys-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
  105. package/dist/{keys-D5r_GH9q.js.map → keys-BU9j5YqW.js.map} +1 -1
  106. package/dist/library-console-C1m6g1BR.js +13 -0
  107. package/dist/library-console-C1m6g1BR.js.map +1 -0
  108. package/dist/library-console-D2GY9Or6.cjs +2 -0
  109. package/dist/library-console-D2GY9Or6.cjs.map +1 -0
  110. package/dist/{library-request-BaZOi4eg.cjs → library-request-1BX_UlaX.cjs} +2 -2
  111. package/dist/{library-request-BaZOi4eg.cjs.map → library-request-1BX_UlaX.cjs.map} +1 -1
  112. package/dist/library-request-BQBT9N9Q.js +24 -0
  113. package/dist/{library-request-BKOcaKtQ.js.map → library-request-BQBT9N9Q.js.map} +1 -1
  114. package/dist/lifecycle-2EtUaRpo.cjs +2 -0
  115. package/dist/lifecycle-2EtUaRpo.cjs.map +1 -0
  116. package/dist/lifecycle-BaKx_-32.js +55 -0
  117. package/dist/lifecycle-BaKx_-32.js.map +1 -0
  118. package/dist/log-record-CAoGBBf3.js +16 -0
  119. package/dist/log-record-CAoGBBf3.js.map +1 -0
  120. package/dist/log-record-i9zOTkpQ.cjs +2 -0
  121. package/dist/log-record-i9zOTkpQ.cjs.map +1 -0
  122. package/dist/{long-frames-CF3qiSAX.cjs → long-frames-BVg4i5SC.cjs} +2 -2
  123. package/dist/{long-frames-CF3qiSAX.cjs.map → long-frames-BVg4i5SC.cjs.map} +1 -1
  124. package/dist/{long-frames-DI5ypfAF.js → long-frames-Czk7IupC.js} +4 -5
  125. package/dist/{long-frames-DI5ypfAF.js.map → long-frames-Czk7IupC.js.map} +1 -1
  126. package/dist/models/config.d.ts +168 -4
  127. package/dist/models/health.d.ts +25 -0
  128. package/dist/models/metric.d.ts +13 -0
  129. package/dist/models/storage.d.ts +5 -0
  130. package/dist/{network-DdzXDI3J.js → network-DBNwApoF.js} +117 -70
  131. package/dist/network-DBNwApoF.js.map +1 -0
  132. package/dist/network-xbbuvG_6.cjs +2 -0
  133. package/dist/network-xbbuvG_6.cjs.map +1 -0
  134. package/dist/openfin-Bxelt0yg.js +7 -0
  135. package/dist/{openfin-BwEN0uj4.js.map → openfin-Bxelt0yg.js.map} +1 -1
  136. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  137. package/dist/otlp-BDvFrLnc.cjs +2 -0
  138. package/dist/otlp-BDvFrLnc.cjs.map +1 -0
  139. package/dist/otlp-BTJdIa6F.js +81 -0
  140. package/dist/otlp-BTJdIa6F.js.map +1 -0
  141. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  142. package/dist/{patch-CCWfuEY7.js → patch-UdPz1ea8.js} +2 -3
  143. package/dist/{patch-CCWfuEY7.js.map → patch-UdPz1ea8.js.map} +1 -1
  144. package/dist/{platform-DBSKTvFn.cjs → platform-C2Ez5kDc.cjs} +2 -2
  145. package/dist/{platform-DBSKTvFn.cjs.map → platform-C2Ez5kDc.cjs.map} +1 -1
  146. package/dist/{platform-Bw1btWCT.js → platform-DkcuXwe-.js} +5 -6
  147. package/dist/{platform-Bw1btWCT.js.map → platform-DkcuXwe-.js.map} +1 -1
  148. package/dist/remote-rules-Cfb4K-Nl.js +98 -0
  149. package/dist/remote-rules-Cfb4K-Nl.js.map +1 -0
  150. package/dist/remote-rules-vzvk7aKf.cjs +2 -0
  151. package/dist/remote-rules-vzvk7aKf.cjs.map +1 -0
  152. package/dist/reports-Dk2YhKIh.cjs +2 -0
  153. package/dist/reports-Dk2YhKIh.cjs.map +1 -0
  154. package/dist/reports-TA-zInnq.js +70 -0
  155. package/dist/reports-TA-zInnq.js.map +1 -0
  156. package/dist/resource-timing-BLv3EA2A.js +76 -0
  157. package/dist/resource-timing-BLv3EA2A.js.map +1 -0
  158. package/dist/resource-timing-Cysw1S1f.cjs +2 -0
  159. package/dist/resource-timing-Cysw1S1f.cjs.map +1 -0
  160. package/dist/sampling-C4VV-1MS.js +60 -0
  161. package/dist/sampling-C4VV-1MS.js.map +1 -0
  162. package/dist/sampling-Ckh2yW9k.cjs +2 -0
  163. package/dist/sampling-Ckh2yW9k.cjs.map +1 -0
  164. package/dist/sanitize-6ymPlVvP.js +112 -0
  165. package/dist/sanitize-6ymPlVvP.js.map +1 -0
  166. package/dist/sanitize-BAWzkZt0.cjs +2 -0
  167. package/dist/sanitize-BAWzkZt0.cjs.map +1 -0
  168. package/dist/select-ZF4by-lF.cjs +3 -0
  169. package/dist/select-ZF4by-lF.cjs.map +1 -0
  170. package/dist/select-xtQaenIi.js +270 -0
  171. package/dist/select-xtQaenIi.js.map +1 -0
  172. package/dist/{sender-DUUmSglb.js → sender-CiMHC9YG.js} +202 -509
  173. package/dist/sender-CiMHC9YG.js.map +1 -0
  174. package/dist/sender-D5wBoXA8.cjs +2 -0
  175. package/dist/sender-D5wBoXA8.cjs.map +1 -0
  176. package/dist/storage/persistence.d.ts +8 -0
  177. package/dist/storage-BA9RqRO-.cjs.map +1 -1
  178. package/dist/{storage-w7Tslvlq.js → storage-DZwed89z.js} +2 -3
  179. package/dist/storage-DZwed89z.js.map +1 -0
  180. package/dist/storm-CYi9Swpx.cjs +2 -0
  181. package/dist/{storm-CNZjsw4T.cjs.map → storm-CYi9Swpx.cjs.map} +1 -1
  182. package/dist/{storm-Daq2jGHU.js → storm-VR024_QN.js} +4 -5
  183. package/dist/{storm-Daq2jGHU.js.map → storm-VR024_QN.js.map} +1 -1
  184. package/dist/transport/headers.d.ts +8 -0
  185. package/dist/transport/http-transport.d.ts +2 -6
  186. package/dist/transport/serializers/otlp.d.ts +14 -0
  187. package/dist/transport/status-transport.d.ts +5 -2
  188. package/dist/transport/worker-client.d.ts +14 -0
  189. package/dist/transport/worker-entry.d.ts +5 -0
  190. package/dist/transport/worker-protocol.d.ts +36 -0
  191. package/dist/transport/worker-server.d.ts +3 -0
  192. package/dist/transport/worker-transport.d.ts +9 -0
  193. package/dist/{types-BR9t_w28.js → types-BAerHgCq.js} +2 -3
  194. package/dist/types-BAerHgCq.js.map +1 -0
  195. package/dist/types-C7WNpnG1.cjs.map +1 -1
  196. package/dist/unclean-exit-CwcUhFOn.js +62 -0
  197. package/dist/unclean-exit-CwcUhFOn.js.map +1 -0
  198. package/dist/unclean-exit-DFUN57wY.cjs +2 -0
  199. package/dist/unclean-exit-DFUN57wY.cjs.map +1 -0
  200. package/dist/user-timing-C9kfRq3J.cjs +2 -0
  201. package/dist/user-timing-C9kfRq3J.cjs.map +1 -0
  202. package/dist/user-timing-_jZIhDKI.js +63 -0
  203. package/dist/user-timing-_jZIhDKI.js.map +1 -0
  204. package/dist/{web-socket-BacvKOvD.cjs → web-socket-BWUoqBh8.cjs} +2 -2
  205. package/dist/{web-socket-BacvKOvD.cjs.map → web-socket-BWUoqBh8.cjs.map} +1 -1
  206. package/dist/{web-socket-CpsD8WAa.js → web-socket-CV7yIMnm.js} +7 -8
  207. package/dist/{web-socket-CpsD8WAa.js.map → web-socket-CV7yIMnm.js.map} +1 -1
  208. package/dist/{web-vitals-Bflr5jSA.js → web-vitals-Bq4WFHQo.js} +2 -3
  209. package/dist/{web-vitals-Bflr5jSA.js.map → web-vitals-Bq4WFHQo.js.map} +1 -1
  210. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -1
  211. package/dist/worker-protocol-Bai7GAIA.cjs +2 -0
  212. package/dist/worker-protocol-Bai7GAIA.cjs.map +1 -0
  213. package/dist/worker-protocol-CrsdSDLn.js +49 -0
  214. package/dist/worker-protocol-CrsdSDLn.js.map +1 -0
  215. package/dist/worker-server-BrIYkfoa.cjs +2 -0
  216. package/dist/worker-server-BrIYkfoa.cjs.map +1 -0
  217. package/dist/worker-server-Dp5HYm4b.js +83 -0
  218. package/dist/worker-server-Dp5HYm4b.js.map +1 -0
  219. package/dist/worker-transport-Bwej4N2e.cjs +2 -0
  220. package/dist/worker-transport-Bwej4N2e.cjs.map +1 -0
  221. package/dist/worker-transport-D6jtgpqN.js +199 -0
  222. package/dist/worker-transport-D6jtgpqN.js.map +1 -0
  223. package/package.json +31 -41
  224. package/dist/bus-BW6N-pY8.cjs +0 -2
  225. package/dist/bus-BW6N-pY8.cjs.map +0 -1
  226. package/dist/bus-DeOPHWaD.js.map +0 -1
  227. package/dist/console-Ce6heqZZ.cjs +0 -2
  228. package/dist/console-Ce6heqZZ.cjs.map +0 -1
  229. package/dist/constants-CN7GE1Lt.js +0 -246
  230. package/dist/constants-CN7GE1Lt.js.map +0 -1
  231. package/dist/constants-CW-MlHdY.cjs +0 -2
  232. package/dist/constants-CW-MlHdY.cjs.map +0 -1
  233. package/dist/interactions-BUDLxbv1.js +0 -74
  234. package/dist/interactions-BUDLxbv1.js.map +0 -1
  235. package/dist/interactions-NHbLKrqe.cjs +0 -2
  236. package/dist/interactions-NHbLKrqe.cjs.map +0 -1
  237. package/dist/library-request-BKOcaKtQ.js +0 -25
  238. package/dist/network-CF8UO5PK.cjs +0 -2
  239. package/dist/network-CF8UO5PK.cjs.map +0 -1
  240. package/dist/network-DdzXDI3J.js.map +0 -1
  241. package/dist/openfin-BwEN0uj4.js +0 -8
  242. package/dist/remote-rules-DIcC5vVC.js +0 -91
  243. package/dist/remote-rules-DIcC5vVC.js.map +0 -1
  244. package/dist/remote-rules-DpFmOef2.cjs +0 -2
  245. package/dist/remote-rules-DpFmOef2.cjs.map +0 -1
  246. package/dist/sampling-BVjspJWu.cjs +0 -2
  247. package/dist/sampling-BVjspJWu.cjs.map +0 -1
  248. package/dist/sampling-Cm3WhI0a.js +0 -76
  249. package/dist/sampling-Cm3WhI0a.js.map +0 -1
  250. package/dist/sanitize-C-ahCFsG.js +0 -123
  251. package/dist/sanitize-C-ahCFsG.js.map +0 -1
  252. package/dist/sanitize-DHucKGdi.cjs +0 -2
  253. package/dist/sanitize-DHucKGdi.cjs.map +0 -1
  254. package/dist/sender-D3fRCR8d.cjs +0 -3
  255. package/dist/sender-D3fRCR8d.cjs.map +0 -1
  256. package/dist/sender-DUUmSglb.js.map +0 -1
  257. package/dist/storage-w7Tslvlq.js.map +0 -1
  258. package/dist/storm-CNZjsw4T.cjs +0 -2
  259. package/dist/types-BR9t_w28.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus-BZ0GldpT.js","names":["BUS_TYPE","BUS_CHANNEL_NAME","REMOTE_SAMPLING_POLL_MS","SEVERITY_NUMBER","RUNTIME_GLOBAL_KEY","BUS_PROTOCOL","BUS_HANDSHAKE_TIMEOUT_MS","parseJourney","parseRemoteRules","applyRemote","isLogRecord","isLogLevel","getFin","windowEnded","countInWindow","unrefTimer","validMessage","value","m","text","key","r","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","OPAQUE_ORIGIN","untrustedText","origin","what","parentOrigin","ancestors","referrer","createDirectLink","host","target","open","diagnostics","receive","createParentLink","self","trusted","trustedOrigins","reported","onMessage","event","createChildrenLink","sources","send","authorize","source","mayPost","answer","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","uuid","name","createOwnerLink","scope","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","permissions","peer","element","frame","options","registration","openFin","ref","reply","known","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","encoder","size","maxMessageBytes","chunk","bytes","record","records","recordBytes","comma","maxRecordsPerMessage","plain","link","index","child","accepted","object","now","rate","entry","encoded","permission","before","current","configured","me","push","registered","settled","finish","timer","resolve","result","from","payload","journey","rules","to","update","upstream","ask"],"sources":["../src/bus/validation.ts","../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/bus/validation.ts\n//\n// Checks the required fields and values of messages from another context.\n\nimport type { BusMessage } from \"../models/bus\";\nimport { isLogLevel, isLogRecord } from \"../models/log-record\";\nimport { BUS_TYPE, SEVERITY_NUMBER } from \"../constants\";\n\n/**\n * Checks the fields required by each bus message type. unwrap() checks the envelope only.\n * @param value Message to check.\n * @returns True if the message has the required fields and values.\n */\nexport function validMessage(value: unknown): value is BusMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const m = value as Record<string, unknown>;\n if (typeof m.from !== \"string\" || !m.from || typeof m.t !== \"string\") return false;\n const text = (key: string): boolean => typeof m[key] === \"string\";\n switch (m.t) {\n case BUS_TYPE.hello:\n case BUS_TYPE.tab:\n return text(\"tabId\");\n case BUS_TYPE.welcome:\n return (\n text(\"to\") &&\n text(\"tabId\") &&\n (m.routingContextId === undefined || text(\"routingContextId\"))\n );\n case BUS_TYPE.journeyRequest:\n case BUS_TYPE.samplingRequest:\n return true;\n case BUS_TYPE.securityContext:\n return text(\"id\") && m.id !== \"\";\n case BUS_TYPE.journey:\n return (m.to === undefined || text(\"to\")) && \"journey\" in m;\n case BUS_TYPE.sampling:\n return text(\"to\") && \"rules\" in m;\n case BUS_TYPE.records:\n return (\n Array.isArray(m.records) &&\n (m.routingContextId === undefined || text(\"routingContextId\")) &&\n m.records.every((r: unknown) => {\n if (!isLogRecord(r) || !isLogLevel(r.severityText)) return false;\n return (\n !Array.isArray(r.attributes) &&\n !Array.isArray(r.resource) &&\n /^\\d+$/.test(r.timeUnixNano) &&\n (r.observedTimeUnixNano === undefined || /^\\d+$/.test(r.observedTimeUnixNano)) &&\n typeof r.traceId === \"string\" &&\n /^(?:[a-f\\d]{32})?$/.test(r.traceId) &&\n typeof r.spanId === \"string\" &&\n /^(?:[a-f\\d]{16})?$/.test(r.spanId) &&\n Number.isInteger(r.traceFlags) &&\n r.traceFlags >= 0 &&\n r.traceFlags <= 255 &&\n r.severityNumber === SEVERITY_NUMBER[r.severityText]\n );\n })\n );\n default:\n return false;\n }\n}\n","// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL, type BUS_TYPE } from \"../constants\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Permissions of one child window or worker. The handshake needs no separate permission. */\nexport type BusPermission = \"records\" | \"journey:read\" | \"journey:write\" | \"sampling:read\";\nexport interface SourceOptions {\n /** Permissions of this source. Without this list, the source can send records only. */\n permissions?: BusPermission[];\n}\n\n/** Origin and permissions for one child frame registration. */\nexport interface FrameOptions extends SourceOptions {\n /** Expected window origin, with its scheme and port. The origin must match exactly. */\n origin: string;\n}\n\n/** Delivery role. It tells if this context sends its records or forwards them upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel. The bus uses it to route incoming and outgoing messages.\n * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe\n * looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Source identity from the transport. The source does not supply it in message.from. */\n peer?: object | string;\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 /** Sends an answer to this source only. A link that cannot address one source omits it. */\n reply?: (message: BusMessage) => void;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: typeof BUS_TYPE.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 | {\n t: typeof BUS_TYPE.welcome;\n from: string;\n to: string;\n tabId: string;\n routingContextId?: string;\n }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: typeof BUS_TYPE.records; from: string; records: LogRecord[]; routingContextId?: string }\n /** Delivery context update. Only the owner from the handshake can send it to its children. */\n | { t: typeof BUS_TYPE.securityContext; from: string; id: string }\n /**\n * Journey update, or the answer to a journey question. An answer holds the address of the\n * context that asked in `to`. The payload comes from another realm. The receiver parses it.\n */\n | { t: typeof BUS_TYPE.journey; from: string; to?: string; journey: unknown }\n /** Query requesting active journey state from connected peers. */\n | { t: typeof BUS_TYPE.journeyRequest; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: typeof BUS_TYPE.tab; from: string; tabId: string }\n /** Request of a forwarder for the remote sampling rules in force. */\n | { t: typeof BUS_TYPE.samplingRequest; from: string }\n /**\n * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field\n * holds the address of the forwarder that asked. The receiver validates `rules` again.\n * Null rules end the copy of the forwarder.\n */\n | { t: typeof BUS_TYPE.sampling; from: string; to: string; rules: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A\n * document gets `message` events from all embedded content on the page. This\n * includes analytics tags, video players and extensions. Without the tag check,\n * the bus parses a message from a video player as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { BUS_TYPE_DETAIL_MAX_CHARS, RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\nimport { getFin } from \"../utils/openfin\";\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, source?: Window): void;\n /**\n * Checks if the parent permits a direct link from the child window.\n * @param source Child window.\n * @param origin Origin of the child window.\n * @returns True if the parent permits this source.\n */\n busCanAccept?: (source: Window, origin: string) => boolean;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst OPAQUE_ORIGIN = \"null\";\n\n/** Location with the ancestor list that Chromium and WebKit give. */\ninterface LocationWithAncestors {\n origin: string;\n ancestorOrigins?: { length: number; item: (index: number) => string | null };\n}\n\n/**\n * Builds the message for an ignored message from an untrusted origin.\n * @param origin Origin of the sender.\n * @param what What the bus ignored, for example \"a message\".\n * @returns The message. A sandboxed sender gets the fix for its frame.\n */\nfunction untrustedText(origin: string, what: string): string {\n if (origin === OPAQUE_ORIGIN) {\n return `The bus ignored ${what} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`;\n }\n\n return `The bus ignored ${what} from ${origin}. If you own this origin, add it to bus.trustedOrigins.`;\n}\n\n/**\n * Reads the origin of the parent frame. A cross-origin parent does not give its location.\n * @returns The origin, or null when the browser does not give it.\n */\nfunction parentOrigin(): string | null {\n const ancestors = (location as LocationWithAncestors).ancestorOrigins;\n if (ancestors && ancestors.length > 0) {\n return ancestors.item(0);\n }\n\n // Firefox has no ancestorOrigins. The referrer of a frame is the page that loaded it.\n // A Referrer-Policy of no-referrer gives \"\". The caller reports an unknown origin.\n const referrer = document.referrer;\n if (referrer === \"\") {\n return null;\n }\n\n try {\n return new URL(referrer).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n if (host.busCanAccept && !host.busCanAccept(window, location.origin)) return null;\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, window);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to a parent window on a trusted origin. Records hold user data.\n * A page on another origin that frames this app must not get them.\n * @param receive Callback for incoming parent messages.\n * @param trustedOrigins Origins of a parent that can get the records, in addition to this origin.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to the parent window, or null at the top level or with an untrusted parent.\n * With null, this context sends its own records.\n */\nexport function createParentLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n // A sandboxed frame has an opaque origin. No parent can list it in its own trust list.\n const self = location.origin;\n if (self === OPAQUE_ORIGIN) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n 'This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.',\n { origin: self, type: \"parent\" },\n );\n return null;\n }\n\n const trusted = new Set([self, ...trustedOrigins]);\n const target = parentOrigin();\n if (target === null || !trusted.has(target)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n target === null\n ? \"The origin of the parent frame is unknown. This context sends its own records.\"\n : `The parent frame is on ${target}. This origin is not in bus.trustedOrigins. This context sends its own records.`,\n { origin: target ?? \"\", type: \"parent\" },\n );\n return null;\n }\n\n // Report each untrusted origin one time. A hostile parent can send many messages.\n const reported = new Set<string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message || event.source !== window.parent) {\n return;\n }\n\n // The parent can navigate to another origin after this frame loads.\n if (!trusted.has(event.origin)) {\n if (!reported.has(event.origin)) {\n reported.add(event.origin);\n // The parent sets message.t. Keep it out of the message text. Cut it in the detail.\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n }\n return;\n }\n\n receive(message, { link: \"parent\", origin: event.origin, peer: event.source });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // Target the trusted origin, not \"*\". The browser drops the message if the parent\n // navigated to another origin.\n window.parent.postMessage(envelope(message), target);\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n authorize?: (source: MessageEventSource | null, origin: string) => boolean,\n mayPost?: (message: BusMessage, source: MessageEventSource) => boolean,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // A sandboxed page has the opaque origin \"null\". Each sandboxed child also has it.\n const trusted = new Set([location.origin, ...trustedOrigins]);\n trusted.delete(OPAQUE_ORIGIN);\n\n // The map keeps the origin of each source.\n // A child that navigates must not get the ids of its previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n /**\n * Posts one message to one child. It removes a child that is closed or no longer permitted.\n * @param source Child window.\n * @param origin Last known origin of the child.\n * @param message Message to send.\n */\n const send = (source: MessageEventSource, origin: string, message: BusMessage): void => {\n if (authorize && !authorize(source, origin)) {\n sources.delete(source);\n return;\n }\n if (mayPost && !mayPost(message, source)) {\n return;\n }\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n return;\n }\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a child frame failed.\", () => {\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 const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n // A nested frame also receives the messages of its parent. The parent link owns them.\n if (window.parent !== window && event.source === window.parent) {\n return;\n }\n if (!authorize && !trusted.has(event.origin)) {\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n return;\n }\n\n if (authorize && !authorize(event.source, event.origin)) return;\n const { source, origin } = event;\n if (source) {\n sources.set(source, origin);\n }\n // Answer only the asking child. A broadcast lets one child use up the budget of each sibling.\n receive(message, {\n link: \"children\",\n origin,\n peer: source ?? undefined,\n reply: source\n ? (answer) => {\n send(source, origin, answer);\n }\n : undefined,\n });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n send(source, origin, message);\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/**\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 iab = getFin()?.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, uuid, name) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, {\n link: \"openfin\",\n origin: \"openfin\",\n peer: uuid && name ? `${uuid}:${name}` : undefined,\n });\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\", peer: worker });\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 BUS_TYPE,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type Journey, parseJourney } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { SourceOptions, FrameOptions } from \"../models/bus\";\nimport { validMessage } from \"./validation\";\nimport type { JourneyScope, ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { getFin } from \"../utils/openfin\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { countInWindow, windowEnded } from \"../utils/fixed-window\";\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 /** Adopts the delivery context of the owner. False refuses a different identity. */\n onSecurityContext?: (id: string) => boolean;\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Journey scope after the bus resolves \"auto\". */\ntype ResolvedScope = Exclude<JourneyScope, \"auto\">;\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Window and worker registrations with their permissions. */\n private readonly sources = new Map<object, SourceOptions & { origin?: string }>();\n /** Message counts for each window and worker in the current rate window. */\n private readonly rates = new WeakMap<object, { start: number; count: number }>();\n /** Message counts for each named source or link in the current rate window. */\n private readonly channelRates = new Map<string, { start: number; count: number }>();\n /** Reply of each same-origin child on the direct link. A weak reply frees a navigated frame. */\n private readonly directReplies = new Map<Window, WeakRef<Receive>>();\n\n /**\n * Checks if this source can receive a control message. A window can read a message\n * even when its address names another window.\n * @param message Control message to send.\n * @param peer Window or worker that receives the message.\n * @returns True if the source has the required permission.\n */\n private mayPost(message: BusMessage, peer: object): boolean {\n const permissions = this.sources.get(peer)?.permissions;\n if (!permissions) return this.config.bus.sourcePolicy === \"trusted-origin\";\n if (message.t === BUS_TYPE.journey) return permissions.includes(\"journey:read\");\n if (message.t === BUS_TYPE.journeyRequest) return permissions.includes(\"journey:write\");\n if (message.t === BUS_TYPE.sampling) return permissions.includes(\"sampling:read\");\n return true;\n }\n\n /**\n * Registers one child window and its permissions.\n * @param frame Frame element or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n // Use instanceof, not \"in\". The \"in\" operator throws on a cross-origin window.\n const element = typeof HTMLIFrameElement === \"undefined\" ? undefined : HTMLIFrameElement;\n const source = element && frame instanceof element ? frame.contentWindow : frame;\n if (!source || new URL(options.origin).origin !== options.origin || options.origin === \"null\")\n throw new Error(\"A frame registration requires a window and an exact origin.\");\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(source, registration);\n this.ensureChildrenLink();\n return () => {\n if (this.sources.get(source) === registration) this.sources.delete(source);\n };\n }\n\n /**\n * Checks if a source is permitted at the given origin.\n * @param source Window or port that sent the message.\n * @param origin Origin supplied by the transport.\n * @returns True if the current source policy permits this source.\n */\n isRegistered(source: object | null, origin: string): boolean {\n if (!source) return false;\n const registration = this.sources.get(source);\n // A registration binds its exact origin under each policy. It needs no trustedOrigins entry.\n if (registration) {\n return registration.origin === origin;\n }\n if (this.config.bus.sourcePolicy === \"registered\") {\n return false;\n }\n return (\n origin !== \"null\" &&\n (origin === location.origin || this.config.bus.trustedOrigins.includes(origin))\n );\n }\n\n /**\n * Sends the new context id to child frames, workers and OpenFin views. Other tabs keep their\n * own context.\n */\n rotateContext(): void {\n // Only the owner sends on the OpenFin link. Without this message, each view keeps the old id.\n this.passContext(this.role === \"sender\");\n }\n\n /**\n * Sends the context id to child frames and workers.\n * @param openFin True to send it to OpenFin views too.\n */\n private passContext(openFin: boolean): void {\n const message: BusMessage = {\n t: BUS_TYPE.securityContext,\n from: this.contextId,\n id: this.config.securityContext.id,\n };\n this.postOver(\"children\", message);\n this.postOver(\"worker\", message);\n this.postToDirectChildren(message);\n if (openFin) {\n this.postOver(\"openfin\", message);\n }\n }\n\n /**\n * Sends a security context message to each same-origin child on the direct link.\n * It drops a child that is closed, freed or no longer permitted.\n * @param message Security context message.\n */\n private postToDirectChildren(message: BusMessage): void {\n for (const [peer, ref] of this.directReplies) {\n const reply = ref.deref();\n if (!reply || peer.closed || !this.isRegistered(peer, location.origin)) {\n this.directReplies.delete(peer);\n continue;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"The reply to a direct child failed.\", () => {\n reply(message, { link: \"direct\", origin: \"same-origin\", peer });\n });\n }\n }\n\n /**\n * Keeps the reply of a direct child for the next context id. It drops each closed child.\n * A removed frame then does not keep its document in memory.\n * @param peer Window of the child.\n * @param reply Reply callback of the child.\n */\n private keepDirectReply(peer: Window, reply: Receive): void {\n for (const known of this.directReplies.keys()) {\n if (known.closed) {\n this.directReplies.delete(known);\n }\n }\n\n this.directReplies.set(peer, new WeakRef(reply));\n }\n\n /** Current bus role. The default is \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** True if this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(). A handshake that ends later must not start a timer. */\n private destroyed = false;\n /** Context id of the owner that answered the handshake. Null with no handshake. */\n private ownerId: string | null = null;\n /** Transport identity of the owner from the handshake. */\n private ownerPeer?: object | string;\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 /**\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 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.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 await this.handshake(direct);\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.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.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 const { maxRecordsPerMessage, maxMessageBytes } = this.config.bus;\n const encoder = new TextEncoder();\n const size = (value: unknown): number =>\n maxMessageBytes ? encoder.encode(JSON.stringify(value)).length : 0;\n const message = (chunk: LogRecord[]): BusMessage => ({\n t: BUS_TYPE.records,\n from: this.contextId,\n records: chunk,\n routingContextId: this.config.securityContext.id || undefined,\n });\n\n // Measure each record one time. A message is the empty envelope, its records and the commas.\n const envelope = size(message([]));\n let chunk: LogRecord[] = [];\n let bytes = envelope;\n\n for (const record of records) {\n const recordBytes = size(record);\n if (maxMessageBytes && envelope + recordBytes > maxMessageBytes) {\n this.diagnostics.count(\"bus.rejected_message\");\n continue;\n }\n\n const comma = chunk.length > 0 ? 1 : 0;\n if (\n (maxRecordsPerMessage && chunk.length >= maxRecordsPerMessage) ||\n (maxMessageBytes && bytes + comma + recordBytes > maxMessageBytes)\n ) {\n this.upstream?.post(message(chunk));\n chunk = [];\n bytes = envelope;\n }\n\n bytes += (chunk.length > 0 ? 1 : 0) + recordBytes;\n chunk.push(record);\n }\n\n if (chunk.length > 0) {\n this.upstream?.post(message(chunk));\n }\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, peer?: Window): void {\n // The child gets the plain source. The reply field stays on this side.\n const plain: MessageSource = { link: \"direct\", origin: \"same-origin\", peer };\n const source: MessageSource = {\n ...plain,\n reply: (answer) => {\n reply(answer, plain);\n },\n };\n if (!this.acceptsMessage(message, source, true)) return;\n if (message.from === this.contextId) {\n return;\n }\n\n // A rotation sends the new id with this reply. The child then does not send a stale batch.\n if (peer) {\n this.keepDirectReply(peer, reply);\n }\n\n // A direct link has no channel from the parent to the child. The parent answers here. The\n // forwarder rule in routeMessage() refuses a sampling question on a direct link.\n if (message.t === BUS_TYPE.samplingRequest) {\n reply(this.rulesAnswer(message.from), plain);\n return;\n }\n // A context that waits for its own owner has no final id. It sends no id.\n if (\n message.t === BUS_TYPE.records &&\n !this.awaitingWelcome &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n reply(\n { t: BUS_TYPE.securityContext, from: this.contextId, id: this.config.securityContext.id },\n plain,\n );\n }\n this.routeMessage(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, options: SourceOptions = {}): () => void {\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(worker, registration);\n const raw = createWorkerLink(worker, this.receive, this.diagnostics);\n const link: Link = {\n ...raw,\n post: (message) => {\n if (this.mayPost(message, worker)) raw.post(message);\n },\n };\n this.links.push(link);\n return () => {\n link.close();\n const index = this.links.indexOf(link);\n if (index >= 0) this.links.splice(index, 1);\n if (this.sources.get(worker) === registration) this.sources.delete(worker);\n };\n }\n\n /**\n * Sends journey state changes over each link of the journey scope.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.postJourney({ t: BUS_TYPE.journey, from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.sources.clear();\n this.directReplies.clear();\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.ownerId = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Sends a journey message over each link of the journey scope. */\n private postJourney(message: BusMessage): void {\n for (const link of this.allLinks()) {\n if (this.journeyLink(link.kind)) {\n link.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n // A message on the direct link here is an answer from the parent. acceptDirect() takes the\n // messages of a direct child. Thus only the children and worker links carry child traffic.\n const child = source.link === \"children\" || source.link === \"worker\";\n if (this.acceptsMessage(message, source, child)) {\n this.routeMessage(message, source);\n }\n };\n\n /**\n * Checks the source, the message limits and the message shape before delivery.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the bus can accept the message.\n */\n private acceptsMessage(message: BusMessage, source: MessageSource, child: boolean): boolean {\n if (this.destroyed) {\n return false;\n }\n\n let accepted: boolean;\n try {\n accepted = this.passesChecks(message, source, child);\n } catch {\n // A value that JSON cannot encode, or a non-finite number under strict validation.\n // The count below reports this rejection.\n accepted = false;\n }\n\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n }\n return accepted;\n }\n\n /**\n * Runs the source, budget, shape and permission checks. Each check returns false, not an error.\n * A flood of rejected messages then makes no stack traces.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the message passes each check.\n */\n private passesChecks(message: BusMessage, source: MessageSource, child: boolean): boolean {\n const { bus } = this.config;\n const registration =\n typeof source.peer === \"object\" ? this.sources.get(source.peer) : undefined;\n if (child && bus.sourcePolicy === \"registered\" && !registration) {\n return false;\n }\n\n const object = typeof source.peer === \"object\" ? source.peer : undefined;\n const key = typeof source.peer === \"string\" ? source.peer : source.link;\n const now = Date.now();\n const rate = (object ? this.rates.get(object) : this.channelRates.get(key)) ?? {\n start: now,\n count: 0,\n };\n if (object) {\n this.rates.set(object, rate);\n } else {\n for (const [peer, entry] of this.channelRates) {\n if (windowEnded(entry, 1000, now)) {\n this.channelRates.delete(peer);\n }\n }\n if (\n bus.maxTrackedSources &&\n this.channelRates.size >= bus.maxTrackedSources &&\n !this.channelRates.has(key)\n ) {\n return false;\n }\n this.channelRates.set(key, rate);\n }\n\n // Count with no limit when the limit is 0. The window of a named source then stays current.\n if (!countInWindow(rate, bus.maxMessagesPerSecond || Infinity, 1000)) {\n return false;\n }\n\n const encoded = JSON.stringify(message, (_key, value: unknown) => {\n if (bus.validation === \"strict\" && typeof value === \"number\" && !Number.isFinite(value)) {\n throw new Error(\"Non-finite value\");\n }\n return value;\n });\n if (bus.maxMessageBytes && new TextEncoder().encode(encoded).length > bus.maxMessageBytes) {\n return false;\n }\n if (bus.validation === \"strict\" && !validMessage(message)) {\n return false;\n }\n if (\n message.t === BUS_TYPE.records &&\n bus.maxRecordsPerMessage &&\n message.records.length > bus.maxRecordsPerMessage\n ) {\n return false;\n }\n\n if (registration) {\n const permission =\n message.t === BUS_TYPE.records\n ? \"records\"\n : message.t === BUS_TYPE.journey\n ? \"journey:write\"\n : message.t === BUS_TYPE.journeyRequest\n ? \"journey:read\"\n : message.t === BUS_TYPE.samplingRequest\n ? \"sampling:read\"\n : undefined;\n if (permission && !registration.permissions?.includes(permission)) {\n return false;\n }\n }\n\n // Only an upstream owner can publish these control messages.\n if (child && (message.t === BUS_TYPE.sampling || message.t === BUS_TYPE.securityContext)) {\n return false;\n }\n\n // Under the registered policy, broadcast is a control channel. It carries no records.\n return !(\n bus.sourcePolicy === \"registered\" &&\n source.link === \"broadcast\" &&\n message.t === BUS_TYPE.records\n );\n }\n\n /**\n * Gives an accepted message to its handler or the upstream link.\n * @param message Message that passed the source and shape checks.\n * @param source Link and identity of the source.\n */\n private routeMessage(message: BusMessage, source: MessageSource): void {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case BUS_TYPE.hello:\n if (this.canOwn(source.link)) {\n // A context that waits for its own owner has only a temporary id. Send no id then.\n // announce() sends the final id when the role is known.\n this.answer(source, {\n t: BUS_TYPE.welcome,\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n routingContextId: this.awaitingWelcome\n ? undefined\n : this.config.securityContext.id || undefined,\n });\n }\n break;\n\n case BUS_TYPE.welcome:\n if (message.to !== this.contextId) {\n break;\n }\n if (\n this.awaitingWelcome?.link === source.link ||\n (this.upstream?.kind === source.link && this.ownerId === null)\n ) {\n // Keep the owner. Only it can set the journey of this context on a shared link.\n this.ownerId = message.from;\n this.ownerPeer = source.peer;\n const before = this.config.securityContext.id;\n if (\n message.routingContextId &&\n this.handlers.onSecurityContext?.(message.routingContextId) === false\n )\n break;\n // A child of this context can hold the old id. Send it the id of the owner. During a\n // handshake the role can still be \"sender\". Do not send on the OpenFin link here.\n if (this.config.securityContext.id !== before) {\n this.passContext(false);\n }\n this.awaitingWelcome?.settle(true);\n }\n break;\n\n case BUS_TYPE.records:\n if (\n this.config.securityContext.isolation &&\n this.config.securityContext.id &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n this.diagnostics.count(\"security.context_mismatch\");\n break;\n }\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 BUS_TYPE.securityContext:\n if (\n source.link === this.upstream?.kind &&\n this.ownerId === message.from &&\n this.ownerPeer === source.peer\n ) {\n if (this.handlers.onSecurityContext?.(message.id) !== false) this.rotateContext();\n }\n break;\n\n case BUS_TYPE.journey:\n if (this.acceptsJourney(message, source)) {\n this.applyJourney(message.journey);\n }\n break;\n\n case BUS_TYPE.journeyRequest: {\n const current = this.handlers.onJourneyRequest();\n // Address the answer. On a shared link, each other context ignores it.\n if (current && this.journeyLink(source.link)) {\n this.answer(source, {\n t: BUS_TYPE.journey,\n from: this.contextId,\n to: message.from,\n journey: current,\n });\n }\n break;\n }\n\n case BUS_TYPE.samplingRequest:\n // A forwarder answers only its own children. A sibling on its upstream link asks too.\n // A sibling answer on OpenFin gives N squared messages, and a stale copy can win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.answer(source, this.rulesAnswer(message.from));\n }\n break;\n\n case BUS_TYPE.sampling:\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case BUS_TYPE.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 * Answers the source of a message. A link that can address one source sends to it only.\n * @param source Link and identity of the source.\n * @param message Answer to send.\n */\n private answer(source: MessageSource, message: BusMessage): void {\n if (source.reply) {\n source.reply(message);\n return;\n }\n this.postOver(source.link, message);\n }\n\n /**\n * Tells if records from a link can go upstream. Records that go back on\n * their arrival link return to their sender. A direct link is an exception.\n * Each direct link is one call into one parent. Thus two direct links in a\n * chain are different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Returns true if this context can be the owner of the given link type. */\n private canOwn(link: LinkKind): boolean {\n // A forwarder that knows its owner owns its own children. It relays their records upstream.\n const owner = this.role === \"sender\" || this.ownerId !== null;\n if (!owner) {\n return false;\n }\n if (link === \"openfin\") {\n return this.role === \"sender\" && this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Finds if this context is the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = getFin()?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests if a cross-origin boundary blocks access to the parent window. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. Lint rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (!this.platform.isWorker) this.ensureChildrenLink();\n if (this.platform.isTopLevelDocument) {\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 /** Opens the link to child frames if it is not already open. */\n private ensureChildrenLink(): void {\n if (this.links.some((link) => link.kind === \"children\")) return;\n const link = createChildrenLink(\n this.receive,\n this.config.bus.trustedOrigins,\n this.diagnostics,\n (source, origin) => {\n const accepted = this.isRegistered(source, origin);\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n // A registered window that speaks from another origin is also untrusted. Without this\n // report, a registration with a wrong origin stops the frame with no named cause.\n const registered = source !== null && this.sources.has(source);\n const trusted =\n origin === location.origin || this.config.bus.trustedOrigins.includes(origin);\n if (registered || !trusted) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n \"The bus rejected a message from an untrusted origin.\",\n );\n }\n }\n return accepted;\n },\n (message, source) => this.mayPost(message, source),\n );\n if (link) this.links.push(link);\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: BUS_TYPE.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: BUS_TYPE.tab,\n from: this.contextId,\n tabId: this.tabId,\n });\n if (this.upstream && this.ownerId === null)\n this.upstream.post({ t: BUS_TYPE.hello, from: this.contextId, tabId: this.tabId });\n this.postJourney({ t: BUS_TYPE.journeyRequest, from: this.contextId });\n this.pollRules();\n // The role is final now. A child welcomed during the handshake got no id. Send it the final id.\n this.passContext(false);\n }\n\n /**\n * Resolves the journey scope. \"auto\" gives \"origin\" in OpenFin and \"tab\" in a browser.\n * @returns The scope in force.\n */\n private journeyScope(): ResolvedScope {\n const { scope } = this.config.journey;\n if (scope !== \"auto\") {\n return scope;\n }\n\n const { platform } = this.platform;\n return platform === \"openfin\" || platform === \"openfin_web\" ? \"origin\" : \"tab\";\n }\n\n /**\n * Tests if a link carries journey messages in the scope in force.\n * Only \"origin\" uses the broadcast link. That link reaches each tab of the origin.\n * @param link Link kind.\n * @returns True if the link carries journey messages.\n */\n private journeyLink(link: LinkKind): boolean {\n const scope = this.journeyScope();\n if (scope === \"context\") {\n return false;\n }\n\n return scope === \"origin\" || link !== \"broadcast\";\n }\n\n /**\n * Tests if this context adopts a journey message.\n * @param message Journey message.\n * @param source Link and origin of the message.\n * @returns True for a message on a journey link, to this context, from an accepted sender.\n * In \"tab\" scope, only the owner of a forwarder is an accepted sender.\n */\n private acceptsJourney(\n message: Extract<BusMessage, { t: typeof BUS_TYPE.journey }>,\n source: MessageSource,\n ): boolean {\n if (!this.journeyLink(source.link)) {\n return false;\n }\n\n if (message.to !== undefined && message.to !== this.contextId) {\n return false;\n }\n\n return (\n this.journeyScope() === \"origin\" ||\n (this.fromOwner(message.from, source.link) &&\n (this.ownerPeer === undefined || this.ownerPeer === source.peer))\n );\n }\n\n /**\n * Tests if a message comes from the upstream owner of this forwarder.\n * @param from Context id of the sender.\n * @param link Link kind of the message.\n * @returns True for the upstream link and, after a handshake, the owner that answered it.\n */\n private fromOwner(from: string, link: LinkKind): boolean {\n if (this.role !== \"forwarder\" || link !== this.upstream?.kind) {\n return false;\n }\n\n return this.ownerId === null || from === this.ownerId;\n }\n\n /**\n * Parses a journey payload from another realm and gives it to the runtime.\n * @param payload Journey, or null when the journey ended.\n */\n private applyJourney(payload: unknown): void {\n if (payload === null) {\n this.handlers.onJourney(null);\n return;\n }\n\n const journey = parseJourney(payload);\n if (journey === null) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n \"The bus dropped a journey message. Its payload is not a journey.\",\n { type: \"journey\" },\n );\n return;\n }\n\n this.handlers.onJourney(journey);\n }\n\n /**\n * Builds the answer to a sampling question. Null rules end the copy of the forwarder.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: BUS_TYPE.sampling, from: this.contextId, to, rules };\n }\n\n /**\n * Tests if this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link is not trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. It must not lower minLevel and read the records.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== location.origin &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return this.ownerPeer === undefined || this.ownerPeer === source.peer;\n }\n\n /**\n * Applies the rules of an answer. It ignores rules that are not valid.\n * @param raw Rules of the answer, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then at each poll interval.\n * A direct link cannot push the rules to a child. A poll works on each link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config at each poll. A later configure() can turn remote sampling on or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: BUS_TYPE.samplingRequest, from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":";;;;;;;;AAaA,SAAgBgB,EAAa,GAAqC;CAChE,IAAI,OAAOC,KAAU,aAAYA,GAAgB,OAAO;CACxD,IAAMC,IAAID;CACV,IAAI,OAAOC,EAAE,QAAS,YAAY,CAACA,EAAE,QAAQ,OAAOA,EAAE,KAAM,UAAU,OAAO;CAC7E,IAAMC,KAAQ,MAAyB,OAAOD,EAAEE,MAAS;CACzD,QAAQF,EAAE,GAAV;EACE,KAAKlB,EAAS;EACd,KAAKA,EAAS,KACZ,OAAOmB,EAAK,OAAO;EACrB,KAAKnB,EAAS,SACZ,OACEmB,EAAK,IAAI,KACTA,EAAK,OAAO,MACXD,EAAE,qBAAqB,KAAA,KAAaC,EAAK,kBAAkB;EAEhE,KAAKnB,EAAS;EACd,KAAKA,EAAS,iBACZ,OAAO;EACT,KAAKA,EAAS,iBACZ,OAAOmB,EAAK,IAAI,KAAKD,EAAE,OAAO;EAChC,KAAKlB,EAAS,SACZ,QAAQkB,EAAE,OAAO,KAAA,KAAaC,EAAK,IAAI,MAAM,aAAaD;EAC5D,KAAKlB,EAAS,UACZ,OAAOmB,EAAK,IAAI,KAAK,WAAWD;EAClC,KAAKlB,EAAS,SACZ,OACE,MAAM,QAAQkB,EAAE,OAAO,MACtBA,EAAE,qBAAqB,KAAA,KAAaC,EAAK,kBAAkB,MAC5DD,EAAE,QAAQ,OAAO,MACX,CAACR,EAAYW,CAAC,KAAK,CAACV,EAAWU,EAAE,YAAY,IAAU,KAEzD,CAAC,MAAM,QAAQA,EAAE,UAAU,KAC3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,UACvBD,EAAS,KAAK;IAAE,GAAGtI,EAAS;IAAiB,MAAM,KAAK;GAAU,CAAC;EAEvE;EAIA,AAFAuI,EAAI,GACJ,KAAK,YAAY,YAAYA,GAAKrI,CAAuB,GACzDa,EAAW,KAAK,SAAS;CAC3B;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-DqKJH_MP.cjs"),t=require("./journey-pffMVMfa.cjs"),n=require("./remote-rules-vzvk7aKf.cjs"),r=require("./log-record-i9zOTkpQ.cjs"),i=require("./openfin-DtH2f7zX.cjs"),a=require("./fixed-window-CvESpFYV.cjs"),o=require("./deadline-XSnm95pg.cjs");function s(t){if(typeof t!=`object`||!t)return!1;let n=t;if(typeof n.from!=`string`||!n.from||typeof n.t!=`string`)return!1;let i=e=>typeof n[e]==`string`;switch(n.t){case e.M.hello:case e.M.tab:return i(`tabId`);case e.M.welcome:return i(`to`)&&i(`tabId`)&&(n.routingContextId===void 0||i(`routingContextId`));case e.M.journeyRequest:case e.M.samplingRequest:return!0;case e.M.securityContext:return i(`id`)&&n.id!==``;case e.M.journey:return(n.to===void 0||i(`to`))&&`journey`in n;case e.M.sampling:return i(`to`)&&`rules`in n;case e.M.records:return Array.isArray(n.records)&&(n.routingContextId===void 0||i(`routingContextId`))&&n.records.every(t=>!r.n(t)||!r.t(t.severityText)?!1:!Array.isArray(t.attributes)&&!Array.isArray(t.resource)&&/^\d+$/.test(t.timeUnixNano)&&(t.observedTimeUnixNano===void 0||/^\d+$/.test(t.observedTimeUnixNano))&&typeof t.traceId==`string`&&/^(?:[a-f\d]{32})?$/.test(t.traceId)&&typeof t.spanId==`string`&&/^(?:[a-f\d]{16})?$/.test(t.spanId)&&Number.isInteger(t.traceFlags)&&t.traceFlags>=0&&t.traceFlags<=255&&t.severityNumber===e.bn[t.severityText]);default:return!1}}function c(t){return{p:e.j,m:t}}function l(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/2`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var u=Symbol.for(e.dn),d=`null`;function f(e,t){return e===d?`The bus ignored ${t} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`:`The bus ignored ${t} from ${e}. If you own this origin, add it to bus.trustedOrigins.`}function p(){let e=location.ancestorOrigins;if(e&&e.length>0)return e.item(0);let t=document.referrer;if(t===``)return null;try{return new URL(t).origin}catch{return null}}function m(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[u]}catch{return null}if(typeof n?.busAccept!=`function`||n.busCanAccept&&!n.busCanAccept(window,location.origin))return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e,window)})},close(){i=!1}}}function h(e,t,n){if(typeof window>`u`||window.parent===window)return null;let r=location.origin;if(r===d)return n.report(`bus.untrusted_origin`,`This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`,{origin:r,type:`parent`}),null;let i=new Set([r,...t]),a=p();if(a===null||!i.has(a))return n.report(`bus.untrusted_origin`,a===null?`The origin of the parent frame is unknown. This context sends its own records.`:`The parent frame is on ${a}. This origin is not in bus.trustedOrigins. This context sends its own records.`,{origin:a??``,type:`parent`}),null;let o=new Set,s=t=>{let r=l(t.data);r&&t.source===window.parent&&(i.has(t.origin)?e(r,{link:`parent`,origin:t.origin,peer:t.source}):o.has(t.origin)||(o.add(t.origin),n.report(`bus.untrusted_origin`,f(t.origin,`a message`),{origin:t.origin,type:r.t.slice(0,48)})))};return addEventListener(`message`,s),{kind:`parent`,post(e){n.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(c(e),a)})},close(){removeEventListener(`message`,s)}}}function g(e,t,n,r,i){if(typeof window>`u`)return null;let a=new Set([location.origin,...t]);a.delete(d);let o=new Map,s=(e,t,a)=>{if(r&&!r(e,t)){o.delete(e);return}if(i&&!i(a,e))return;let s=e;s.closed?o.delete(e):n.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{s.postMessage(c(a),t)})},u=t=>{let i=l(t.data);if(!i||window.parent!==window&&t.source===window.parent)return;if(!r&&!a.has(t.origin)){n.report(`bus.untrusted_origin`,f(t.origin,`a message`),{origin:t.origin,type:i.t.slice(0,48)});return}if(r&&!r(t.source,t.origin))return;let{source:c,origin:u}=t;c&&o.set(c,u),e(i,{link:`children`,origin:u,peer:c??void 0,reply:c?e=>{s(c,u,e)}:void 0})};return addEventListener(`message`,u),{kind:`children`,post(e){for(let[t,n]of o)s(t,n,e)},close(){removeEventListener(`message`,u),o.clear()}}}function _(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let i=n.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new r(e));return i?(i.onmessage=e=>{let n=l(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{i.postMessage(c(e))})},close(){n.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{i.close()})}}):null}function v(e,t,n,r){let a=i.t()?.InterApplicationBus;if(!a)return null;if(!t)return r.report(`openfin.unavailable`,`OpenFin gives no application uuid. The InterApplicationBus link stays closed.`),null;let o=`${e}.${t}`;return r.guardAsync(`bus.send_failed`,`The InterApplicationBus.subscribe call failed.`,()=>a.subscribe({uuid:t},o,(e,t,r)=>{let i=l(e);i&&n(i,{link:`openfin`,origin:`openfin`,peer:t&&r?`${t}:${r}`:void 0})})),{kind:`openfin`,post(e){r.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>a.publish(o,c(e)))},close(){}}}function y(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=l(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`The postMessage call of the worker failed.`,()=>{r(c(e))})},close(){}})}function b(e,t,n){let r=n=>{let r=l(n.data);r&&t(r,{link:`worker`,origin:`same-origin`,peer:e})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(c(t))})},close(){e.removeEventListener(`message`,r)}}}var x={timeoutMs:e.k,maxAttempts:3},S=[`children`,`direct`,`worker`],C=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;sources=new Map;rates=new WeakMap;channelRates=new Map;directReplies=new Map;mayPost(t,n){let r=this.sources.get(n)?.permissions;return r?t.t===e.M.journey?r.includes(`journey:read`):t.t===e.M.journeyRequest?r.includes(`journey:write`):t.t!==e.M.sampling||r.includes(`sampling:read`):this.config.bus.sourcePolicy===`trusted-origin`}registerFrame(e,t){let n=typeof HTMLIFrameElement>`u`?void 0:HTMLIFrameElement,r=n&&e instanceof n?e.contentWindow:e;if(!r||new URL(t.origin).origin!==t.origin||t.origin===`null`)throw Error(`A frame registration requires a window and an exact origin.`);let i={...t,permissions:[...t.permissions??[`records`]]};return this.sources.set(r,i),this.ensureChildrenLink(),()=>{this.sources.get(r)===i&&this.sources.delete(r)}}isRegistered(e,t){if(!e)return!1;let n=this.sources.get(e);return n?n.origin===t:this.config.bus.sourcePolicy!==`registered`&&t!==`null`&&(t===location.origin||this.config.bus.trustedOrigins.includes(t))}rotateContext(){this.passContext(this.role===`sender`)}passContext(t){let n={t:e.M.securityContext,from:this.contextId,id:this.config.securityContext.id};this.postOver(`children`,n),this.postOver(`worker`,n),this.postToDirectChildren(n),t&&this.postOver(`openfin`,n)}postToDirectChildren(e){for(let[t,n]of this.directReplies){let r=n.deref();!r||t.closed||!this.isRegistered(t,location.origin)?this.directReplies.delete(t):this.diagnostics.guard(`bus.send_failed`,`The reply to a direct child failed.`,()=>{r(e,{link:`direct`,origin:`same-origin`,peer:t})})}}keepDirectReply(e,t){for(let e of this.directReplies.keys())e.closed&&this.directReplies.delete(e);this.directReplies.set(e,new WeakRef(t))}role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;rulesPoll;destroyed=!1;ownerId=null;ownerPeer;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=x){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}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,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.announce(),this.role;this.openControlLinks();let t=m(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,await this.handshake(t),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.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.announce(),this.role}sendRecords(t){let{maxRecordsPerMessage:n,maxMessageBytes:r}=this.config.bus,i=new TextEncoder,a=e=>r?i.encode(JSON.stringify(e)).length:0,o=t=>({t:e.M.records,from:this.contextId,records:t,routingContextId:this.config.securityContext.id||void 0}),s=a(o([])),c=[],l=s;for(let e of t){let t=a(e);if(r&&s+t>r){this.diagnostics.count(`bus.rejected_message`);continue}let i=+(c.length>0);(n&&c.length>=n||r&&l+i+t>r)&&(this.upstream?.post(o(c)),c=[],l=s),l+=+(c.length>0)+t,c.push(e)}c.length>0&&this.upstream?.post(o(c))}acceptDirect(t,n,r){let i={link:`direct`,origin:`same-origin`,peer:r},a={...i,reply:e=>{n(e,i)}};this.acceptsMessage(t,a,!0)&&t.from!==this.contextId&&(r&&this.keepDirectReply(r,n),t.t===e.M.samplingRequest?n(this.rulesAnswer(t.from),i):(t.t===e.M.records&&!this.awaitingWelcome&&t.routingContextId!==this.config.securityContext.id&&n({t:e.M.securityContext,from:this.contextId,id:this.config.securityContext.id},i),this.routeMessage(t,a)))}attachWorker(e,t={}){let n={...t,permissions:[...t.permissions??[`records`]]};this.sources.set(e,n);let r=b(e,this.receive,this.diagnostics),i={...r,post:t=>{this.mayPost(t,e)&&r.post(t)}};return this.links.push(i),()=>{i.close();let t=this.links.indexOf(i);t>=0&&this.links.splice(t,1),this.sources.get(e)===n&&this.sources.delete(e)}}broadcastJourney(t){this.postJourney({t:e.M.journey,from:this.contextId,journey:t})}destroy(){this.sources.clear(),this.directReplies.clear(),this.destroyed=!0,clearInterval(this.rulesPoll),this.rulesPoll=void 0;for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.ownerId=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}postJourney(e){for(let t of this.allLinks())this.journeyLink(t.kind)&&t.post(e)}receive=(e,t)=>{let n=t.link===`children`||t.link===`worker`;this.acceptsMessage(e,t,n)&&this.routeMessage(e,t)};acceptsMessage(e,t,n){if(this.destroyed)return!1;let r;try{r=this.passesChecks(e,t,n)}catch{r=!1}return r||this.diagnostics.count(`bus.rejected_message`),r}passesChecks(t,n,r){let{bus:i}=this.config,o=typeof n.peer==`object`?this.sources.get(n.peer):void 0;if(r&&i.sourcePolicy===`registered`&&!o)return!1;let c=typeof n.peer==`object`?n.peer:void 0,l=typeof n.peer==`string`?n.peer:n.link,u=Date.now(),d=(c?this.rates.get(c):this.channelRates.get(l))??{start:u,count:0};if(c)this.rates.set(c,d);else{for(let[e,t]of this.channelRates)a.n(t,1e3,u)&&this.channelRates.delete(e);if(i.maxTrackedSources&&this.channelRates.size>=i.maxTrackedSources&&!this.channelRates.has(l))return!1;this.channelRates.set(l,d)}if(!a.t(d,i.maxMessagesPerSecond||1/0,1e3))return!1;let f=JSON.stringify(t,(e,t)=>{if(i.validation===`strict`&&typeof t==`number`&&!Number.isFinite(t))throw Error(`Non-finite value`);return t});if(i.maxMessageBytes&&new TextEncoder().encode(f).length>i.maxMessageBytes||i.validation===`strict`&&!s(t)||t.t===e.M.records&&i.maxRecordsPerMessage&&t.records.length>i.maxRecordsPerMessage)return!1;if(o){let n=t.t===e.M.records?`records`:t.t===e.M.journey?`journey:write`:t.t===e.M.journeyRequest?`journey:read`:t.t===e.M.samplingRequest?`sampling:read`:void 0;if(n&&!o.permissions?.includes(n))return!1}return r&&(t.t===e.M.sampling||t.t===e.M.securityContext)?!1:i.sourcePolicy!==`registered`||n.link!==`broadcast`||t.t!==e.M.records}routeMessage(t,n){if(t.from!==this.contextId)switch(t.t){case e.M.hello:this.canOwn(n.link)&&this.answer(n,{t:e.M.welcome,from:this.contextId,to:t.from,tabId:this.tabId,routingContextId:this.awaitingWelcome?void 0:this.config.securityContext.id||void 0});break;case e.M.welcome:if(t.to!==this.contextId)break;if(this.awaitingWelcome?.link===n.link||this.upstream?.kind===n.link&&this.ownerId===null){this.ownerId=t.from,this.ownerPeer=n.peer;let e=this.config.securityContext.id;if(t.routingContextId&&this.handlers.onSecurityContext?.(t.routingContextId)===!1)break;this.config.securityContext.id!==e&&this.passContext(!1),this.awaitingWelcome?.settle(!0)}break;case e.M.records:if(this.config.securityContext.isolation&&this.config.securityContext.id&&t.routingContextId!==this.config.securityContext.id){this.diagnostics.count(`security.context_mismatch`);break}this.role===`sender`?this.handlers.onRecords(t.records):this.upstream&&this.canRelay(n.link)&&this.upstream.post(t);break;case e.M.securityContext:n.link===this.upstream?.kind&&this.ownerId===t.from&&this.ownerPeer===n.peer&&this.handlers.onSecurityContext?.(t.id)!==!1&&this.rotateContext();break;case e.M.journey:this.acceptsJourney(t,n)&&this.applyJourney(t.journey);break;case e.M.journeyRequest:{let r=this.handlers.onJourneyRequest();r&&this.journeyLink(n.link)&&this.answer(n,{t:e.M.journey,from:this.contextId,to:t.from,journey:r});break}case e.M.samplingRequest:(this.role===`forwarder`?n.link!==this.upstream?.kind:this.canOwn(n.link))&&this.answer(n,this.rulesAnswer(t.from));break;case e.M.sampling:this.acceptsRules(t.to,n)&&this.applyRules(t.rules);break;case e.M.tab:n.link===`broadcast`&&t.tabId===this.tabId&&this.contextId>t.from&&this.handlers.onTabConflict()}}answer(e,t){e.reply?e.reply(t):this.postOver(e.link,t)}canRelay(e){return e===`direct`||e!==this.upstream?.kind}canOwn(e){return this.role!==`sender`&&this.ownerId===null?!1:e===`openfin`?this.role===`sender`&&this.isOpenFinProvider:S.includes(e)}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=i.t()?.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?y(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:h(this.receive,this.config.bus.trustedOrigins,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isWorker||this.ensureChildrenLink(),this.platform.isTopLevelDocument&&t(_(e.O,this.receive,this.diagnostics)),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureChildrenLink(){if(this.links.some(e=>e.kind===`children`))return;let e=g(this.receive,this.config.bus.trustedOrigins,this.diagnostics,(e,t)=>{let n=this.isRegistered(e,t);if(!n){this.diagnostics.count(`bus.rejected_message`);let n=e!==null&&this.sources.has(e),r=t===location.origin||this.config.bus.trustedOrigins.includes(t);(n||!r)&&this.diagnostics.report(`bus.untrusted_origin`,`The bus rejected a message from an untrusted origin.`)}return n},(e,t)=>this.mayPost(e,t));e&&this.links.push(e)}ensureOpenFinLink(){return this.openFinLink??=v(e.O,this.platform.openfinUuid,this.receive,this.diagnostics),this.openFinLink}handshake(t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,this.awaitingWelcome=null,clearTimeout(a),n(e))};this.awaitingWelcome={link:t.kind,settle:i};let a=setTimeout(()=>{i(!1)},this.handshakeOptions.timeoutMs);o.r(a),t.post({t:e.M.hello,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:e.M.tab,from:this.contextId,tabId:this.tabId}),this.upstream&&this.ownerId===null&&this.upstream.post({t:e.M.hello,from:this.contextId,tabId:this.tabId}),this.postJourney({t:e.M.journeyRequest,from:this.contextId}),this.pollRules(),this.passContext(!1)}journeyScope(){let{scope:e}=this.config.journey;if(e!==`auto`)return e;let{platform:t}=this.platform;return t===`openfin`||t===`openfin_web`?`origin`:`tab`}journeyLink(e){let t=this.journeyScope();return t===`context`?!1:t===`origin`||e!==`broadcast`}acceptsJourney(e,t){return!this.journeyLink(t.link)||e.to!==void 0&&e.to!==this.contextId?!1:this.journeyScope()===`origin`||this.fromOwner(e.from,t.link)&&(this.ownerPeer===void 0||this.ownerPeer===t.peer)}fromOwner(e,t){return this.role!==`forwarder`||t!==this.upstream?.kind?!1:this.ownerId===null||e===this.ownerId}applyJourney(e){if(e===null){this.handlers.onJourney(null);return}let n=t.r(e);n===null?this.diagnostics.report(`record.dropped_malformed`,`The bus dropped a journey message. Its payload is not a journey.`,{type:`journey`}):this.handlers.onJourney(n)}rulesAnswer(t){let n=this.handlers.remote.sampling?.wire()??null;return{t:e.M.sampling,from:this.contextId,to:t,rules:n}}acceptsRules(e,t){if(this.role!==`forwarder`||e!==this.contextId||t.link!==this.upstream?.kind)return!1;let{origin:n}=t;return t.link===`parent`&&n!==location.origin&&!this.config.bus.trustedOrigins.includes(n)?(this.diagnostics.report(`bus.untrusted_origin`,`The bus ignored sampling rules from ${n}. If you own this origin, add it to bus.trustedOrigins.`,{origin:n,type:`sampling`}),!1):this.ownerPeer===void 0||this.ownerPeer===t.peer}applyRules(e){if(e===null){n.t(this.handlers.remote,this.config,null);return}let t=n.n(e,this.diagnostics);t&&n.t(this.handlers.remote,this.config,t)}pollRules(){let{upstream:t}=this;if(this.destroyed||this.role!==`forwarder`||!t)return;let n=()=>{this.config.sampling.remote&&t.post({t:e.M.samplingRequest,from:this.contextId})};n(),this.rulesPoll=setInterval(n,e.Xt),o.r(this.rulesPoll)}};exports.Bus=C;
2
+ //# sourceMappingURL=bus-VWlmM5xs.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus-VWlmM5xs.cjs","names":["BUS_TYPE","isLogRecord","isLogLevel","SEVERITY_NUMBER","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","getFin","BUS_HANDSHAKE_TIMEOUT_MS","BUS_TYPE","windowEnded","countInWindow","getFin","BUS_CHANNEL_NAME","parseJourney","parseRemoteRules","REMOTE_SAMPLING_POLL_MS","require_constants","require_journey","require_remote_rules","require_log_record","require_openfin","require_fixed_window","require_deadline","validMessage","value","m","text","key","r","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","OPAQUE_ORIGIN","untrustedText","origin","what","parentOrigin","ancestors","referrer","createDirectLink","host","target","open","diagnostics","receive","createParentLink","self","trusted","trustedOrigins","reported","onMessage","event","createChildrenLink","sources","send","authorize","source","mayPost","answer","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","uuid","name","createOwnerLink","scope","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","permissions","peer","element","frame","options","registration","openFin","ref","reply","known","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","encoder","size","maxMessageBytes","chunk","bytes","record","records","recordBytes","comma","maxRecordsPerMessage","plain","link","index","child","accepted","object","now","rate","entry","encoded","permission","before","current","configured","me","push","registered","settled","finish","timer","resolve","result","from","payload","journey","rules","to","update","upstream","ask"],"sources":["../src/bus/validation.ts","../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/bus/validation.ts\n//\n// Checks the required fields and values of messages from another context.\n\nimport type { BusMessage } from \"../models/bus\";\nimport { isLogLevel, isLogRecord } from \"../models/log-record\";\nimport { BUS_TYPE, SEVERITY_NUMBER } from \"../constants\";\n\n/**\n * Checks the fields required by each bus message type. unwrap() checks the envelope only.\n * @param value Message to check.\n * @returns True if the message has the required fields and values.\n */\nexport function validMessage(value: unknown): value is BusMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const m = value as Record<string, unknown>;\n if (typeof m.from !== \"string\" || !m.from || typeof m.t !== \"string\") return false;\n const text = (key: string): boolean => typeof m[key] === \"string\";\n switch (m.t) {\n case BUS_TYPE.hello:\n case BUS_TYPE.tab:\n return text(\"tabId\");\n case BUS_TYPE.welcome:\n return (\n text(\"to\") &&\n text(\"tabId\") &&\n (m.routingContextId === undefined || text(\"routingContextId\"))\n );\n case BUS_TYPE.journeyRequest:\n case BUS_TYPE.samplingRequest:\n return true;\n case BUS_TYPE.securityContext:\n return text(\"id\") && m.id !== \"\";\n case BUS_TYPE.journey:\n return (m.to === undefined || text(\"to\")) && \"journey\" in m;\n case BUS_TYPE.sampling:\n return text(\"to\") && \"rules\" in m;\n case BUS_TYPE.records:\n return (\n Array.isArray(m.records) &&\n (m.routingContextId === undefined || text(\"routingContextId\")) &&\n m.records.every((r: unknown) => {\n if (!isLogRecord(r) || !isLogLevel(r.severityText)) return false;\n return (\n !Array.isArray(r.attributes) &&\n !Array.isArray(r.resource) &&\n /^\\d+$/.test(r.timeUnixNano) &&\n (r.observedTimeUnixNano === undefined || /^\\d+$/.test(r.observedTimeUnixNano)) &&\n typeof r.traceId === \"string\" &&\n /^(?:[a-f\\d]{32})?$/.test(r.traceId) &&\n typeof r.spanId === \"string\" &&\n /^(?:[a-f\\d]{16})?$/.test(r.spanId) &&\n Number.isInteger(r.traceFlags) &&\n r.traceFlags >= 0 &&\n r.traceFlags <= 255 &&\n r.severityNumber === SEVERITY_NUMBER[r.severityText]\n );\n })\n );\n default:\n return false;\n }\n}\n","// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL, type BUS_TYPE } from \"../constants\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Permissions of one child window or worker. The handshake needs no separate permission. */\nexport type BusPermission = \"records\" | \"journey:read\" | \"journey:write\" | \"sampling:read\";\nexport interface SourceOptions {\n /** Permissions of this source. Without this list, the source can send records only. */\n permissions?: BusPermission[];\n}\n\n/** Origin and permissions for one child frame registration. */\nexport interface FrameOptions extends SourceOptions {\n /** Expected window origin, with its scheme and port. The origin must match exactly. */\n origin: string;\n}\n\n/** Delivery role. It tells if this context sends its records or forwards them upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel. The bus uses it to route incoming and outgoing messages.\n * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe\n * looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Source identity from the transport. The source does not supply it in message.from. */\n peer?: object | string;\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 /** Sends an answer to this source only. A link that cannot address one source omits it. */\n reply?: (message: BusMessage) => void;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: typeof BUS_TYPE.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 | {\n t: typeof BUS_TYPE.welcome;\n from: string;\n to: string;\n tabId: string;\n routingContextId?: string;\n }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: typeof BUS_TYPE.records; from: string; records: LogRecord[]; routingContextId?: string }\n /** Delivery context update. Only the owner from the handshake can send it to its children. */\n | { t: typeof BUS_TYPE.securityContext; from: string; id: string }\n /**\n * Journey update, or the answer to a journey question. An answer holds the address of the\n * context that asked in `to`. The payload comes from another realm. The receiver parses it.\n */\n | { t: typeof BUS_TYPE.journey; from: string; to?: string; journey: unknown }\n /** Query requesting active journey state from connected peers. */\n | { t: typeof BUS_TYPE.journeyRequest; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: typeof BUS_TYPE.tab; from: string; tabId: string }\n /** Request of a forwarder for the remote sampling rules in force. */\n | { t: typeof BUS_TYPE.samplingRequest; from: string }\n /**\n * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field\n * holds the address of the forwarder that asked. The receiver validates `rules` again.\n * Null rules end the copy of the forwarder.\n */\n | { t: typeof BUS_TYPE.sampling; from: string; to: string; rules: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A\n * document gets `message` events from all embedded content on the page. This\n * includes analytics tags, video players and extensions. Without the tag check,\n * the bus parses a message from a video player as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { BUS_TYPE_DETAIL_MAX_CHARS, RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\nimport { getFin } from \"../utils/openfin\";\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, source?: Window): void;\n /**\n * Checks if the parent permits a direct link from the child window.\n * @param source Child window.\n * @param origin Origin of the child window.\n * @returns True if the parent permits this source.\n */\n busCanAccept?: (source: Window, origin: string) => boolean;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst OPAQUE_ORIGIN = \"null\";\n\n/** Location with the ancestor list that Chromium and WebKit give. */\ninterface LocationWithAncestors {\n origin: string;\n ancestorOrigins?: { length: number; item: (index: number) => string | null };\n}\n\n/**\n * Builds the message for an ignored message from an untrusted origin.\n * @param origin Origin of the sender.\n * @param what What the bus ignored, for example \"a message\".\n * @returns The message. A sandboxed sender gets the fix for its frame.\n */\nfunction untrustedText(origin: string, what: string): string {\n if (origin === OPAQUE_ORIGIN) {\n return `The bus ignored ${what} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`;\n }\n\n return `The bus ignored ${what} from ${origin}. If you own this origin, add it to bus.trustedOrigins.`;\n}\n\n/**\n * Reads the origin of the parent frame. A cross-origin parent does not give its location.\n * @returns The origin, or null when the browser does not give it.\n */\nfunction parentOrigin(): string | null {\n const ancestors = (location as LocationWithAncestors).ancestorOrigins;\n if (ancestors && ancestors.length > 0) {\n return ancestors.item(0);\n }\n\n // Firefox has no ancestorOrigins. The referrer of a frame is the page that loaded it.\n // A Referrer-Policy of no-referrer gives \"\". The caller reports an unknown origin.\n const referrer = document.referrer;\n if (referrer === \"\") {\n return null;\n }\n\n try {\n return new URL(referrer).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n if (host.busCanAccept && !host.busCanAccept(window, location.origin)) return null;\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, window);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to a parent window on a trusted origin. Records hold user data.\n * A page on another origin that frames this app must not get them.\n * @param receive Callback for incoming parent messages.\n * @param trustedOrigins Origins of a parent that can get the records, in addition to this origin.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to the parent window, or null at the top level or with an untrusted parent.\n * With null, this context sends its own records.\n */\nexport function createParentLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n // A sandboxed frame has an opaque origin. No parent can list it in its own trust list.\n const self = location.origin;\n if (self === OPAQUE_ORIGIN) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n 'This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.',\n { origin: self, type: \"parent\" },\n );\n return null;\n }\n\n const trusted = new Set([self, ...trustedOrigins]);\n const target = parentOrigin();\n if (target === null || !trusted.has(target)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n target === null\n ? \"The origin of the parent frame is unknown. This context sends its own records.\"\n : `The parent frame is on ${target}. This origin is not in bus.trustedOrigins. This context sends its own records.`,\n { origin: target ?? \"\", type: \"parent\" },\n );\n return null;\n }\n\n // Report each untrusted origin one time. A hostile parent can send many messages.\n const reported = new Set<string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message || event.source !== window.parent) {\n return;\n }\n\n // The parent can navigate to another origin after this frame loads.\n if (!trusted.has(event.origin)) {\n if (!reported.has(event.origin)) {\n reported.add(event.origin);\n // The parent sets message.t. Keep it out of the message text. Cut it in the detail.\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n }\n return;\n }\n\n receive(message, { link: \"parent\", origin: event.origin, peer: event.source });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // Target the trusted origin, not \"*\". The browser drops the message if the parent\n // navigated to another origin.\n window.parent.postMessage(envelope(message), target);\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n authorize?: (source: MessageEventSource | null, origin: string) => boolean,\n mayPost?: (message: BusMessage, source: MessageEventSource) => boolean,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // A sandboxed page has the opaque origin \"null\". Each sandboxed child also has it.\n const trusted = new Set([location.origin, ...trustedOrigins]);\n trusted.delete(OPAQUE_ORIGIN);\n\n // The map keeps the origin of each source.\n // A child that navigates must not get the ids of its previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n /**\n * Posts one message to one child. It removes a child that is closed or no longer permitted.\n * @param source Child window.\n * @param origin Last known origin of the child.\n * @param message Message to send.\n */\n const send = (source: MessageEventSource, origin: string, message: BusMessage): void => {\n if (authorize && !authorize(source, origin)) {\n sources.delete(source);\n return;\n }\n if (mayPost && !mayPost(message, source)) {\n return;\n }\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n return;\n }\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a child frame failed.\", () => {\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 const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n // A nested frame also receives the messages of its parent. The parent link owns them.\n if (window.parent !== window && event.source === window.parent) {\n return;\n }\n if (!authorize && !trusted.has(event.origin)) {\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n return;\n }\n\n if (authorize && !authorize(event.source, event.origin)) return;\n const { source, origin } = event;\n if (source) {\n sources.set(source, origin);\n }\n // Answer only the asking child. A broadcast lets one child use up the budget of each sibling.\n receive(message, {\n link: \"children\",\n origin,\n peer: source ?? undefined,\n reply: source\n ? (answer) => {\n send(source, origin, answer);\n }\n : undefined,\n });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n send(source, origin, message);\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/**\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 iab = getFin()?.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, uuid, name) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, {\n link: \"openfin\",\n origin: \"openfin\",\n peer: uuid && name ? `${uuid}:${name}` : undefined,\n });\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\", peer: worker });\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 BUS_TYPE,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type Journey, parseJourney } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { SourceOptions, FrameOptions } from \"../models/bus\";\nimport { validMessage } from \"./validation\";\nimport type { JourneyScope, ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { getFin } from \"../utils/openfin\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { countInWindow, windowEnded } from \"../utils/fixed-window\";\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 /** Adopts the delivery context of the owner. False refuses a different identity. */\n onSecurityContext?: (id: string) => boolean;\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Journey scope after the bus resolves \"auto\". */\ntype ResolvedScope = Exclude<JourneyScope, \"auto\">;\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Window and worker registrations with their permissions. */\n private readonly sources = new Map<object, SourceOptions & { origin?: string }>();\n /** Message counts for each window and worker in the current rate window. */\n private readonly rates = new WeakMap<object, { start: number; count: number }>();\n /** Message counts for each named source or link in the current rate window. */\n private readonly channelRates = new Map<string, { start: number; count: number }>();\n /** Reply of each same-origin child on the direct link. A weak reply frees a navigated frame. */\n private readonly directReplies = new Map<Window, WeakRef<Receive>>();\n\n /**\n * Checks if this source can receive a control message. A window can read a message\n * even when its address names another window.\n * @param message Control message to send.\n * @param peer Window or worker that receives the message.\n * @returns True if the source has the required permission.\n */\n private mayPost(message: BusMessage, peer: object): boolean {\n const permissions = this.sources.get(peer)?.permissions;\n if (!permissions) return this.config.bus.sourcePolicy === \"trusted-origin\";\n if (message.t === BUS_TYPE.journey) return permissions.includes(\"journey:read\");\n if (message.t === BUS_TYPE.journeyRequest) return permissions.includes(\"journey:write\");\n if (message.t === BUS_TYPE.sampling) return permissions.includes(\"sampling:read\");\n return true;\n }\n\n /**\n * Registers one child window and its permissions.\n * @param frame Frame element or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n // Use instanceof, not \"in\". The \"in\" operator throws on a cross-origin window.\n const element = typeof HTMLIFrameElement === \"undefined\" ? undefined : HTMLIFrameElement;\n const source = element && frame instanceof element ? frame.contentWindow : frame;\n if (!source || new URL(options.origin).origin !== options.origin || options.origin === \"null\")\n throw new Error(\"A frame registration requires a window and an exact origin.\");\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(source, registration);\n this.ensureChildrenLink();\n return () => {\n if (this.sources.get(source) === registration) this.sources.delete(source);\n };\n }\n\n /**\n * Checks if a source is permitted at the given origin.\n * @param source Window or port that sent the message.\n * @param origin Origin supplied by the transport.\n * @returns True if the current source policy permits this source.\n */\n isRegistered(source: object | null, origin: string): boolean {\n if (!source) return false;\n const registration = this.sources.get(source);\n // A registration binds its exact origin under each policy. It needs no trustedOrigins entry.\n if (registration) {\n return registration.origin === origin;\n }\n if (this.config.bus.sourcePolicy === \"registered\") {\n return false;\n }\n return (\n origin !== \"null\" &&\n (origin === location.origin || this.config.bus.trustedOrigins.includes(origin))\n );\n }\n\n /**\n * Sends the new context id to child frames, workers and OpenFin views. Other tabs keep their\n * own context.\n */\n rotateContext(): void {\n // Only the owner sends on the OpenFin link. Without this message, each view keeps the old id.\n this.passContext(this.role === \"sender\");\n }\n\n /**\n * Sends the context id to child frames and workers.\n * @param openFin True to send it to OpenFin views too.\n */\n private passContext(openFin: boolean): void {\n const message: BusMessage = {\n t: BUS_TYPE.securityContext,\n from: this.contextId,\n id: this.config.securityContext.id,\n };\n this.postOver(\"children\", message);\n this.postOver(\"worker\", message);\n this.postToDirectChildren(message);\n if (openFin) {\n this.postOver(\"openfin\", message);\n }\n }\n\n /**\n * Sends a security context message to each same-origin child on the direct link.\n * It drops a child that is closed, freed or no longer permitted.\n * @param message Security context message.\n */\n private postToDirectChildren(message: BusMessage): void {\n for (const [peer, ref] of this.directReplies) {\n const reply = ref.deref();\n if (!reply || peer.closed || !this.isRegistered(peer, location.origin)) {\n this.directReplies.delete(peer);\n continue;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"The reply to a direct child failed.\", () => {\n reply(message, { link: \"direct\", origin: \"same-origin\", peer });\n });\n }\n }\n\n /**\n * Keeps the reply of a direct child for the next context id. It drops each closed child.\n * A removed frame then does not keep its document in memory.\n * @param peer Window of the child.\n * @param reply Reply callback of the child.\n */\n private keepDirectReply(peer: Window, reply: Receive): void {\n for (const known of this.directReplies.keys()) {\n if (known.closed) {\n this.directReplies.delete(known);\n }\n }\n\n this.directReplies.set(peer, new WeakRef(reply));\n }\n\n /** Current bus role. The default is \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** True if this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(). A handshake that ends later must not start a timer. */\n private destroyed = false;\n /** Context id of the owner that answered the handshake. Null with no handshake. */\n private ownerId: string | null = null;\n /** Transport identity of the owner from the handshake. */\n private ownerPeer?: object | string;\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 /**\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 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.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 await this.handshake(direct);\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.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.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 const { maxRecordsPerMessage, maxMessageBytes } = this.config.bus;\n const encoder = new TextEncoder();\n const size = (value: unknown): number =>\n maxMessageBytes ? encoder.encode(JSON.stringify(value)).length : 0;\n const message = (chunk: LogRecord[]): BusMessage => ({\n t: BUS_TYPE.records,\n from: this.contextId,\n records: chunk,\n routingContextId: this.config.securityContext.id || undefined,\n });\n\n // Measure each record one time. A message is the empty envelope, its records and the commas.\n const envelope = size(message([]));\n let chunk: LogRecord[] = [];\n let bytes = envelope;\n\n for (const record of records) {\n const recordBytes = size(record);\n if (maxMessageBytes && envelope + recordBytes > maxMessageBytes) {\n this.diagnostics.count(\"bus.rejected_message\");\n continue;\n }\n\n const comma = chunk.length > 0 ? 1 : 0;\n if (\n (maxRecordsPerMessage && chunk.length >= maxRecordsPerMessage) ||\n (maxMessageBytes && bytes + comma + recordBytes > maxMessageBytes)\n ) {\n this.upstream?.post(message(chunk));\n chunk = [];\n bytes = envelope;\n }\n\n bytes += (chunk.length > 0 ? 1 : 0) + recordBytes;\n chunk.push(record);\n }\n\n if (chunk.length > 0) {\n this.upstream?.post(message(chunk));\n }\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, peer?: Window): void {\n // The child gets the plain source. The reply field stays on this side.\n const plain: MessageSource = { link: \"direct\", origin: \"same-origin\", peer };\n const source: MessageSource = {\n ...plain,\n reply: (answer) => {\n reply(answer, plain);\n },\n };\n if (!this.acceptsMessage(message, source, true)) return;\n if (message.from === this.contextId) {\n return;\n }\n\n // A rotation sends the new id with this reply. The child then does not send a stale batch.\n if (peer) {\n this.keepDirectReply(peer, reply);\n }\n\n // A direct link has no channel from the parent to the child. The parent answers here. The\n // forwarder rule in routeMessage() refuses a sampling question on a direct link.\n if (message.t === BUS_TYPE.samplingRequest) {\n reply(this.rulesAnswer(message.from), plain);\n return;\n }\n // A context that waits for its own owner has no final id. It sends no id.\n if (\n message.t === BUS_TYPE.records &&\n !this.awaitingWelcome &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n reply(\n { t: BUS_TYPE.securityContext, from: this.contextId, id: this.config.securityContext.id },\n plain,\n );\n }\n this.routeMessage(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, options: SourceOptions = {}): () => void {\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(worker, registration);\n const raw = createWorkerLink(worker, this.receive, this.diagnostics);\n const link: Link = {\n ...raw,\n post: (message) => {\n if (this.mayPost(message, worker)) raw.post(message);\n },\n };\n this.links.push(link);\n return () => {\n link.close();\n const index = this.links.indexOf(link);\n if (index >= 0) this.links.splice(index, 1);\n if (this.sources.get(worker) === registration) this.sources.delete(worker);\n };\n }\n\n /**\n * Sends journey state changes over each link of the journey scope.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.postJourney({ t: BUS_TYPE.journey, from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.sources.clear();\n this.directReplies.clear();\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.ownerId = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Sends a journey message over each link of the journey scope. */\n private postJourney(message: BusMessage): void {\n for (const link of this.allLinks()) {\n if (this.journeyLink(link.kind)) {\n link.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n // A message on the direct link here is an answer from the parent. acceptDirect() takes the\n // messages of a direct child. Thus only the children and worker links carry child traffic.\n const child = source.link === \"children\" || source.link === \"worker\";\n if (this.acceptsMessage(message, source, child)) {\n this.routeMessage(message, source);\n }\n };\n\n /**\n * Checks the source, the message limits and the message shape before delivery.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the bus can accept the message.\n */\n private acceptsMessage(message: BusMessage, source: MessageSource, child: boolean): boolean {\n if (this.destroyed) {\n return false;\n }\n\n let accepted: boolean;\n try {\n accepted = this.passesChecks(message, source, child);\n } catch {\n // A value that JSON cannot encode, or a non-finite number under strict validation.\n // The count below reports this rejection.\n accepted = false;\n }\n\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n }\n return accepted;\n }\n\n /**\n * Runs the source, budget, shape and permission checks. Each check returns false, not an error.\n * A flood of rejected messages then makes no stack traces.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the message passes each check.\n */\n private passesChecks(message: BusMessage, source: MessageSource, child: boolean): boolean {\n const { bus } = this.config;\n const registration =\n typeof source.peer === \"object\" ? this.sources.get(source.peer) : undefined;\n if (child && bus.sourcePolicy === \"registered\" && !registration) {\n return false;\n }\n\n const object = typeof source.peer === \"object\" ? source.peer : undefined;\n const key = typeof source.peer === \"string\" ? source.peer : source.link;\n const now = Date.now();\n const rate = (object ? this.rates.get(object) : this.channelRates.get(key)) ?? {\n start: now,\n count: 0,\n };\n if (object) {\n this.rates.set(object, rate);\n } else {\n for (const [peer, entry] of this.channelRates) {\n if (windowEnded(entry, 1000, now)) {\n this.channelRates.delete(peer);\n }\n }\n if (\n bus.maxTrackedSources &&\n this.channelRates.size >= bus.maxTrackedSources &&\n !this.channelRates.has(key)\n ) {\n return false;\n }\n this.channelRates.set(key, rate);\n }\n\n // Count with no limit when the limit is 0. The window of a named source then stays current.\n if (!countInWindow(rate, bus.maxMessagesPerSecond || Infinity, 1000)) {\n return false;\n }\n\n const encoded = JSON.stringify(message, (_key, value: unknown) => {\n if (bus.validation === \"strict\" && typeof value === \"number\" && !Number.isFinite(value)) {\n throw new Error(\"Non-finite value\");\n }\n return value;\n });\n if (bus.maxMessageBytes && new TextEncoder().encode(encoded).length > bus.maxMessageBytes) {\n return false;\n }\n if (bus.validation === \"strict\" && !validMessage(message)) {\n return false;\n }\n if (\n message.t === BUS_TYPE.records &&\n bus.maxRecordsPerMessage &&\n message.records.length > bus.maxRecordsPerMessage\n ) {\n return false;\n }\n\n if (registration) {\n const permission =\n message.t === BUS_TYPE.records\n ? \"records\"\n : message.t === BUS_TYPE.journey\n ? \"journey:write\"\n : message.t === BUS_TYPE.journeyRequest\n ? \"journey:read\"\n : message.t === BUS_TYPE.samplingRequest\n ? \"sampling:read\"\n : undefined;\n if (permission && !registration.permissions?.includes(permission)) {\n return false;\n }\n }\n\n // Only an upstream owner can publish these control messages.\n if (child && (message.t === BUS_TYPE.sampling || message.t === BUS_TYPE.securityContext)) {\n return false;\n }\n\n // Under the registered policy, broadcast is a control channel. It carries no records.\n return !(\n bus.sourcePolicy === \"registered\" &&\n source.link === \"broadcast\" &&\n message.t === BUS_TYPE.records\n );\n }\n\n /**\n * Gives an accepted message to its handler or the upstream link.\n * @param message Message that passed the source and shape checks.\n * @param source Link and identity of the source.\n */\n private routeMessage(message: BusMessage, source: MessageSource): void {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case BUS_TYPE.hello:\n if (this.canOwn(source.link)) {\n // A context that waits for its own owner has only a temporary id. Send no id then.\n // announce() sends the final id when the role is known.\n this.answer(source, {\n t: BUS_TYPE.welcome,\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n routingContextId: this.awaitingWelcome\n ? undefined\n : this.config.securityContext.id || undefined,\n });\n }\n break;\n\n case BUS_TYPE.welcome:\n if (message.to !== this.contextId) {\n break;\n }\n if (\n this.awaitingWelcome?.link === source.link ||\n (this.upstream?.kind === source.link && this.ownerId === null)\n ) {\n // Keep the owner. Only it can set the journey of this context on a shared link.\n this.ownerId = message.from;\n this.ownerPeer = source.peer;\n const before = this.config.securityContext.id;\n if (\n message.routingContextId &&\n this.handlers.onSecurityContext?.(message.routingContextId) === false\n )\n break;\n // A child of this context can hold the old id. Send it the id of the owner. During a\n // handshake the role can still be \"sender\". Do not send on the OpenFin link here.\n if (this.config.securityContext.id !== before) {\n this.passContext(false);\n }\n this.awaitingWelcome?.settle(true);\n }\n break;\n\n case BUS_TYPE.records:\n if (\n this.config.securityContext.isolation &&\n this.config.securityContext.id &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n this.diagnostics.count(\"security.context_mismatch\");\n break;\n }\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 BUS_TYPE.securityContext:\n if (\n source.link === this.upstream?.kind &&\n this.ownerId === message.from &&\n this.ownerPeer === source.peer\n ) {\n if (this.handlers.onSecurityContext?.(message.id) !== false) this.rotateContext();\n }\n break;\n\n case BUS_TYPE.journey:\n if (this.acceptsJourney(message, source)) {\n this.applyJourney(message.journey);\n }\n break;\n\n case BUS_TYPE.journeyRequest: {\n const current = this.handlers.onJourneyRequest();\n // Address the answer. On a shared link, each other context ignores it.\n if (current && this.journeyLink(source.link)) {\n this.answer(source, {\n t: BUS_TYPE.journey,\n from: this.contextId,\n to: message.from,\n journey: current,\n });\n }\n break;\n }\n\n case BUS_TYPE.samplingRequest:\n // A forwarder answers only its own children. A sibling on its upstream link asks too.\n // A sibling answer on OpenFin gives N squared messages, and a stale copy can win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.answer(source, this.rulesAnswer(message.from));\n }\n break;\n\n case BUS_TYPE.sampling:\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case BUS_TYPE.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 * Answers the source of a message. A link that can address one source sends to it only.\n * @param source Link and identity of the source.\n * @param message Answer to send.\n */\n private answer(source: MessageSource, message: BusMessage): void {\n if (source.reply) {\n source.reply(message);\n return;\n }\n this.postOver(source.link, message);\n }\n\n /**\n * Tells if records from a link can go upstream. Records that go back on\n * their arrival link return to their sender. A direct link is an exception.\n * Each direct link is one call into one parent. Thus two direct links in a\n * chain are different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Returns true if this context can be the owner of the given link type. */\n private canOwn(link: LinkKind): boolean {\n // A forwarder that knows its owner owns its own children. It relays their records upstream.\n const owner = this.role === \"sender\" || this.ownerId !== null;\n if (!owner) {\n return false;\n }\n if (link === \"openfin\") {\n return this.role === \"sender\" && this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Finds if this context is the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = getFin()?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests if a cross-origin boundary blocks access to the parent window. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. Lint rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (!this.platform.isWorker) this.ensureChildrenLink();\n if (this.platform.isTopLevelDocument) {\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 /** Opens the link to child frames if it is not already open. */\n private ensureChildrenLink(): void {\n if (this.links.some((link) => link.kind === \"children\")) return;\n const link = createChildrenLink(\n this.receive,\n this.config.bus.trustedOrigins,\n this.diagnostics,\n (source, origin) => {\n const accepted = this.isRegistered(source, origin);\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n // A registered window that speaks from another origin is also untrusted. Without this\n // report, a registration with a wrong origin stops the frame with no named cause.\n const registered = source !== null && this.sources.has(source);\n const trusted =\n origin === location.origin || this.config.bus.trustedOrigins.includes(origin);\n if (registered || !trusted) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n \"The bus rejected a message from an untrusted origin.\",\n );\n }\n }\n return accepted;\n },\n (message, source) => this.mayPost(message, source),\n );\n if (link) this.links.push(link);\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: BUS_TYPE.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: BUS_TYPE.tab,\n from: this.contextId,\n tabId: this.tabId,\n });\n if (this.upstream && this.ownerId === null)\n this.upstream.post({ t: BUS_TYPE.hello, from: this.contextId, tabId: this.tabId });\n this.postJourney({ t: BUS_TYPE.journeyRequest, from: this.contextId });\n this.pollRules();\n // The role is final now. A child welcomed during the handshake got no id. Send it the final id.\n this.passContext(false);\n }\n\n /**\n * Resolves the journey scope. \"auto\" gives \"origin\" in OpenFin and \"tab\" in a browser.\n * @returns The scope in force.\n */\n private journeyScope(): ResolvedScope {\n const { scope } = this.config.journey;\n if (scope !== \"auto\") {\n return scope;\n }\n\n const { platform } = this.platform;\n return platform === \"openfin\" || platform === \"openfin_web\" ? \"origin\" : \"tab\";\n }\n\n /**\n * Tests if a link carries journey messages in the scope in force.\n * Only \"origin\" uses the broadcast link. That link reaches each tab of the origin.\n * @param link Link kind.\n * @returns True if the link carries journey messages.\n */\n private journeyLink(link: LinkKind): boolean {\n const scope = this.journeyScope();\n if (scope === \"context\") {\n return false;\n }\n\n return scope === \"origin\" || link !== \"broadcast\";\n }\n\n /**\n * Tests if this context adopts a journey message.\n * @param message Journey message.\n * @param source Link and origin of the message.\n * @returns True for a message on a journey link, to this context, from an accepted sender.\n * In \"tab\" scope, only the owner of a forwarder is an accepted sender.\n */\n private acceptsJourney(\n message: Extract<BusMessage, { t: typeof BUS_TYPE.journey }>,\n source: MessageSource,\n ): boolean {\n if (!this.journeyLink(source.link)) {\n return false;\n }\n\n if (message.to !== undefined && message.to !== this.contextId) {\n return false;\n }\n\n return (\n this.journeyScope() === \"origin\" ||\n (this.fromOwner(message.from, source.link) &&\n (this.ownerPeer === undefined || this.ownerPeer === source.peer))\n );\n }\n\n /**\n * Tests if a message comes from the upstream owner of this forwarder.\n * @param from Context id of the sender.\n * @param link Link kind of the message.\n * @returns True for the upstream link and, after a handshake, the owner that answered it.\n */\n private fromOwner(from: string, link: LinkKind): boolean {\n if (this.role !== \"forwarder\" || link !== this.upstream?.kind) {\n return false;\n }\n\n return this.ownerId === null || from === this.ownerId;\n }\n\n /**\n * Parses a journey payload from another realm and gives it to the runtime.\n * @param payload Journey, or null when the journey ended.\n */\n private applyJourney(payload: unknown): void {\n if (payload === null) {\n this.handlers.onJourney(null);\n return;\n }\n\n const journey = parseJourney(payload);\n if (journey === null) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n \"The bus dropped a journey message. Its payload is not a journey.\",\n { type: \"journey\" },\n );\n return;\n }\n\n this.handlers.onJourney(journey);\n }\n\n /**\n * Builds the answer to a sampling question. Null rules end the copy of the forwarder.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: BUS_TYPE.sampling, from: this.contextId, to, rules };\n }\n\n /**\n * Tests if this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link is not trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. It must not lower minLevel and read the records.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== location.origin &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return this.ownerPeer === undefined || this.ownerPeer === source.peer;\n }\n\n /**\n * Applies the rules of an answer. It ignores rules that are not valid.\n * @param raw Rules of the answer, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then at each poll interval.\n * A direct link cannot push the rules to a child. A poll works on each link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config at each poll. A later configure() can turn remote sampling on or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: BUS_TYPE.samplingRequest, from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":"A,kRAaA,SAAgBuB,EAAa,EAAqC,CAChE,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMC,EAAID,EACV,GAAI,OAAOC,EAAE,MAAS,UAAY,CAACA,EAAE,MAAQ,OAAOA,EAAE,GAAM,SAAU,MAAO,GAC7E,IAAMC,EAAQ,GAAyB,OAAOD,EAAEE,IAAS,SACzD,OAAQF,EAAE,EAAV,CACE,KAAKzB,EAAAA,EAAS,MACd,KAAKA,EAAAA,EAAS,IACZ,OAAO0B,EAAK,OAAO,EACrB,KAAK1B,EAAAA,EAAS,QACZ,OACE0B,EAAK,IAAI,GACTA,EAAK,OAAO,IACXD,EAAE,mBAAqB,IAAA,IAAaC,EAAK,kBAAkB,GAEhE,KAAK1B,EAAAA,EAAS,eACd,KAAKA,EAAAA,EAAS,gBACZ,MAAO,GACT,KAAKA,EAAAA,EAAS,gBACZ,OAAO0B,EAAK,IAAI,GAAKD,EAAE,KAAO,GAChC,KAAKzB,EAAAA,EAAS,QACZ,OAAQyB,EAAE,KAAO,IAAA,IAAaC,EAAK,IAAI,IAAM,YAAaD,EAC5D,KAAKzB,EAAAA,EAAS,SACZ,OAAO0B,EAAK,IAAI,GAAK,UAAWD,EAClC,KAAKzB,EAAAA,EAAS,QACZ,OACE,MAAM,QAAQyB,EAAE,OAAO,IACtBA,EAAE,mBAAqB,IAAA,IAAaC,EAAK,kBAAkB,I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AK,OAAQ0H,CAAM,CAEzD,CAMA,WAA0B,CACxB,GAAM,CAAE,YAAa,KAErB,GAAI,KAAK,WAAa,KAAK,OAAS,aAAe,CAACC,EAClD,OAIF,IAAMC,MAAkB,CAClB,KAAK,OAAO,SAAS,QACvBD,EAAS,KAAK,CAAE,EAAGrI,EAAAA,EAAS,gBAAiB,KAAM,KAAK,SAAU,CAAC,CAEvE,EAEAsI,EAAI,EACJ,KAAK,UAAY,YAAYA,EAAK/H,EAAAA,EAAuB,EACzDO,EAAA,EAAW,KAAK,SAAS,CAC3B,CACF,E"}
@@ -10,6 +10,10 @@ export declare class InteractionCapture implements Capture {
10
10
  private readonly restores;
11
11
  /** Tracked URL prior to the latest navigation event. */
12
12
  private lastUrl;
13
+ /** Element of the current click burst, and the times of its clicks. */
14
+ private burst;
15
+ /** Stops the dead click check that runs now. */
16
+ private stopDeadCheck;
13
17
  /**
14
18
  * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.
15
19
  */
@@ -23,6 +27,20 @@ export declare class InteractionCapture implements Capture {
23
27
  uninstall(): void;
24
28
  /** Rotates trace context and records a click breadcrumb. */
25
29
  private readonly onClick;
30
+ /**
31
+ * Counts the clicks on one element. It records `ui.rage_click` one time in each burst.
32
+ * @param target Clicked element.
33
+ * @param action Action name of the click.
34
+ * @param options Interaction options.
35
+ */
36
+ private countRage;
37
+ /**
38
+ * Watches the page after a click on a control. With no DOM change, no navigation and no scroll
39
+ * in `deadClickMs`, it records `ui.dead_click`. One check runs at a time.
40
+ * @param action Action name of the click.
41
+ * @param options Interaction options.
42
+ */
43
+ private watchDead;
26
44
  /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */
27
45
  private readonly onNavigate;
28
46
  /** Patches History.pushState and replaceState to observe programmatic navigations. */
@@ -0,0 +1,20 @@
1
+ import type { Capture, CaptureContext } from "./types";
2
+ /** Records page states with the duration of the previous state. */
3
+ export declare class LifecycleCapture implements Capture {
4
+ private readonly ctx;
5
+ readonly name = "lifecycle";
6
+ private installed;
7
+ private phase;
8
+ private readonly window;
9
+ constructor(ctx: CaptureContext);
10
+ /** Installs document and back-forward cache listeners. */
11
+ install(): void;
12
+ /** Removes all listeners. */
13
+ uninstall(): void;
14
+ private readonly onVisibility;
15
+ private readonly onFreeze;
16
+ private readonly onResume;
17
+ private readonly onPageShow;
18
+ /** Updates the state even when its event exceeds the rate limit. */
19
+ private transition;
20
+ }
@@ -0,0 +1,17 @@
1
+ import type { Capture, CaptureContext } from "./types";
2
+ /** Records browser reports without message text, code samples or URL queries. */
3
+ export declare class ReportCapture implements Capture {
4
+ private readonly ctx;
5
+ readonly name = "reports";
6
+ private installed;
7
+ private observer;
8
+ private readonly window;
9
+ constructor(ctx: CaptureContext);
10
+ /** Installs report and CSP listeners. CSP reports do not need ReportingObserver. */
11
+ install(): void;
12
+ /** Disconnects the observer and removes the CSP listener. */
13
+ uninstall(): void;
14
+ private readonly onCsp;
15
+ /** Reads only fixed report fields. The diagnostics guard contains a failed field read. */
16
+ private record;
17
+ }
@@ -0,0 +1,14 @@
1
+ import { type Capture, type CaptureContext } from "./types";
2
+ /** Records bounded resource timings and slow resource events. */
3
+ export declare class ResourceTimingCapture implements Capture {
4
+ private readonly ctx;
5
+ readonly name = "resourceTiming";
6
+ private observer;
7
+ private readonly window;
8
+ constructor(ctx: CaptureContext);
9
+ /** Reads buffered resources only at the first install in this document. */
10
+ install(): void;
11
+ /** Disconnects the observer. */
12
+ uninstall(): void;
13
+ private record;
14
+ }
@@ -0,0 +1,19 @@
1
+ /** One duration entry from the Server-Timing response header. */
2
+ interface ServerTimingEntry {
3
+ name: string;
4
+ duration: number;
5
+ description: string;
6
+ }
7
+ /** Server duration entries and the server span that they name. */
8
+ export interface ServerTiming {
9
+ entries: ServerTimingEntry[];
10
+ link?: {
11
+ traceId: string;
12
+ spanId: string;
13
+ };
14
+ }
15
+ /** Finds the header in an XHR header list. Chrome prints an error for a direct hidden read. */
16
+ export declare function xhrServerTiming(headers: string): string | null;
17
+ /** Reads bounded server duration entries. A missing header gives no entries. */
18
+ export declare function readServerTiming(header: string | null): ServerTiming;
19
+ export {};