@utk09/ui-observability 1.0.0 → 1.2.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.
- package/CHANGELOG.md +111 -219
- package/README.md +24 -26
- package/dist/{batch-CXmPmTse.js → batch-120Kc9jr.js} +3 -3
- package/dist/{batch-CXmPmTse.js.map → batch-120Kc9jr.js.map} +1 -1
- package/dist/{batch-mmPigCpi.cjs → batch-C3uNp5kU.cjs} +2 -2
- package/dist/{batch-mmPigCpi.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
- package/dist/bus/bus.d.cts +31 -2
- package/dist/bus/bus.d.ts +31 -2
- package/dist/bus-Dj8IEVcC.cjs +2 -0
- package/dist/bus-Dj8IEVcC.cjs.map +1 -0
- package/dist/{bus-C39wspFV.js → bus-DyNafxZN.js} +127 -104
- package/dist/bus-DyNafxZN.js.map +1 -0
- package/dist/capture/errors.d.cts +10 -0
- package/dist/capture/errors.d.ts +10 -0
- package/dist/capture/interactions.d.cts +35 -3
- package/dist/capture/interactions.d.ts +35 -3
- package/dist/capture/observed-windows.d.cts +51 -0
- package/dist/capture/observed-windows.d.ts +51 -0
- package/dist/capture/replay.d.cts +1 -1
- package/dist/capture/replay.d.ts +1 -1
- package/dist/capture/types.d.cts +5 -0
- package/dist/capture/types.d.ts +5 -0
- package/dist/capture/web-vitals.d.cts +1 -0
- package/dist/capture/web-vitals.d.ts +1 -0
- package/dist/{compression-tVtXwVjX.js → compression-BWkDWY3v.js} +2 -2
- package/dist/{compression-tVtXwVjX.js.map → compression-BWkDWY3v.js.map} +1 -1
- package/dist/{compression-CvED_Jel.cjs → compression-CEVe7NPX.cjs} +2 -2
- package/dist/{compression-CvED_Jel.cjs.map → compression-CEVe7NPX.cjs.map} +1 -1
- package/dist/config-C0PtemvC.cjs +2 -0
- package/dist/config-C0PtemvC.cjs.map +1 -0
- package/dist/config-DK1Zf7jn.js +556 -0
- package/dist/config-DK1Zf7jn.js.map +1 -0
- package/dist/{console-BGgGnjSi.js → console-CAyCQOpm.js} +5 -5
- package/dist/{console-BGgGnjSi.js.map → console-CAyCQOpm.js.map} +1 -1
- package/dist/{console-CSZ5_Vx5.cjs → console-Dk6GH4yj.cjs} +2 -2
- package/dist/{console-CSZ5_Vx5.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
- package/dist/{constants-CUyd9cTZ.js → constants-CEHN6KuY.js} +46 -25
- package/dist/constants-CEHN6KuY.js.map +1 -0
- package/dist/constants-NtiQDWL_.cjs +2 -0
- package/dist/constants-NtiQDWL_.cjs.map +1 -0
- package/dist/constants.d.cts +23 -0
- package/dist/constants.d.ts +23 -0
- package/dist/core/config.d.cts +9 -3
- package/dist/core/config.d.ts +9 -3
- package/dist/core/diagnostics.d.cts +1 -1
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/pipeline.d.cts +11 -0
- package/dist/core/pipeline.d.ts +11 -0
- package/dist/core/record.d.cts +2 -2
- package/dist/core/record.d.ts +2 -2
- package/dist/core/rotation.d.cts +26 -2
- package/dist/core/rotation.d.ts +26 -2
- package/dist/core/runtime.d.cts +9 -0
- package/dist/core/runtime.d.ts +9 -0
- package/dist/core/sender.d.cts +3 -2
- package/dist/core/sender.d.ts +3 -2
- package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
- package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
- package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-w78W46zr.js} +4 -4
- package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-w78W46zr.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.js +36 -36
- package/dist/doctor.js.map +1 -1
- package/dist/errors-07pmZ7VY.cjs +3 -0
- package/dist/errors-07pmZ7VY.cjs.map +1 -0
- package/dist/{errors-BE_EZV7Q.js → errors-C-LYbqyB.js} +27 -24
- package/dist/errors-C-LYbqyB.js.map +1 -0
- package/dist/{factory-CTi0Is3F.js → factory-BHYrcSaU.js} +39 -28
- package/dist/factory-BHYrcSaU.js.map +1 -0
- package/dist/factory-DsaNdcXp.cjs +2 -0
- package/dist/factory-DsaNdcXp.cjs.map +1 -0
- package/dist/{identity-DdhKgrpk.js → identity-Byh3gCdT.js} +35 -24
- package/dist/identity-Byh3gCdT.js.map +1 -0
- package/dist/identity-BzAzdQyv.cjs +2 -0
- package/dist/identity-BzAzdQyv.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +453 -417
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-BYywz-v6.js} +17 -17
- package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
- package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
- package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
- package/dist/interactions-BXzEel4F.cjs +2 -0
- package/dist/interactions-BXzEel4F.cjs.map +1 -0
- package/dist/interactions-DdKPMWIN.js +207 -0
- package/dist/interactions-DdKPMWIN.js.map +1 -0
- package/dist/{journey-B4Adltjm.cjs → journey-BUmsrgaw.cjs} +2 -2
- package/dist/{journey-B4Adltjm.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
- package/dist/{journey-D2_sia57.js → journey-Nu655gEO.js} +14 -14
- package/dist/{journey-D2_sia57.js.map → journey-Nu655gEO.js.map} +1 -1
- package/dist/{library-console-CPW6bvZH.cjs → library-console-DdIlzzph.cjs} +2 -2
- package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
- package/dist/{library-console-Btrzt814.js → library-console-amePMnP8.js} +2 -2
- package/dist/{library-console-Btrzt814.js.map → library-console-amePMnP8.js.map} +1 -1
- package/dist/{library-request-BJ9PLRaD.js → library-request-Cv7C05jf.js} +2 -2
- package/dist/{library-request-BJ9PLRaD.js.map → library-request-Cv7C05jf.js.map} +1 -1
- package/dist/{library-request-D7OvTxZV.cjs → library-request-DO3Ec7KE.cjs} +2 -2
- package/dist/{library-request-D7OvTxZV.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
- package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-B5yfH5is.cjs} +2 -2
- package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
- package/dist/{lifecycle-22CUCrc9.js → lifecycle-CMHz2Zbs.js} +2 -2
- package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
- package/dist/{log-record-BNiLfqtL.js → log-record-B_nSqxoe.js} +2 -2
- package/dist/{log-record-BNiLfqtL.js.map → log-record-B_nSqxoe.js.map} +1 -1
- package/dist/{log-record-CkivuiEl.cjs → log-record-Bdywwg0k.cjs} +2 -2
- package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
- package/dist/{long-frames-DNFaRnC3.js → long-frames-6NGl1-uN.js} +3 -3
- package/dist/{long-frames-DNFaRnC3.js.map → long-frames-6NGl1-uN.js.map} +1 -1
- package/dist/{long-frames-BUUbXd-B.cjs → long-frames-D9DfSWqv.cjs} +2 -2
- package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
- package/dist/models/bus.d.cts +6 -1
- package/dist/models/bus.d.ts +6 -1
- package/dist/models/config.d.cts +27 -11
- package/dist/models/config.d.ts +27 -11
- package/dist/models/serializer.d.cts +3 -1
- package/dist/models/serializer.d.ts +3 -1
- package/dist/{network-CGMLQ-mA.cjs → network-BNHBI0Fc.cjs} +2 -2
- package/dist/{network-CGMLQ-mA.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
- package/dist/{network-on2zZT6H.js → network-Cc3tSB7e.js} +5 -5
- package/dist/{network-on2zZT6H.js.map → network-Cc3tSB7e.js.map} +1 -1
- package/dist/observed-windows-8JtCsIr1.js +64 -0
- package/dist/observed-windows-8JtCsIr1.js.map +1 -0
- package/dist/observed-windows-BlE25nrn.cjs +2 -0
- package/dist/observed-windows-BlE25nrn.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{otlp-DimfrRor.js → otlp-Btix3EBa.js} +7 -7
- package/dist/{otlp-DimfrRor.js.map → otlp-Btix3EBa.js.map} +1 -1
- package/dist/{otlp-BENHf3g9.cjs → otlp-CFSW-Dno.cjs} +2 -2
- package/dist/{otlp-BENHf3g9.cjs.map → otlp-CFSW-Dno.cjs.map} +1 -1
- package/dist/patch-DlcKzIi-.cjs +2 -0
- package/dist/patch-DlcKzIi-.cjs.map +1 -0
- package/dist/patch-Sr1wKg7W.js +9 -0
- package/dist/patch-Sr1wKg7W.js.map +1 -0
- package/dist/platform-BZjp9wp1.cjs +2 -0
- package/dist/platform-BZjp9wp1.cjs.map +1 -0
- package/dist/platform-Dba6R3Hp.js +75 -0
- package/dist/platform-Dba6R3Hp.js.map +1 -0
- package/dist/{profiler-BAZoh7A4.js → profiler-DNKcqu09.js} +60 -60
- package/dist/{profiler-BAZoh7A4.js.map → profiler-DNKcqu09.js.map} +1 -1
- package/dist/{profiler-D4tJpDRc.cjs → profiler-DpoPi1hH.cjs} +2 -2
- package/dist/{profiler-D4tJpDRc.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
- package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
- package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
- package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-CGXZeZ_3.js} +16 -16
- package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
- package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-DNK96vLa.js} +25 -25
- package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-DNK96vLa.js.map} +1 -1
- package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-DuMFRlit.cjs} +2 -2
- package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-DuMFRlit.cjs.map} +1 -1
- package/dist/replay-Cab-lSit.cjs +2 -0
- package/dist/replay-Cab-lSit.cjs.map +1 -0
- package/dist/{replay-Ds-ANH34.js → replay-Dy6OiaOZ.js} +104 -77
- package/dist/replay-Dy6OiaOZ.js.map +1 -0
- package/dist/{reports-BDSe4dFH.cjs → reports-CGK9YQch.cjs} +2 -2
- package/dist/{reports-BDSe4dFH.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
- package/dist/{reports-C-thq-bk.js → reports-CX57-S9s.js} +3 -3
- package/dist/{reports-C-thq-bk.js.map → reports-CX57-S9s.js.map} +1 -1
- package/dist/{resource-timing-eUl2dNgC.js → resource-timing-CWVDCbrY.js} +4 -4
- package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
- package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-DalulXiR.cjs} +2 -2
- package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-DalulXiR.cjs.map} +1 -1
- package/dist/response-body-Cpz5__4g.cjs +3 -0
- package/dist/response-body-Cpz5__4g.cjs.map +1 -0
- package/dist/{response-body-eoSQpLiH.js → response-body-yi92Rpvo.js} +109 -109
- package/dist/response-body-yi92Rpvo.js.map +1 -0
- package/dist/{rotation-Cwct4ckk.js → rotation-ChBbNDE2.js} +27 -28
- package/dist/rotation-ChBbNDE2.js.map +1 -0
- package/dist/rotation-fTnNJcfH.cjs +2 -0
- package/dist/rotation-fTnNJcfH.cjs.map +1 -0
- package/dist/{sampling-BlrI8jor.js → sampling-DZTOD28D.js} +16 -16
- package/dist/{sampling-BlrI8jor.js.map → sampling-DZTOD28D.js.map} +1 -1
- package/dist/{sampling-mXt4dstx.cjs → sampling-wAVJIZXp.cjs} +2 -2
- package/dist/{sampling-mXt4dstx.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
- package/dist/{sanitize-Ba0KqU06.js → sanitize-B2GKlSFp.js} +2 -2
- package/dist/{sanitize-Ba0KqU06.js.map → sanitize-B2GKlSFp.js.map} +1 -1
- package/dist/{sanitize-DQyiI_KY.cjs → sanitize-BZdhoghq.cjs} +2 -2
- package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
- package/dist/{sender-Dv8rAmpV.js → sender-BRSpc7R8.js} +192 -178
- package/dist/sender-BRSpc7R8.js.map +1 -0
- package/dist/sender-CFu98DAB.cjs +2 -0
- package/dist/sender-CFu98DAB.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.cts +3 -1
- package/dist/storage/emergency-queue.d.ts +3 -1
- package/dist/storage/stored-context.d.cts +3 -2
- package/dist/storage/stored-context.d.ts +3 -2
- package/dist/stored-context-CPLlzgpm.cjs +2 -0
- package/dist/stored-context-CPLlzgpm.cjs.map +1 -0
- package/dist/{stored-context-B2EzVuYm.js → stored-context-df1dEnht.js} +12 -10
- package/dist/stored-context-df1dEnht.js.map +1 -0
- package/dist/{storm-DjKetLKZ.js → storm-U3_ek1nA.js} +2 -2
- package/dist/{storm-DjKetLKZ.js.map → storm-U3_ek1nA.js.map} +1 -1
- package/dist/{storm-C-zYSdDX.cjs → storm-qiE_AMC7.cjs} +2 -2
- package/dist/{storm-C-zYSdDX.cjs.map → storm-qiE_AMC7.cjs.map} +1 -1
- package/dist/transport/exit-flush.d.cts +23 -0
- package/dist/transport/exit-flush.d.ts +23 -0
- package/dist/transport/http-transport.d.cts +3 -2
- package/dist/transport/http-transport.d.ts +3 -2
- package/dist/transport/retry-engine.d.cts +11 -3
- package/dist/transport/retry-engine.d.ts +11 -3
- package/dist/types-BAerHgCq.js.map +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-Bj6gYHeL.js} +2 -2
- package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
- package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
- package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
- package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
- package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
- package/dist/{user-timing-BePqb1uN.js → user-timing-Duz0d-OA.js} +2 -2
- package/dist/{user-timing-BePqb1uN.js.map → user-timing-Duz0d-OA.js.map} +1 -1
- package/dist/utils/identity.d.cts +5 -0
- package/dist/utils/identity.d.ts +5 -0
- package/dist/utils/lock.d.cts +3 -2
- package/dist/utils/lock.d.ts +3 -2
- package/dist/utils/openfin.d.cts +18 -6
- package/dist/utils/openfin.d.ts +18 -6
- package/dist/utils/patch.d.cts +1 -1
- package/dist/utils/patch.d.ts +1 -1
- package/dist/utils/platform.d.cts +6 -0
- package/dist/utils/platform.d.ts +6 -0
- package/dist/{web-socket-DSHgDiZ6.js → web-socket-CE_9Q22z.js} +5 -5
- package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-CE_9Q22z.js.map} +1 -1
- package/dist/{web-socket-CoIUBM3C.cjs → web-socket-sm3rD-A_.cjs} +2 -2
- package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-sm3rD-A_.cjs.map} +1 -1
- package/dist/{web-vitals-4pWACwaR.js → web-vitals-CGwXGF-M.js} +4 -4
- package/dist/web-vitals-CGwXGF-M.js.map +1 -0
- package/dist/web-vitals-Df4Wsfx9.cjs +2 -0
- package/dist/web-vitals-Df4Wsfx9.cjs.map +1 -0
- package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
- package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
- package/dist/{worker-protocol-x074Rpet.js → worker-protocol-h4-tRWqy.js} +6 -6
- package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
- package/dist/{worker-server-CFe4nvos.cjs → worker-server-CF1yatXq.cjs} +2 -2
- package/dist/{worker-server-CFe4nvos.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
- package/dist/worker-server-FYfKHQhJ.js +94 -0
- package/dist/{worker-server-iUVSjH8L.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
- package/dist/worker-transport-COgY4RX8.cjs +2 -0
- package/dist/worker-transport-COgY4RX8.cjs.map +1 -0
- package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-jzX1IusG.js} +49 -45
- package/dist/worker-transport-jzX1IusG.js.map +1 -0
- package/llms.txt +14 -12
- package/package.json +13 -5
- package/dist/bus-C39wspFV.js.map +0 -1
- package/dist/bus-_EaOVPGq.cjs +0 -2
- package/dist/bus-_EaOVPGq.cjs.map +0 -1
- package/dist/config-DUs7uHHt.cjs +0 -2
- package/dist/config-DUs7uHHt.cjs.map +0 -1
- package/dist/config-SgQcCP1_.js +0 -560
- package/dist/config-SgQcCP1_.js.map +0 -1
- package/dist/constants-CUyd9cTZ.js.map +0 -1
- package/dist/constants-CqdJhTxH.cjs +0 -2
- package/dist/constants-CqdJhTxH.cjs.map +0 -1
- package/dist/errors-BE_EZV7Q.js.map +0 -1
- package/dist/errors-CNPbesMs.cjs +0 -3
- package/dist/errors-CNPbesMs.cjs.map +0 -1
- package/dist/factory-CTi0Is3F.js.map +0 -1
- package/dist/factory-hRrH32v5.cjs +0 -2
- package/dist/factory-hRrH32v5.cjs.map +0 -1
- package/dist/identity-DdhKgrpk.js.map +0 -1
- package/dist/identity-DlWRIuwy.cjs +0 -2
- package/dist/identity-DlWRIuwy.cjs.map +0 -1
- package/dist/interactions-CUkzK8sR.cjs +0 -2
- package/dist/interactions-CUkzK8sR.cjs.map +0 -1
- package/dist/interactions-DiFvCosX.js +0 -111
- package/dist/interactions-DiFvCosX.js.map +0 -1
- package/dist/patch-BX8KrPCT.cjs +0 -2
- package/dist/patch-BX8KrPCT.cjs.map +0 -1
- package/dist/patch-UdPz1ea8.js +0 -8
- package/dist/patch-UdPz1ea8.js.map +0 -1
- package/dist/platform-BaaFIPCU.js +0 -62
- package/dist/platform-BaaFIPCU.js.map +0 -1
- package/dist/platform-CfA3-7sJ.cjs +0 -2
- package/dist/platform-CfA3-7sJ.cjs.map +0 -1
- package/dist/replay-B3gFXIZd.cjs +0 -2
- package/dist/replay-B3gFXIZd.cjs.map +0 -1
- package/dist/replay-Ds-ANH34.js.map +0 -1
- package/dist/response-body-YdNl-HkR.cjs +0 -3
- package/dist/response-body-YdNl-HkR.cjs.map +0 -1
- package/dist/response-body-eoSQpLiH.js.map +0 -1
- package/dist/rotation-Cwct4ckk.js.map +0 -1
- package/dist/rotation-D4qUAHAu.cjs +0 -2
- package/dist/rotation-D4qUAHAu.cjs.map +0 -1
- package/dist/sender-BdRuNVhF.cjs +0 -2
- package/dist/sender-BdRuNVhF.cjs.map +0 -1
- package/dist/sender-Dv8rAmpV.js.map +0 -1
- package/dist/stored-context-B2EzVuYm.js.map +0 -1
- package/dist/stored-context-CXt7eHZL.cjs +0 -2
- package/dist/stored-context-CXt7eHZL.cjs.map +0 -1
- package/dist/web-vitals-4pWACwaR.js.map +0 -1
- package/dist/web-vitals-__X7t4pj.cjs +0 -2
- package/dist/web-vitals-__X7t4pj.cjs.map +0 -1
- package/dist/worker-server-iUVSjH8L.js +0 -94
- package/dist/worker-transport-CRAX-09c.cjs +0 -2
- package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
- package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"replay-B3gFXIZd.cjs","names":["META_EVENT","withDeadline","HEADER_CONTENT_TYPE","CONTENT_TYPE_JSON","HEADER_BATCH_ID","HEADER_ATTEMPT","gzip","HEADER_CONTENT_ENCODING","ENCODING_GZIP","runAsLibraryRequest","isLibraryRequest","matchesAny","allowInWindow","newId","REPLAY_ID_KEY","IGNORE_SELECTOR","require_constants","require_identity","require_library_request","require_unref","require_defineProperty","require_compression","require_deadline","require_storm","require_types","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":"A,2VAMA,IAAMA,EAAa,EAGb0B,EAAa,EAGNC,EAAb,KAA0B,CAsBxB,YAAY,EAAyC,CAAxBP,EAAA,EAAA,KAAA,WAAA,IAAA,EAAA,EApB7BA,EAAA,EAAA,KAAA,QAA4B,CAAC,CAAA,EAG7BA,EAAA,EAAA,KAAA,QAA0B,CAAC,CAAA,EAG3BA,EAAA,EAAA,KAAA,QAAgB,CAAA,EAMhBA,EAAA,EAAA,KAAA,UAAkB,EAAA,EAGlBA,EAAA,EAAA,KAAA,OAAe,CAAA,EAKc,KAAA,SAAAQ,CAAyB,CAStD,IAAI,EAAc,EAAc,EAA8B,CAE5D,IAAMC,EAAQC,GAAcC,IAAS/B,EAErC,GAAI,KAAK,SAAW,CAAC6B,EAEnB,MADA,MAAK,OACE,IAGLA,GAAS,KAAK,MAAM,SAAW,KACjC,KAAK,QAAU,GACf,KAAK,MAAM,KAAK,CAAC,CAAC,EAClB,KAAK,MAAM,KAAK,CAAC,EAEb,KAAK,MAAM,OAASH,GACtB,KAAK,WAAW,GAIpB,IAAMM,EAAO,KAAK,MAAM,OAAS,EACjC,KAAK,MAAMA,EAAK,CAAC,KAAKC,CAAI,EAC1B,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C,KAAK,IAAI,OAAO,QAAQ,WAC5D,EAAK,KAAOA,EAAK,KAAK,MAAM,MAAM,CAAC,CAAC,SAKxC,GAAIxB,EAAM,OAASX,GAAqBmC,EAAK,SAAWlC,EAIxD,KAAK,IAAMmC,KAAUD,EAAK,OAAS,CAAC,EAClC,EAAO,MAAQ,KAAK,WAAWC,EAAO,MAAOA,EAAO,EAAE,EAGxD,IAAK,IAAMC,KAAOF,EAAK,MAAQ,CAAC,EAC1BE,EAAI,MAAM,OAASnC,IAErB,EAAI,KAAO,CACT,GAAGmC,EAAI,KACP,YAAa,KAAK,WAAWA,EAAI,KAAK,YAAaA,EAAI,KAAK,EAAE,CAChE,EAToD,CAPxD,CAmBF,CASA,WAAmB,EAAe,EAAqB,CACrD,IAAMC,EAAO,KAAK,QAAQ,QAAQ,QAAQC,CAAE,EAG5C,GAAI,OAAOvF,GAAS,UAAY,CAACsF,GAAQA,EAAK,cAC5C,OAAOtF,EAGT,GAAM,CAAE,WAAU,iBAAkB,KAAK,IAAI,OAAO,OAC9CwF,EAAQF,EAAK,YAAkC,MAAQ,KAM7D,OAJI/B,EACK,KAAK,SAASvD,EAAMwF,CAAI,EAG1BnC,EAAc,OAAS,GAAKmC,GAAM,QAAQnC,EAAc,KAAK,GAAG,CAAC,EACpErD,EAAK,QAAQ,MAAO2C,CAAc,EAClC3C,CACN,CAyKA,WAAmB,EAAuB,CACxC,GAAM,CAAE,QAAS,KAAK,IAEjByF,EAAK,SACR,EAAK,OAAS,GACd,KAAK,IAAI,YAAY,OAAO,yBAA0BC,CAAO,EAEjE,CACF,E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"replay-Ds-ANH34.js","names":["META_EVENT","REPLAY_ID_KEY","HEADER_CONTENT_ENCODING","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","ENCODING_GZIP","HEADER_BATCH_ID","IGNORE_SELECTOR","CONTENT_TYPE_JSON","newId","runAsLibraryRequest","isLibraryRequest","unrefTimer","_defineProperty","gzip","withDeadline","allowInWindow","matchesAny","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAMA,IAAa,GAGbmB,IAAa,GAGNC,IAAb,MAA0B;CAsBxB,YAAY,GAAyC;EAAxB,AAAAP,EAAA,MAAA,YAAA,KAAA,CAAA,GApB7BA,EAAA,MAAA,SAA4B,CAAC,CAAA,GAG7BA,EAAA,MAAA,SAA0B,CAAC,CAAA,GAG3BA,EAAA,MAAA,SAAgB,CAAA,GAMhBA,EAAA,MAAA,WAAkB,EAAA,GAGlBA,EAAA,MAAA,QAAe,CAAA,GAKc,KAAA,WAAAQ;CAAyB;CAStD,IAAI,GAAc,GAAc,GAA8B;EAE5D,IAAMC,IAAQC,KAAcC,MAASxB;EAErC,IAAI,KAAK,WAAW,CAACsB,GAEnB,OADA,KAAK,QACE;EAGT,CAAIA,KAAS,KAAK,MAAM,WAAW,OACjC,KAAK,UAAU,IACf,KAAK,MAAM,KAAK,CAAC,CAAC,GAClB,KAAK,MAAM,KAAK,CAAC,GAEb,KAAK,MAAM,SAASH,KACtB,KAAK,WAAW;EAIpB,IAAMM,IAAO,KAAK,MAAM,SAAS;EAGjC,AAFA,KAAK,MAAMA,EAAK,CAAC,KAAKC,CAAI,GAC1B,KAAK,MAAMD,MAASC,EAAK,QACzB,KAAK,SAASA,EAAK;EAEnB,IAAMC,IAAQ,KAAK,SAAS;EAC5B,OAAO,KAAK,QAAQA,KAAS,KAAK,MAAM,SAAS,IAI/C,AADA,KAAK,UAAU,KAAK,MAAM,WAAW,GACrC,KAAK,QAAQ,KAAK,WAAW;EAG/B,OAAO,KAAK;CACd;CAOA,OAA0C;EACxC,IAAMC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AAI,KAAK,EAAE;IAChE;GAToD;EAPxD;CAmBF;CASA,WAAmB,GAAe,GAAqB;EACrD,IAAMC,IAAO,KAAK,QAAQ,QAAQ,QAAQC,CAAE;EAG5C,IAAI,OAAOvF,KAAS,YAAY,CAACsF,KAAQA,EAAK,eAC5C,OAAOtF;EAGT,IAAM,EAAE,aAAU,qBAAkB,KAAK,IAAI,OAAO,QAC9CwF,IAAQF,EAAK,YAAkC,QAAQ;EAM7D,OAJI/B,IACK,KAAK,SAASvD,GAAMwF,CAAI,IAG1BnC,EAAc,SAAS,KAAKmC,GAAM,QAAQnC,EAAc,KAAK,GAAG,CAAC,IACpErD,EAAK,QAAQ,OAAO2C,CAAc,IAClC3C;CACN;CAyKA,WAAmB,GAAuB;EACxC,IAAM,EAAE,YAAS,KAAK;EAEtB,AAAKyF,EAAK,WACR,EAAK,SAAS,IACd,KAAK,IAAI,YAAY,OAAO,0BAA0BC,CAAO;CAEjE;AACF"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CqdJhTxH.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./defineProperty-X1c4tIPD.cjs"),r=require("./sanitize-DQyiI_KY.cjs"),i=require("./batch-mmPigCpi.cjs"),a=require("./otlp-BENHf3g9.cjs");var o=class extends Error{constructor(e,t,r,i,a,o){super(t),n.t(this,`kind`,void 0),n.t(this,`status`,void 0),n.t(this,`retryAfterMs`,void 0),n.t(this,`maxBytes`,void 0),this.kind=e,this.status=r,this.retryAfterMs=i,this.maxBytes=a,this.name=`TransportError`,o!==void 0&&Object.defineProperty(this,"cause",{value:o,writable:!0,configurable:!0})}};function s(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.Vt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var c={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},l=new Set([e.a,...Object.keys(c)]);function u(t){return e.Ut.test(t)?Number(BigInt(t)/e.Wt):Date.now()}function d(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function f(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function p(e,t,n,r){let i=d(n);if(i!==null)f(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)p(e,t,i,r);else for(let[i,a]of Object.entries(n))p(e,`${t}.${i}`,a,r);r.delete(n)}}function m(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))p(t,r,i,n);return t}function h(e){let t=[];for(let[n,r]of Object.entries(c)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function g(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(l.has(e)&&typeof t==`string`)))}var _={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=u(t.timeUnixNano),{attributes:r}=t,i=r[e.a];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.Q},log:{level:e.Z[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:h(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.bn],version:t.resource[e.xn],environment:t.resource[e.gn]},user_agent:{original:t.resource[e.mn]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...m(t.resource),...m(g(r))}})}).join(`
|
|
2
|
-
`)}\n`,contentType:e.B}}},v=1;function y(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function b(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function x(t){let n=t.attributes[e.zt.attributeKeys],r={};if(!Array.isArray(n))return r;for(let i of n){let n=typeof i==`string`&&!e.Rt.includes(i)?t.attributes[i]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[i]=n)}return r}function S(t){let n=y(t,e.zt.count);if(n===void 0){let e=y(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.zt.bounds],i=t.attributes[e.zt.buckets];if(!b(r)||!b(i)||i.length!==r.length+1)return null;let a=y(t,e.zt.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:y(t,e.zt.sum),min:a,max:y(t,e.zt.max),bucketCounts:i.map(String),explicitBounds:r}}function C(e){let t=y(e,`metric.value`);return t===void 0?null:{asDouble:t}}function w(t,n){let r=t.attributes[e.zt.start],i=n===`histogram`?S(t):C(t);return i===null?null:{attributes:a.i(x(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function T({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:v,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var E={name:e.Fn,serialize(t){let n=a.t(t).map(t=>{let n=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],r=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=w(e,r);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:r,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=n.get(c)??s;l.points.push(i),n.set(c,l)}return{resource:{attributes:a.i(t.resource)},scopeMetrics:[{scope:{name:e.$n,version:e.er},metrics:[...n.values()].map(T)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.z}}},D={internal:1,client:3},O=2,k=0,A=new Set([e.g,...Object.values(e.Hn)]);function j(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function M(t){let n=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!A.has(e))),r=j(t,e.Hn.parentId),i=j(t,e.Hn.linkTraceId),o=j(t,e.Hn.linkSpanId);return{traceId:t.traceId,spanId:t.spanId,...r?{parentSpanId:r}:{},...i&&o?{links:[{traceId:i,spanId:o}]}:{},name:t.body,kind:j(t,e.Hn.kind)===`client`?D.client:D.internal,startTimeUnixNano:j(t,e.Hn.start)??t.timeUnixNano,endTimeUnixNano:j(t,e.Hn.end)??t.timeUnixNano,attributes:a.i(n),status:{code:j(t,e.Hn.status)===`error`?O:k}}}var N={name:e.Fn,serialize(t){let n=a.t(t).map(e=>({resource:{attributes:a.i(e.resource)},scopeSpans:a.n(e.records).map(e=>({scope:{name:e.name},spans:e.records.map(M)}))}));return{body:JSON.stringify({resourceSpans:n}),contentType:e.z}}};function P(e){return e===`otlp`?a.r:e===`ecs`?_:e}function F(e,t){let n=t=>e.records.length>0&&e.records.every(e=>i.t(e,`log.type`)===t);return t.metricsEndpoint!==null&&n(`metric`)?`metrics`:n(`span`)?`traces`:`logs`}function I(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var L={metrics:E,traces:N};function R(e,t,n,r){try{return(L[F(t,e)]??P(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var z={logs:`rejectedLogRecords`,metrics:`rejectedDataPoints`,traces:`rejectedSpans`};function B(e,t){return e!==`logs`||t===`otlp`}function V(e,t){if(e.status===413)return!0;let n=e.headers.get(`Content-Type`)??``;return t&&e.ok&&n.includes(`json`)}function H(e,t,n){return n.guardAsync(`transport.http_error`,`The library could not read the response body. It uses the status code alone.`,()=>U(e,t))}async function U(e,t){let n=e.body?.getReader();if(!n)return``;let r,i=new Promise((e,t)=>{r=()=>{t(Error(`The request ended before its body arrived.`))}});t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r();let a=()=>Promise.race([n.read(),i]),o=new TextDecoder,s=``,c=0;try{let e=await a();for(;!e.done;){if(c+=e.value.byteLength,c>16384){await n.cancel();return}s+=o.decode(e.value,{stream:!0}),e=await a()}return s+o.decode()}finally{t.removeEventListener(`abort`,r)}}function W(e){let n=JSON.parse(e),r=t.n(n)?n.maxBytes:void 0;return typeof r==`number`&&Number.isSafeInteger(r)&&r>0?r:void 0}function G(e,n){if(e.trim()===``)return;let i=JSON.parse(e),a=t.n(i)?i.partialSuccess:void 0;if(!t.n(a))return;let o=K(a[z[n]]),s=typeof a.errorMessage==`string`?r.i(a.errorMessage,256):``;if(o!==0||s!==``)return{rejected:o,message:s}}function K(e){return typeof e==`string`&&/^\d{1,15}$/.test(e)?Number(e):typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:0}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return N}});
|
|
3
|
-
//# sourceMappingURL=response-body-YdNl-HkR.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"response-body-YdNl-HkR.cjs","names":["MILLIS_PER_SECOND","ATTR_APP_NAMESPACE","NANOS_PATTERN","NANOS_PER_MILLI","ECS_VERSION","ECS_LEVEL_NAMES","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_BROWSER_USER_AGENT","CONTENT_TYPE_NDJSON","METRIC_KEYS","METRIC_FIELD_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","TELEMETRY_SDK_NAME","TELEMETRY_SDK_VERSION","CONTENT_TYPE_JSON","ATTR_LOG_TYPE","SPAN_KEYS","toKeyValues","SERIALIZER_NAME_OTLP","groupByResource","groupByScope","CONTENT_TYPE_JSON","otlpSerializer","attributeOf","isObject","truncate","require_constants","require_guards","require_defineProperty","require_sanitize","require_batch","require_otlp","TransportError","message","kind","status","retryAfterMs","maxBytes","cause","parseRetryAfter","header","seconds","date","ERROR_FIELDS","MAPPED_KEYS","toMillis","timeUnixNano","toLabelValue","value","pushLabel","existing","labels","key","flattenLabel","scalar","seen","item","name","entry","toLabels","source","errorOf","fields","field","attributes","unmapped","ecsSerializer","records","millis","record","logger","DELTA","numberOf","isNumbers","pointAttributes","keys","out","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","start","values","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","entries","group","type","named","unit","found","SPAN_KIND","STATUS_ERROR","STATUS_UNSET","FIELD_KEYS","stringOf","spanOf","parent","linkTraceId","linkSpanId","otlpTracesSerializer","resourceSpans","scope","serializerFor","choice","batchKind","only","batch","config","endpointFor","SIGNAL_SERIALIZERS","serializeBatch","error","diagnostics","REJECTED_FIELDS","isOtlpBatch","serializer","needsBody","response","otlp","readOptionalBody","readBodyText","signal","reader","abort","aborted","reject","readChunk","decoder","text","size","chunk","maxBytesOf","parsed","hint","partialSuccessOf","partial","rejected","countOf"],"sources":["../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/otlp-traces.ts","../src/transport/serializers/select.ts","../src/transport/response-body.ts"],"sourcesContent":["// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind decides whether the engine retries, backs off or drops. Transient, offline\n * and timeout failures are retried with backoff. A throttled failure waits for the server's\n * delay, and a too_large failure splits the batch. A permanent failure is dropped, because the\n * server will never accept that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** A failed transport attempt, with its failure kind and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message);\n this.name = \"TransportError\";\n\n // Older browsers ignore the ES2022 (message, { cause }) option, so set the property the way\n // the native one does: own, writable and not enumerable.\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, writable: true, configurable: true });\n }\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. A date in the past gives a negative delay,\n * which is clamped to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n ECS_VERSION,\n LOG_TYPE_METRIC,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** The ECS field for each error attribute. */\nconst ERROR_FIELDS = {\n \"error.type\": \"type\",\n \"error.message\": \"message\",\n \"error.stack_trace\": \"stack_trace\",\n} as const;\n\n/** Attribute keys whose string value moves to an ECS field, and so leaves labels. */\nconst MAPPED_KEYS = new Set<string>([ATTR_APP_NAMESPACE, ...Object.keys(ERROR_FIELDS)]);\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the bus has only\n * passed a shape check, and BigInt throws a SyntaxError on a non-numeric string. That error\n * would lose the whole batch, not just one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input isn't numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, and that error would lose the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field, and an array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map, and a\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. Stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind, otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype, so an attribute named `__proto__` becomes a key and not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/**\n * Builds the ECS error field from the error attributes.\n * @param attributes Record attributes.\n * @returns The field, or undefined for a record without a string error attribute.\n */\nfunction errorOf(attributes: Record<string, unknown>): Record<string, string> | undefined {\n const fields: [string, string][] = [];\n\n for (const [key, field] of Object.entries(ERROR_FIELDS)) {\n const value = attributes[key];\n if (typeof value === \"string\") {\n fields.push([field, value]);\n }\n }\n\n return fields.length > 0 ? Object.fromEntries(fields) : undefined;\n}\n\n/**\n * Removes the attributes that have an ECS field. A label copy of a stack trace would double\n * the size.\n * @param attributes Record attributes.\n * @returns The attributes that go to labels.\n */\nfunction unmapped(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(attributes).filter(\n ([key, value]) => !(MAPPED_KEYS.has(key) && typeof value === \"string\"),\n ),\n );\n}\n\n/** Writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n const { attributes } = record;\n const logger = attributes[ATTR_APP_NAMESPACE];\n\n // JSON.stringify leaves out an undefined field.\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n ecs: { version: ECS_VERSION },\n log: {\n level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase(),\n logger: typeof logger === \"string\" ? logger : undefined,\n },\n event: { kind: attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC ? \"metric\" : \"event\" },\n error: errorOf(attributes),\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // A captured network event's request URL takes precedence over the page URL.\n url: {\n full: attributes[ATTR_URL_FULL] ?? attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last, so a record attribute overrides a resource key with the\n // same name.\n labels: { ...toLabels(record.resource), ...toLabels(unmapped(attributes)) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp-metrics.ts\n//\n// Serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport only\n// uses it for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_FIELD_KEYS,\n METRIC_KEYS,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** The OTLP field for each metric type. Anything that isn't a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Checks whether a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the app passed in its call. The record's context attributes\n * stay out, because a session id on every point would create a new series for every session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key from the app's call can have the same name as a metric field, and that field\n // holds the library's value. Any other metric. key, such as the web-vitals rating, is the\n // caller's own.\n const named = typeof key === \"string\" && !METRIC_FIELD_KEYS.includes(key);\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds a point's histogram fields.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut short.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A single-value histogram record, for example a long frame, has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // The library always builds complete lists, but a record from elsewhere can have lists that\n // don't line up, and a point built from those would report bogus buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // Per OTLP, a histogram with a negative value sets no sum, because a backend reads the sum\n // as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A single-value record has no interval, so its point starts and ends at its own time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A counter record from another context can hold a negative value. A monotonic sum must not\n // decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** Writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. Drops any record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/otlp-traces.ts\n//\n// Serializes span records as an OTLP/JSON ExportTraceServiceRequest. The transport\n// uses it for a batch of span records.\n\nimport { ATTR_LOG_TYPE, CONTENT_TYPE_JSON, SERIALIZER_NAME_OTLP, SPAN_KEYS } from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, groupByScope, toKeyValues } from \"./otlp\";\n\n/** The OTLP SpanKind for each of the library's span kinds. */\nconst SPAN_KIND = { internal: 1, client: 3 } as const;\n\n/** OTLP StatusCode ERROR. */\nconst STATUS_ERROR = 2;\n\n/** OTLP StatusCode UNSET. */\nconst STATUS_UNSET = 0;\n\n/** Attribute keys that hold span fields, and so aren't span attributes. */\nconst FIELD_KEYS = new Set<string>([ATTR_LOG_TYPE, ...Object.values(SPAN_KEYS)]);\n\n/**\n * Reads a string attribute.\n * @param record Span record.\n * @param key Attribute key.\n * @returns The string, or undefined.\n */\nfunction stringOf(record: LogRecord, key: string): string | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Builds one OTLP span. A record that lost a time field starts and ends at its record time.\n * @param record Span record.\n * @returns The OTLP span.\n */\nfunction spanOf(record: LogRecord): Record<string, unknown> {\n const attributes = Object.fromEntries(\n Object.entries(record.attributes).filter(([key]) => !FIELD_KEYS.has(key)),\n );\n const parent = stringOf(record, SPAN_KEYS.parentId);\n const linkTraceId = stringOf(record, SPAN_KEYS.linkTraceId);\n const linkSpanId = stringOf(record, SPAN_KEYS.linkSpanId);\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n // A root span has no parent, so leave the field out.\n ...(parent ? { parentSpanId: parent } : {}),\n ...(linkTraceId && linkSpanId\n ? {\n links: [{ traceId: linkTraceId, spanId: linkSpanId }],\n }\n : {}),\n name: record.body,\n kind: stringOf(record, SPAN_KEYS.kind) === \"client\" ? SPAN_KIND.client : SPAN_KIND.internal,\n startTimeUnixNano: stringOf(record, SPAN_KEYS.start) ?? record.timeUnixNano,\n endTimeUnixNano: stringOf(record, SPAN_KEYS.end) ?? record.timeUnixNano,\n attributes: toKeyValues(attributes),\n status: {\n code: stringOf(record, SPAN_KEYS.status) === \"error\" ? STATUS_ERROR : STATUS_UNSET,\n },\n };\n}\n\n/** Writes span records as an OTLP/JSON ExportTraceServiceRequest. */\nexport const otlpTracesSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource.\n * @param records Span records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceSpans = groupByResource(records).map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeSpans: groupByScope(group.records).map((scope) => ({\n scope: { name: scope.name },\n spans: scope.records.map(spanOf),\n })),\n }));\n\n return {\n body: JSON.stringify({ resourceSpans }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this module,\n// and config.ts keeps just the name, so the main chunk contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\nimport { otlpTracesSerializer } from \"./otlp-traces\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Returns the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A batch\n * of span records is always \"traces\" and must not go to endpoint as log records. A stored\n * record can be corrupt, and then it is neither a metric nor a span.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, \"traces\" for only span\n * records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const only = (type: string): boolean =>\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === type);\n\n if (config.metricsEndpoint !== null && only(\"metric\")) {\n return \"metrics\";\n }\n\n return only(\"span\") ? \"traces\" : \"logs\";\n}\n\n/**\n * Returns the endpoint for a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, tracesEndpoint for a traces batch, else\n * endpoint. null or \"\" means the batch has no destination.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n if (kind === \"metrics\") {\n return config.metricsEndpoint;\n }\n\n return kind === \"traces\" ? config.tracesEndpoint : config.endpoint;\n}\n\n/** Serializers for the batch kinds that don't use the configured serializer. */\nconst SIGNAL_SERIALIZERS: Partial<Record<BatchKind, LogSerializer>> = {\n metrics: otlpMetricsSerializer,\n traces: otlpTracesSerializer,\n};\n\n/**\n * Serializes a batch. Reports a serializer that throws, and the caller then drops the batch.\n * A metrics batch gets the OTLP metrics format, and a traces batch the OTLP traces format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n SIGNAL_SERIALIZERS[batchKind(batch, config)] ?? serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/response-body.ts\n//\n// Reads the small JSON answer of an ingest server on the main thread and in the worker. The\n// read stops at the request's abort signal and at RESPONSE_BODY_LIMIT_BYTES, otherwise a server\n// that sends the headers and then stalls or streams forever holds the dispatch slot.\n\nimport {\n HEADER_CONTENT_TYPE,\n HTTP_PAYLOAD_TOO_LARGE,\n RESPONSE_BODY_LIMIT_BYTES,\n SERVER_MESSAGE_MAX_CHARS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { BatchKind, SerializerChoice } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { truncate } from \"../utils/sanitize\";\n\n/** What an OTLP server rejected or warned about in a batch it accepted. */\nexport interface PartialSuccess {\n /** Number of records the server rejected. 0 means a warning only. */\n rejected: number;\n /** The server's errorMessage, cut to SERVER_MESSAGE_MAX_CHARS. Empty when it sent none. */\n message: string;\n}\n\n/** OTLP names the rejected count after the signal. */\nconst REJECTED_FIELDS: Record<BatchKind, string> = {\n logs: \"rejectedLogRecords\",\n metrics: \"rejectedDataPoints\",\n traces: \"rejectedSpans\",\n};\n\n/**\n * Checks whether a batch goes out in an OTLP format. Metrics and traces always do.\n * @param kind Kind of the batch.\n * @param serializer The log serializer option.\n * @returns True for an OTLP batch.\n */\nexport function isOtlpBatch(kind: BatchKind, serializer: SerializerChoice): boolean {\n return kind !== \"logs\" || serializer === \"otlp\";\n}\n\n/**\n * Checks whether the library reads a response's body. A 413 can carry a size hint, and an OTLP\n * answer in JSON can carry a partialSuccess.\n * @param response Response whose headers have arrived.\n * @param otlp True when the batch went out in an OTLP format.\n * @returns True when the body has something the library uses.\n */\nexport function needsBody(response: Response, otlp: boolean): boolean {\n if (response.status === HTTP_PAYLOAD_TOO_LARGE) {\n return true;\n }\n\n const type = response.headers.get(HEADER_CONTENT_TYPE) ?? \"\";\n return otlp && response.ok && type.includes(\"json\");\n}\n\n/**\n * Reads a body that only adds detail to the status. A body that fails or runs out of time gives\n * undefined, because the server has answered and a retry would send an accepted batch again.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @param diagnostics Reports a read that fails.\n * @returns The text, or undefined when the read fails or the body is larger than the limit.\n */\nexport function readOptionalBody(\n response: Response,\n signal: AbortSignal,\n diagnostics: Diagnostics,\n): Promise<string | undefined> {\n return diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the response body. It uses the status code alone.\",\n () => readBodyText(response, signal),\n );\n}\n\n/**\n * Reads a response body as text, up to RESPONSE_BODY_LIMIT_BYTES.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @returns The text, or undefined when the body is larger than the limit.\n * @throws Error when the signal aborts or the body stream fails.\n */\nasync function readBodyText(response: Response, signal: AbortSignal): Promise<string | undefined> {\n const reader = response.body?.getReader();\n if (!reader) {\n return \"\";\n }\n\n // A browser's fetch abort also fails the stream, but a body that a service worker or a test\n // builds doesn't know the signal, so race each read against it too.\n let abort!: () => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => {\n reject(new Error(\"The request ended before its body arrived.\"));\n };\n });\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n\n const readChunk = () => Promise.race([reader.read(), aborted]);\n const decoder = new TextDecoder();\n let text = \"\";\n let size = 0;\n try {\n let chunk = await readChunk();\n while (!chunk.done) {\n size += chunk.value.byteLength;\n if (size > RESPONSE_BODY_LIMIT_BYTES) {\n // Release the connection instead of downloading the rest.\n await reader.cancel();\n return undefined;\n }\n\n text += decoder.decode(chunk.value, { stream: true });\n chunk = await readChunk();\n }\n\n return text + decoder.decode();\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n}\n\n/**\n * Reads the optional size hint of a 413 body, for example {\"maxBytes\":65536}.\n * @param text The body text.\n * @returns The hint when it's a positive safe integer, otherwise undefined.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function maxBytesOf(text: string): number | undefined {\n const parsed: unknown = JSON.parse(text);\n const hint = isObject(parsed) ? parsed.maxBytes : undefined;\n\n return typeof hint === \"number\" && Number.isSafeInteger(hint) && hint > 0 ? hint : undefined;\n}\n\n/**\n * Reads the partialSuccess of an OTLP export answer, for example\n * {\"partialSuccess\":{\"rejectedLogRecords\":\"2\",\"errorMessage\":\"...\"}}.\n * @param text The answer's body text.\n * @param kind Kind of the batch, which names the count's field.\n * @returns What the server rejected or warned about, or undefined for a full success.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function partialSuccessOf(text: string, kind: BatchKind): PartialSuccess | undefined {\n // OTLP allows an empty body for a full success.\n if (text.trim() === \"\") {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(text);\n const partial = isObject(parsed) ? parsed.partialSuccess : undefined;\n if (!isObject(partial)) {\n return undefined;\n }\n\n const rejected = countOf(partial[REJECTED_FIELDS[kind]]);\n const message =\n typeof partial.errorMessage === \"string\"\n ? truncate(partial.errorMessage, SERVER_MESSAGE_MAX_CHARS)\n : \"\";\n if (rejected === 0 && message === \"\") {\n return undefined;\n }\n\n return { rejected, message };\n}\n\n/**\n * Reads an OTLP int64 count, which JSON gives as a digit string or as a number.\n * @param value The count field.\n * @returns The count, or 0 for anything that isn't a whole number above 0.\n */\nfunction countOf(value: unknown): number {\n // Up to 15 digits always fits in a safe integer.\n if (typeof value === \"string\" && /^\\d{1,15}$/.test(value)) {\n return Number(value);\n }\n\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n"],"mappings":"A,kOAgBA,IAAaoC,EAAb,cAAoC,KAAM,CASxC,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMC,CAAO,EAPGL,EAAA,EAAA,KAAA,OAAA,IAAA,EAAA,EAEAA,EAAA,EAAA,KAAA,SAAA,IAAA,EAAA,EACAA,EAAA,EAAA,KAAA,eAAA,IAAA,EAAA,EACAA,EAAA,EAAA,KAAA,WAAA,IAAA,EAAA,EAJA,KAAA,KAAAM,EAEA,KAAA,OAAAC,EACA,KAAA,aAAAC,EACA,KAAA,SAAAC,EAIhB,KAAK,KAAO,iBAIRC,IAAU,IAAA,IACZ,OAAO,eAAe,KAAM,QAAS,CAAE,MAAOA,EAAO,SAAU,GAAM,aAAc,EAAK,CAAC,CAE7F,CACF,EASA,SAAgBC,EAAgB,EAA2C,CACzE,GAAI,CAACC,EACH,OAGF,IAAMC,EAAU,OAAOD,CAAM,EAC7B,GAAI,OAAO,SAASC,CAAO,EACzB,OAAO,KAAK,IAAI,EAAGA,EAAU7C,EAAAA,EAAiB,EAGhD,IAAM8C,EAAO,KAAK,MAAMF,CAAM,EAC9B,OAAO,OAAO,MAAME,CAAI,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAO,KAAK,IAAI,CAAC,CACvE,CCtCA,IAAMC,EAAe,CACnB,aAAc,OACd,gBAAiB,UACjB,oBAAqB,aACvB,EAGMC,EAAc,IAAI,IAAY,CAAC/C,EAAAA,EAAoB,GAAG,OAAO,KAAK8C,CAAY,CAAC,CAAC,EAStF,SAASE,EAAS,EAA8B,CAK9C,OAJK/C,EAAAA,GAAc,KAAKgD,CAAY,EAI7B,OAAO,OAAOA,CAAY,EAAI/C,EAAAA,EAAe,EAH3C,KAAK,IAAI,CAIpB,CAUA,SAASgD,EAAa,EAAmC,CAUvD,OATI,OAAOC,GAAU,UAAY,OAAOA,GAAU,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iB,IAAA,GAC3D,GAAI,CAACpH,EAAAA,EAASuH,CAAO,EACnB,OAGF,IAAMC,EAAWC,EAAQF,EAAQtB,EAAgBvF,GAAM,EACjDD,EACJ,OAAO8G,EAAQ,cAAiB,SAC5BtH,EAAAA,EAASsH,EAAQ,aAAA,GAAsC,EACvD,GACN,GAAIC,IAAa,GAAK/G,IAAY,GAIlC,MAAO,CAAE,WAAU,SAAQ,CAC7B,CAOA,SAASgH,EAAQ,EAAwB,CAMvC,OAJI,OAAOjG,GAAU,UAAY,aAAa,KAAKA,CAAK,EAC/C,OAAOA,CAAK,EAGd,OAAOA,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,EAAQ,EAAIA,EAAQ,CACzF,C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"response-body-eoSQpLiH.js","names":["TELEMETRY_SDK_NAME","CONTENT_TYPE_NDJSON","SERIALIZER_NAME_OTLP","SPAN_KEYS","ECS_VERSION","METRIC_FIELD_KEYS","NANOS_PATTERN","MILLIS_PER_SECOND","NANOS_PER_MILLI","ECS_LEVEL_NAMES","ATTR_APP_NAMESPACE","RESOURCE_SERVICE_NAME","TELEMETRY_SDK_VERSION","ATTR_LOG_TYPE","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_BROWSER_USER_AGENT","RESOURCE_SERVICE_VERSION","CONTENT_TYPE_JSON","METRIC_KEYS","isObject","_defineProperty","truncate","attributeOf","toKeyValues","groupByScope","otlpSerializer","groupByResource","TransportError","message","kind","status","retryAfterMs","maxBytes","cause","parseRetryAfter","header","seconds","date","ERROR_FIELDS","MAPPED_KEYS","toMillis","timeUnixNano","toLabelValue","value","pushLabel","existing","labels","key","flattenLabel","scalar","seen","item","name","entry","toLabels","source","errorOf","fields","field","attributes","unmapped","ecsSerializer","records","millis","record","logger","DELTA","numberOf","isNumbers","pointAttributes","keys","out","histogramOf","count","bounds","buckets","min","numberPointOf","pointOf","start","values","metricOf","points","data","point","otlpMetricsSerializer","resourceMetrics","entries","group","type","named","unit","found","SPAN_KIND","STATUS_ERROR","STATUS_UNSET","FIELD_KEYS","stringOf","spanOf","parent","linkTraceId","linkSpanId","otlpTracesSerializer","resourceSpans","scope","serializerFor","choice","batchKind","only","batch","config","endpointFor","SIGNAL_SERIALIZERS","serializeBatch","error","REJECTED_FIELDS","isOtlpBatch","serializer","needsBody","response","otlp","readOptionalBody","diagnostics","readBodyText","signal","reader","abort","aborted","readChunk","decoder","text","size","chunk","maxBytesOf","parsed","hint","partialSuccessOf","partial","rejected","countOf"],"sources":["../src/transport/errors.ts","../src/transport/serializers/ecs.ts","../src/transport/serializers/otlp-metrics.ts","../src/transport/serializers/otlp-traces.ts","../src/transport/serializers/select.ts","../src/transport/response-body.ts"],"sourcesContent":["// src/transport/errors.ts\n//\n// Classifies HTTP transport failures and parses the Retry-After header.\n\nimport { MILLIS_PER_SECOND } from \"../constants\";\n\n/**\n * The failure kind decides whether the engine retries, backs off or drops. Transient, offline\n * and timeout failures are retried with backoff. A throttled failure waits for the server's\n * delay, and a too_large failure splits the batch. A permanent failure is dropped, because the\n * server will never accept that batch.\n */\nexport type TransportFailureKind =\n \"transient\" | \"throttled\" | \"too_large\" | \"permanent\" | \"timeout\" | \"offline\";\n\n/** A failed transport attempt, with its failure kind and metadata. */\nexport class TransportError extends Error {\n /**\n * @param kind Failure classification.\n * @param message Error description.\n * @param status Optional HTTP response status code.\n * @param retryAfterMs Delay requested by the server in milliseconds.\n * @param maxBytes Maximum payload bytes suggested by a 413 response.\n * @param cause Error that caused this failure.\n */\n constructor(\n public readonly kind: TransportFailureKind,\n message: string,\n public readonly status?: number,\n public readonly retryAfterMs?: number,\n public readonly maxBytes?: number,\n cause?: unknown,\n ) {\n super(message);\n this.name = \"TransportError\";\n\n // Older browsers ignore the ES2022 (message, { cause }) option, so set the property the way\n // the native one does: own, writable and not enumerable.\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, writable: true, configurable: true });\n }\n }\n}\n\n/**\n * Parses an HTTP Retry-After value into a delay in milliseconds. The value\n * can be a number of seconds or an HTTP date. A date in the past gives a negative delay,\n * which is clamped to zero.\n * @param header Raw Retry-After header string or null.\n * @returns Non-negative delay in milliseconds, or undefined if invalid or missing.\n */\nexport function parseRetryAfter(header: string | null): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * MILLIS_PER_SECOND);\n }\n\n const date = Date.parse(header);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","// src/transport/serializers/ecs.ts\n//\n// Serializes log batches as Elastic Common Schema (ECS) newline-delimited JSON.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_URL_FULL,\n CONTENT_TYPE_NDJSON,\n ECS_LEVEL_NAMES,\n ECS_VERSION,\n LOG_TYPE_METRIC,\n NANOS_PATTERN,\n NANOS_PER_MILLI,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n SERIALIZER_NAME_ECS,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\n\n/** The ECS field for each error attribute. */\nconst ERROR_FIELDS = {\n \"error.type\": \"type\",\n \"error.message\": \"message\",\n \"error.stack_trace\": \"stack_trace\",\n} as const;\n\n/** Attribute keys whose string value moves to an ECS field, and so leaves labels. */\nconst MAPPED_KEYS = new Set<string>([ATTR_APP_NAMESPACE, ...Object.keys(ERROR_FIELDS)]);\n\n/**\n * Converts a nanosecond epoch string to epoch milliseconds. A record from the bus has only\n * passed a shape check, and BigInt throws a SyntaxError on a non-numeric string. That error\n * would lose the whole batch, not just one record.\n * @param timeUnixNano Nanosecond epoch as decimal digits.\n * @returns Epoch milliseconds, or the current time when the input isn't numeric.\n */\nfunction toMillis(timeUnixNano: string): number {\n if (!NANOS_PATTERN.test(timeUnixNano)) {\n return Date.now();\n }\n\n return Number(BigInt(timeUnixNano) / NANOS_PER_MILLI);\n}\n\n/** Elasticsearch maps these value types under `labels` without a dynamic mapping conflict. */\ntype LabelValue = string | number | boolean;\n\n/**\n * Converts a value to its label form.\n * @param value Raw attribute or resource value.\n * @returns Scalar label value, or null when the value has no scalar form.\n */\nfunction toLabelValue(value: unknown): LabelValue | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n // JSON.stringify throws on a BigInt, and that error would lose the whole batch.\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return null;\n}\n\n/**\n * Writes one label, folding a repeated key into an array. Elasticsearch reads\n * a repeated leaf as one multi-valued field, and an array of objects maps the same way.\n * @param labels Label map being built.\n * @param key Dotted label key.\n * @param value Scalar label value.\n */\nfunction pushLabel(labels: Record<string, unknown>, key: string, value: LabelValue): void {\n const existing = labels[key];\n\n if (existing === undefined) {\n labels[key] = value;\n return;\n }\n\n if (Array.isArray(existing)) {\n (existing as LabelValue[]).push(value);\n return;\n }\n\n labels[key] = [existing, value];\n}\n\n/**\n * Flattens one value into dotted label keys. ECS `labels` is a flat map, and a\n * nested object under it causes an Elasticsearch dynamic mapping conflict.\n * @param labels Label map being built.\n * @param key Dotted key for this value.\n * @param value Value to flatten.\n * @param seen Active ancestor objects. Stops infinite recursion on a cycle.\n */\nfunction flattenLabel(\n labels: Record<string, unknown>,\n key: string,\n value: unknown,\n seen: WeakSet<object>,\n): void {\n const scalar = toLabelValue(value);\n\n if (scalar !== null) {\n pushLabel(labels, key, scalar);\n return;\n }\n\n // A forwarded record has only passed a shape check, so its attributes can contain a cycle.\n if (typeof value !== \"object\" || value === null || seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n flattenLabel(labels, key, item, seen);\n }\n } else {\n for (const [name, entry] of Object.entries(value)) {\n flattenLabel(labels, `${key}.${name}`, entry, seen);\n }\n }\n\n // Remove the object on unwind, otherwise a repeated sibling reads as a cycle.\n seen.delete(value);\n}\n\n/**\n * Flattens an attribute or resource map into ECS labels.\n * @param source Attribute or resource map.\n * @returns Flat label map keyed by dotted path.\n */\nfunction toLabels(source: Record<string, unknown>): Record<string, unknown> {\n // Use a null prototype, so an attribute named `__proto__` becomes a key and not a prototype.\n const labels: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const seen = new WeakSet();\n\n for (const [key, value] of Object.entries(source)) {\n flattenLabel(labels, key, value, seen);\n }\n\n return labels;\n}\n\n/**\n * Builds the ECS error field from the error attributes.\n * @param attributes Record attributes.\n * @returns The field, or undefined for a record without a string error attribute.\n */\nfunction errorOf(attributes: Record<string, unknown>): Record<string, string> | undefined {\n const fields: [string, string][] = [];\n\n for (const [key, field] of Object.entries(ERROR_FIELDS)) {\n const value = attributes[key];\n if (typeof value === \"string\") {\n fields.push([field, value]);\n }\n }\n\n return fields.length > 0 ? Object.fromEntries(fields) : undefined;\n}\n\n/**\n * Removes the attributes that have an ECS field. A label copy of a stack trace would double\n * the size.\n * @param attributes Record attributes.\n * @returns The attributes that go to labels.\n */\nfunction unmapped(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(attributes).filter(\n ([key, value]) => !(MAPPED_KEYS.has(key) && typeof value === \"string\"),\n ),\n );\n}\n\n/** Writes log records as Elastic Common Schema (ECS) NDJSON documents. */\nexport const ecsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_ECS,\n\n /**\n * Serializes log records into newline-delimited ECS JSON documents.\n * @param records Records to serialize.\n * @returns Serialized NDJSON batch payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const lines = records.map((record) => {\n const millis = toMillis(record.timeUnixNano);\n\n const { attributes } = record;\n const logger = attributes[ATTR_APP_NAMESPACE];\n\n // JSON.stringify leaves out an undefined field.\n return JSON.stringify({\n \"@timestamp\": new Date(millis).toISOString(),\n message: record.body,\n ecs: { version: ECS_VERSION },\n log: {\n level: ECS_LEVEL_NAMES[record.severityText] ?? record.severityText.toLowerCase(),\n logger: typeof logger === \"string\" ? logger : undefined,\n },\n event: { kind: attributes[ATTR_LOG_TYPE] === LOG_TYPE_METRIC ? \"metric\" : \"event\" },\n error: errorOf(attributes),\n trace: { id: record.traceId },\n span: { id: record.spanId },\n service: {\n name: record.resource[RESOURCE_SERVICE_NAME],\n version: record.resource[RESOURCE_SERVICE_VERSION],\n environment: record.resource[RESOURCE_DEPLOYMENT_ENVIRONMENT],\n },\n user_agent: { original: record.resource[RESOURCE_BROWSER_USER_AGENT] },\n // A captured network event's request URL takes precedence over the page URL.\n url: {\n full: attributes[ATTR_URL_FULL] ?? attributes[ATTR_PAGE_URL],\n },\n // Spread the attributes last, so a record attribute overrides a resource key with the\n // same name.\n labels: { ...toLabels(record.resource), ...toLabels(unmapped(attributes)) },\n });\n });\n\n return { body: `${lines.join(\"\\n\")}\\n`, contentType: CONTENT_TYPE_NDJSON };\n },\n};\n","// src/transport/serializers/otlp-metrics.ts\n//\n// Serializes metric records as an OTLP/JSON ExportMetricsServiceRequest. The transport only\n// uses it for a batch of metric records when metricsEndpoint is set.\n\nimport {\n CONTENT_TYPE_JSON,\n METRIC_FIELD_KEYS,\n METRIC_KEYS,\n SERIALIZER_NAME_OTLP,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, toKeyValues } from \"./otlp\";\n\n/** OTLP AggregationTemporality DELTA. Each point holds the change since the previous point. */\nconst DELTA = 1;\n\n/** The OTLP field for each metric type. Anything that isn't a counter or a histogram is a gauge. */\ntype MetricField = \"sum\" | \"histogram\" | \"gauge\";\n\n/** One OTLP data point. */\ntype DataPoint = Record<string, unknown>;\n\n/** Data points of one metric name, type and unit. */\ninterface MetricEntry {\n /** Metric name. */\n name: string;\n /** Unit of the values. */\n unit: string;\n /** OTLP field of the type. */\n field: MetricField;\n /** Data points. */\n points: DataPoint[];\n}\n\n/**\n * Reads a finite number attribute.\n * @param record Metric record.\n * @param key Attribute key.\n * @returns The number, or undefined.\n */\nfunction numberOf(record: LogRecord, key: string): number | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Checks whether a value is a list of finite numbers.\n * @param value Attribute value.\n * @returns True for a list of finite numbers.\n */\nfunction isNumbers(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((item: unknown) => typeof item === \"number\" && Number.isFinite(item))\n );\n}\n\n/**\n * Reads the point attributes that the app passed in its call. The record's context attributes\n * stay out, because a session id on every point would create a new series for every session.\n * @param record Metric record.\n * @returns The string, number and boolean attributes that `metric.attribute_keys` names.\n */\nfunction pointAttributes(record: LogRecord): Record<string, unknown> {\n const keys: unknown = record.attributes[METRIC_KEYS.attributeKeys];\n const out: Record<string, unknown> = {};\n\n if (!Array.isArray(keys)) {\n return out;\n }\n\n for (const key of keys as unknown[]) {\n // A key from the app's call can have the same name as a metric field, and that field\n // holds the library's value. Any other metric. key, such as the web-vitals rating, is the\n // caller's own.\n const named = typeof key === \"string\" && !METRIC_FIELD_KEYS.includes(key);\n const value: unknown = named ? record.attributes[key] : undefined;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n out[key as string] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Builds a point's histogram fields.\n * @param record Metric record.\n * @returns The fields, or null for a point that a record limit cut short.\n */\nfunction histogramOf(record: LogRecord): DataPoint | null {\n const count = numberOf(record, METRIC_KEYS.count);\n\n // A single-value histogram record, for example a long frame, has one bucket and no boundaries.\n if (count === undefined) {\n const value = numberOf(record, \"metric.value\");\n return value === undefined\n ? null\n : {\n count: \"1\",\n sum: value < 0 ? undefined : value,\n min: value,\n max: value,\n bucketCounts: [\"1\"],\n explicitBounds: [],\n };\n }\n\n const bounds: unknown = record.attributes[METRIC_KEYS.bounds];\n const buckets: unknown = record.attributes[METRIC_KEYS.buckets];\n\n // The library always builds complete lists, but a record from elsewhere can have lists that\n // don't line up, and a point built from those would report bogus buckets.\n if (!isNumbers(bounds) || !isNumbers(buckets) || buckets.length !== bounds.length + 1) {\n return null;\n }\n\n // Per OTLP, a histogram with a negative value sets no sum, because a backend reads the sum\n // as a total.\n const min = numberOf(record, METRIC_KEYS.min);\n\n return {\n count: String(count),\n sum: min !== undefined && min < 0 ? undefined : numberOf(record, METRIC_KEYS.sum),\n min,\n max: numberOf(record, METRIC_KEYS.max),\n // OTLP JSON encodes an int64 as a decimal string.\n bucketCounts: buckets.map(String),\n explicitBounds: bounds,\n };\n}\n\n/**\n * Builds the value field of a sum or gauge point.\n * @param record Metric record.\n * @returns The field, or null for a record without a valid value.\n */\nfunction numberPointOf(record: LogRecord): DataPoint | null {\n const value = numberOf(record, \"metric.value\");\n return value === undefined ? null : { asDouble: value };\n}\n\n/**\n * Builds one OTLP data point.\n * @param record Metric record.\n * @param field OTLP field of the type.\n * @returns The point, or null for a record without a valid value.\n */\nfunction pointOf(record: LogRecord, field: MetricField): DataPoint | null {\n const start: unknown = record.attributes[METRIC_KEYS.start];\n const values = field === \"histogram\" ? histogramOf(record) : numberPointOf(record);\n\n if (values === null) {\n return null;\n }\n\n return {\n attributes: toKeyValues(pointAttributes(record)),\n // A single-value record has no interval, so its point starts and ends at its own time.\n startTimeUnixNano: typeof start === \"string\" ? start : record.timeUnixNano,\n timeUnixNano: record.timeUnixNano,\n ...values,\n };\n}\n\n/**\n * Builds the OTLP metric of an entry.\n * @param entry Data points of one name, type and unit.\n * @returns The OTLP metric.\n */\nfunction metricOf({ name, unit, field, points }: MetricEntry): Record<string, unknown> {\n if (field === \"gauge\") {\n return { name, unit, gauge: { dataPoints: points } };\n }\n\n const data: Record<string, unknown> = { aggregationTemporality: DELTA, dataPoints: points };\n\n // A counter record from another context can hold a negative value. A monotonic sum must not\n // decrease.\n if (field === \"sum\") {\n data.isMonotonic = points.every((point) => (point.asDouble as number) >= 0);\n }\n\n return { name, unit, [field]: data };\n}\n\n/** Writes metric records as an OTLP/JSON ExportMetricsServiceRequest. */\nexport const otlpMetricsSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource, then by metric name, type and unit. Drops any record\n * without a valid value.\n * @param records Metric records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceMetrics = groupByResource(records).map((group) => {\n const entries = new Map<string, MetricEntry>();\n\n for (const record of group.records) {\n const type: unknown = record.attributes[\"metric.type\"];\n const field: MetricField =\n type === \"counter\" ? \"sum\" : type === \"histogram\" ? \"histogram\" : \"gauge\";\n const point = pointOf(record, field);\n\n if (point === null) {\n continue;\n }\n\n const named: unknown = record.attributes[\"metric.name\"];\n const unit: unknown = record.attributes[\"metric.unit\"];\n const entry: MetricEntry = {\n name: typeof named === \"string\" ? named : record.body,\n unit: typeof unit === \"string\" ? unit : \"\",\n field,\n points: [],\n };\n const key = JSON.stringify([entry.field, entry.name, entry.unit]);\n const found = entries.get(key) ?? entry;\n\n found.points.push(point);\n entries.set(key, found);\n }\n\n return {\n resource: { attributes: toKeyValues(group.resource) },\n scopeMetrics: [\n {\n scope: { name: TELEMETRY_SDK_NAME, version: TELEMETRY_SDK_VERSION },\n metrics: [...entries.values()].map(metricOf),\n },\n ],\n };\n });\n\n return {\n body: JSON.stringify({ resourceMetrics }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/otlp-traces.ts\n//\n// Serializes span records as an OTLP/JSON ExportTraceServiceRequest. The transport\n// uses it for a batch of span records.\n\nimport { ATTR_LOG_TYPE, CONTENT_TYPE_JSON, SERIALIZER_NAME_OTLP, SPAN_KEYS } from \"../../constants\";\nimport type { LogRecord } from \"../../models/log-record\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { groupByResource, groupByScope, toKeyValues } from \"./otlp\";\n\n/** The OTLP SpanKind for each of the library's span kinds. */\nconst SPAN_KIND = { internal: 1, client: 3 } as const;\n\n/** OTLP StatusCode ERROR. */\nconst STATUS_ERROR = 2;\n\n/** OTLP StatusCode UNSET. */\nconst STATUS_UNSET = 0;\n\n/** Attribute keys that hold span fields, and so aren't span attributes. */\nconst FIELD_KEYS = new Set<string>([ATTR_LOG_TYPE, ...Object.values(SPAN_KEYS)]);\n\n/**\n * Reads a string attribute.\n * @param record Span record.\n * @param key Attribute key.\n * @returns The string, or undefined.\n */\nfunction stringOf(record: LogRecord, key: string): string | undefined {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Builds one OTLP span. A record that lost a time field starts and ends at its record time.\n * @param record Span record.\n * @returns The OTLP span.\n */\nfunction spanOf(record: LogRecord): Record<string, unknown> {\n const attributes = Object.fromEntries(\n Object.entries(record.attributes).filter(([key]) => !FIELD_KEYS.has(key)),\n );\n const parent = stringOf(record, SPAN_KEYS.parentId);\n const linkTraceId = stringOf(record, SPAN_KEYS.linkTraceId);\n const linkSpanId = stringOf(record, SPAN_KEYS.linkSpanId);\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n // A root span has no parent, so leave the field out.\n ...(parent ? { parentSpanId: parent } : {}),\n ...(linkTraceId && linkSpanId\n ? {\n links: [{ traceId: linkTraceId, spanId: linkSpanId }],\n }\n : {}),\n name: record.body,\n kind: stringOf(record, SPAN_KEYS.kind) === \"client\" ? SPAN_KIND.client : SPAN_KIND.internal,\n startTimeUnixNano: stringOf(record, SPAN_KEYS.start) ?? record.timeUnixNano,\n endTimeUnixNano: stringOf(record, SPAN_KEYS.end) ?? record.timeUnixNano,\n attributes: toKeyValues(attributes),\n status: {\n code: stringOf(record, SPAN_KEYS.status) === \"error\" ? STATUS_ERROR : STATUS_UNSET,\n },\n };\n}\n\n/** Writes span records as an OTLP/JSON ExportTraceServiceRequest. */\nexport const otlpTracesSerializer: LogSerializer = {\n /** The format name. */\n name: SERIALIZER_NAME_OTLP,\n\n /**\n * Groups the records by resource.\n * @param records Span records to serialize.\n * @returns Serialized JSON payload.\n */\n serialize(records: LogRecord[]): SerializedBatch {\n const resourceSpans = groupByResource(records).map((group) => ({\n resource: { attributes: toKeyValues(group.resource) },\n scopeSpans: groupByScope(group.records).map((scope) => ({\n scope: { name: scope.name },\n spans: scope.records.map(spanOf),\n })),\n }));\n\n return {\n body: JSON.stringify({ resourceSpans }),\n contentType: CONTENT_TYPE_JSON,\n };\n },\n};\n","// src/transport/serializers/select.ts\n//\n// Maps the serializer option to an implementation. Only transport code imports this module,\n// and config.ts keeps just the name, so the main chunk contains no serializer.\n\nimport { ATTR_LOG_TYPE } from \"../../constants\";\nimport type { Diagnostics } from \"../../core/diagnostics\";\nimport { attributeOf, type LogBatch } from \"../../models/batch\";\nimport type { BatchKind, ResolvedConfig, SerializerChoice } from \"../../models/config\";\nimport type { LogSerializer, SerializedBatch } from \"../../models/serializer\";\nimport { ecsSerializer } from \"./ecs\";\nimport { otlpSerializer } from \"./otlp\";\nimport { otlpMetricsSerializer } from \"./otlp-metrics\";\nimport { otlpTracesSerializer } from \"./otlp-traces\";\n\n/**\n * Returns the implementation for a resolved serializer option.\n * @param choice Serializer name, or a custom implementation.\n * @returns Serializer implementation.\n */\nexport function serializerFor(choice: SerializerChoice): LogSerializer {\n if (choice === \"otlp\") {\n return otlpSerializer;\n }\n\n if (choice === \"ecs\") {\n return ecsSerializer;\n }\n\n return choice;\n}\n\n/**\n * Returns the kind of a batch. Only a batch of metric records goes to metricsEndpoint. A batch\n * of span records is always \"traces\" and must not go to endpoint as log records. A stored\n * record can be corrupt, and then it is neither a metric nor a span.\n * @param batch Batch to test.\n * @param config Active configuration.\n * @returns \"metrics\" with metricsEndpoint set and only metric records, \"traces\" for only span\n * records, else \"logs\".\n */\nexport function batchKind(batch: LogBatch, config: ResolvedConfig): BatchKind {\n const only = (type: string): boolean =>\n batch.records.length > 0 &&\n batch.records.every((record) => attributeOf(record, ATTR_LOG_TYPE) === type);\n\n if (config.metricsEndpoint !== null && only(\"metric\")) {\n return \"metrics\";\n }\n\n return only(\"span\") ? \"traces\" : \"logs\";\n}\n\n/**\n * Returns the endpoint for a batch kind.\n * @param kind Kind of the batch.\n * @param config Active configuration.\n * @returns metricsEndpoint for a metrics batch, tracesEndpoint for a traces batch, else\n * endpoint. null or \"\" means the batch has no destination.\n */\nexport function endpointFor(kind: BatchKind, config: ResolvedConfig): string | null {\n if (kind === \"metrics\") {\n return config.metricsEndpoint;\n }\n\n return kind === \"traces\" ? config.tracesEndpoint : config.endpoint;\n}\n\n/** Serializers for the batch kinds that don't use the configured serializer. */\nconst SIGNAL_SERIALIZERS: Partial<Record<BatchKind, LogSerializer>> = {\n metrics: otlpMetricsSerializer,\n traces: otlpTracesSerializer,\n};\n\n/**\n * Serializes a batch. Reports a serializer that throws, and the caller then drops the batch.\n * A metrics batch gets the OTLP metrics format, and a traces batch the OTLP traces format.\n * @param config Active configuration.\n * @param batch Batch to serialize.\n * @param diagnostics Diagnostics reporter.\n * @param message ASD-STE100 sentence for the report.\n * @returns The serialized batch, or undefined if the serializer threw.\n */\nexport function serializeBatch(\n config: ResolvedConfig,\n batch: LogBatch,\n diagnostics: Diagnostics,\n message: string,\n): SerializedBatch | undefined {\n try {\n const serializer =\n SIGNAL_SERIALIZERS[batchKind(batch, config)] ?? serializerFor(config.serializer);\n return serializer.serialize(batch.records);\n } catch (error) {\n diagnostics.report(\"transport.serialize_failed\", message, { batchId: batch.id }, error);\n return undefined;\n }\n}\n","// src/transport/response-body.ts\n//\n// Reads the small JSON answer of an ingest server on the main thread and in the worker. The\n// read stops at the request's abort signal and at RESPONSE_BODY_LIMIT_BYTES, otherwise a server\n// that sends the headers and then stalls or streams forever holds the dispatch slot.\n\nimport {\n HEADER_CONTENT_TYPE,\n HTTP_PAYLOAD_TOO_LARGE,\n RESPONSE_BODY_LIMIT_BYTES,\n SERVER_MESSAGE_MAX_CHARS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { BatchKind, SerializerChoice } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { truncate } from \"../utils/sanitize\";\n\n/** What an OTLP server rejected or warned about in a batch it accepted. */\nexport interface PartialSuccess {\n /** Number of records the server rejected. 0 means a warning only. */\n rejected: number;\n /** The server's errorMessage, cut to SERVER_MESSAGE_MAX_CHARS. Empty when it sent none. */\n message: string;\n}\n\n/** OTLP names the rejected count after the signal. */\nconst REJECTED_FIELDS: Record<BatchKind, string> = {\n logs: \"rejectedLogRecords\",\n metrics: \"rejectedDataPoints\",\n traces: \"rejectedSpans\",\n};\n\n/**\n * Checks whether a batch goes out in an OTLP format. Metrics and traces always do.\n * @param kind Kind of the batch.\n * @param serializer The log serializer option.\n * @returns True for an OTLP batch.\n */\nexport function isOtlpBatch(kind: BatchKind, serializer: SerializerChoice): boolean {\n return kind !== \"logs\" || serializer === \"otlp\";\n}\n\n/**\n * Checks whether the library reads a response's body. A 413 can carry a size hint, and an OTLP\n * answer in JSON can carry a partialSuccess.\n * @param response Response whose headers have arrived.\n * @param otlp True when the batch went out in an OTLP format.\n * @returns True when the body has something the library uses.\n */\nexport function needsBody(response: Response, otlp: boolean): boolean {\n if (response.status === HTTP_PAYLOAD_TOO_LARGE) {\n return true;\n }\n\n const type = response.headers.get(HEADER_CONTENT_TYPE) ?? \"\";\n return otlp && response.ok && type.includes(\"json\");\n}\n\n/**\n * Reads a body that only adds detail to the status. A body that fails or runs out of time gives\n * undefined, because the server has answered and a retry would send an accepted batch again.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @param diagnostics Reports a read that fails.\n * @returns The text, or undefined when the read fails or the body is larger than the limit.\n */\nexport function readOptionalBody(\n response: Response,\n signal: AbortSignal,\n diagnostics: Diagnostics,\n): Promise<string | undefined> {\n return diagnostics.guardAsync(\n \"transport.http_error\",\n \"The library could not read the response body. It uses the status code alone.\",\n () => readBodyText(response, signal),\n );\n}\n\n/**\n * Reads a response body as text, up to RESPONSE_BODY_LIMIT_BYTES.\n * @param response Response whose headers have arrived.\n * @param signal The request's abort signal. An abort ends the read.\n * @returns The text, or undefined when the body is larger than the limit.\n * @throws Error when the signal aborts or the body stream fails.\n */\nasync function readBodyText(response: Response, signal: AbortSignal): Promise<string | undefined> {\n const reader = response.body?.getReader();\n if (!reader) {\n return \"\";\n }\n\n // A browser's fetch abort also fails the stream, but a body that a service worker or a test\n // builds doesn't know the signal, so race each read against it too.\n let abort!: () => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => {\n reject(new Error(\"The request ended before its body arrived.\"));\n };\n });\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n\n const readChunk = () => Promise.race([reader.read(), aborted]);\n const decoder = new TextDecoder();\n let text = \"\";\n let size = 0;\n try {\n let chunk = await readChunk();\n while (!chunk.done) {\n size += chunk.value.byteLength;\n if (size > RESPONSE_BODY_LIMIT_BYTES) {\n // Release the connection instead of downloading the rest.\n await reader.cancel();\n return undefined;\n }\n\n text += decoder.decode(chunk.value, { stream: true });\n chunk = await readChunk();\n }\n\n return text + decoder.decode();\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n}\n\n/**\n * Reads the optional size hint of a 413 body, for example {\"maxBytes\":65536}.\n * @param text The body text.\n * @returns The hint when it's a positive safe integer, otherwise undefined.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function maxBytesOf(text: string): number | undefined {\n const parsed: unknown = JSON.parse(text);\n const hint = isObject(parsed) ? parsed.maxBytes : undefined;\n\n return typeof hint === \"number\" && Number.isSafeInteger(hint) && hint > 0 ? hint : undefined;\n}\n\n/**\n * Reads the partialSuccess of an OTLP export answer, for example\n * {\"partialSuccess\":{\"rejectedLogRecords\":\"2\",\"errorMessage\":\"...\"}}.\n * @param text The answer's body text.\n * @param kind Kind of the batch, which names the count's field.\n * @returns What the server rejected or warned about, or undefined for a full success.\n * @throws SyntaxError when the text isn't JSON.\n */\nexport function partialSuccessOf(text: string, kind: BatchKind): PartialSuccess | undefined {\n // OTLP allows an empty body for a full success.\n if (text.trim() === \"\") {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(text);\n const partial = isObject(parsed) ? parsed.partialSuccess : undefined;\n if (!isObject(partial)) {\n return undefined;\n }\n\n const rejected = countOf(partial[REJECTED_FIELDS[kind]]);\n const message =\n typeof partial.errorMessage === \"string\"\n ? truncate(partial.errorMessage, SERVER_MESSAGE_MAX_CHARS)\n : \"\";\n if (rejected === 0 && message === \"\") {\n return undefined;\n }\n\n return { rejected, message };\n}\n\n/**\n * Reads an OTLP int64 count, which JSON gives as a digit string or as a number.\n * @param value The count field.\n * @returns The count, or 0 for anything that isn't a whole number above 0.\n */\nfunction countOf(value: unknown): number {\n // Up to 15 digits always fits in a safe integer.\n if (typeof value === \"string\" && /^\\d{1,15}$/.test(value)) {\n return Number(value);\n }\n\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n"],"mappings":";;;;;;;AAgBA,IAAa2B,KAAb,cAAoC,MAAM;CASxC,YACE,GACA,GACA,GACA,GACA,GACA,GACA;EAMA,AALA,MAAMC,CAAO,GAPGR,EAAA,MAAA,QAAA,KAAA,CAAA,GAEAA,EAAA,MAAA,UAAA,KAAA,CAAA,GACAA,EAAA,MAAA,gBAAA,KAAA,CAAA,GACAA,EAAA,MAAA,YAAA,KAAA,CAAA,GAJA,KAAA,OAAAS,GAEA,KAAA,SAAAC,GACA,KAAA,eAAAC,GACA,KAAA,WAAAC,GAIhB,KAAK,OAAO,kBAIRC,MAAU,KAAA,KACZ,OAAO,eAAe,MAAM,SAAS;GAAE,OAAOA;GAAO,UAAU;GAAM,cAAc;EAAK,CAAC;CAE7F;AACF;AASA,SAAgBC,GAAgB,GAA2C;CACzE,IAAI,CAACC,GACH;CAGF,IAAMC,IAAU,O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CAC3D,IAAMC,IAAkB,KAAK,MAAMJ,CAAI,GACjCK,IAAOpH,EAASmH,CAAM,IAAIA,EAAO,WAAW,KAAA;CAElD,OAAO,OAAOC,KAAS,YAAY,OAAO,cAAcA,CAAI,KAAKA,IAAO,IAAIA,IAAO,KAAA;AACrF;AAUA,SAAgBC,GAAiB,GAAc,GAA6C;CAE1F,IAAIN,EAAK,KAAK,MAAM,IAClB;CAGF,IAAMI,IAAkB,KAAK,MAAMJ,CAAI,GACjCO,IAAUtH,EAASmH,CAAM,IAAIA,EAAO,iBAAiB,KAAA;CAC3D,IAAI,CAACnH,EAASsH,CAAO,GACnB;CAGF,IAAMC,IAAWC,GAAQF,EAAQtB,GAAgBtF,GAAM,GACjDD,IACJ,OAAO6G,EAAQ,gBAAiB,WAC5BpH,EAASoH,EAAQ,cAAA,GAAsC,IACvD;CACN,IAAIC,MAAa,KAAK9G,MAAY,IAIlC,OAAO;EAAE;EAAU;CAAQ;AAC7B;AAOA,SAAS+G,GAAQ,GAAwB;CAMvC,OAJI,OAAOhG,KAAU,YAAY,aAAa,KAAKA,CAAK,IAC/C,OAAOA,CAAK,IAGd,OAAOA,KAAU,YAAY,OAAO,cAAcA,CAAK,KAAKA,IAAQ,IAAIA,IAAQ;AACzF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rotation-Cwct4ckk.js","names":["ROUTING_KEYS","ROUTING_RESET","newId","resolveEndpoint","resolveDestination","applyResolvedConfig","resolveConfig","PENDING_RULES","REFUSED","unapplied","given","input","key","applied","next","quiet","routingOf","copy","routing","value","validOptions","isObject","update","pending","timeoutMs","planRotation","host","options","previous","runtime","nextId","stoppedLoss","rule","held","live","stored","batch","rotateContext","plan","error","oldUrls","config","newUrls","url","old","closed","retired","carried","ids","diagnostics","clearStored","keepStored","context","seq","record"],"sources":["../src/core/rotation.ts"],"sourcesContent":["// src/core/rotation.ts\n//\n// Changes the security context. The runtime loads this module on the first\n// rotateSecurityContext(), because an app rotates rarely and the main graph shouldn't carry it.\n\nimport { FLUSH_TIMEOUT_MAX_MS, FLUSH_TIMEOUT_MS, ROUTING_KEYS, ROUTING_RESET } from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type {\n ObservabilityConfig,\n ResolvedConfig,\n RoutingOptions,\n SecurityContextRotationOptions,\n SecurityContextUpdate,\n} from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport { newId } from \"../utils/identity\";\nimport { applyResolvedConfig, resolveConfig, resolveDestination, resolveEndpoint } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { ObservabilityRuntime } from \"./runtime\";\nimport type { Sender } from \"./sender\";\nimport { clearStored, keepStored, type StoreAccess } from \"../storage/stored-context\";\n\n/** What to do with the old context's records. */\ntype PendingRule = NonNullable<SecurityContextRotationOptions[\"pending\"]>;\n\n/** The rules a rotation accepts. */\nconst PENDING_RULES: readonly string[] = [\"discard\", \"flush\", \"retain\", \"carry\"];\n\n/** Stands in for the current value when a check resolves a URL, so a refused URL returns it. */\nconst REFUSED = Symbol(\"refused\");\n\n/**\n * The runtime's private state that a rotation changes. The runtime's fields stay private, and\n * the rotation can only make these changes.\n */\nexport interface RotationHost {\n /** The runtime, for its config, diagnostics and the state that other calls change too. */\n runtime: ObservabilityRuntime;\n /** A reporter that nobody reads, for a check that repeats a resolve the app already saw. */\n quiet: Diagnostics;\n /** Waits for a delivery stack load in progress. */\n senderLoaded(): Promise<void>;\n /**\n * Removes the routing settings in a console-only runtime.\n * @param input The settings of the next context.\n * @returns The settings the runtime accepts.\n */\n allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig>;\n /** Stops delivery after a rejected rotation. */\n closeDelivery(): Promise<void>;\n /** Sends the old context's open points, and ends its trace and journey. */\n closeContext(): void;\n /**\n * Takes the old context's held records and its sender, so nothing new goes to them.\n * @returns The records, the sender, and true if a failed rotation had closed the context.\n */\n /** Returns what opening the store needs, for a rotation with no old sender. */\n storeAccess(): StoreAccess;\n takeOld(): {\n held: LogRecord[];\n sender: Sender | undefined;\n closed: boolean;\n carried: LogBatch[];\n };\n /**\n * Reports records that belong to neither context.\n * @param records The records.\n */\n drop(records: LogRecord[]): void;\n /** Starts a new identity epoch, without the old identity's remote rules. */\n advanceIdentity(): void;\n /** Opens delivery again and loads the new context's sender. */\n openDelivery(): Promise<void>;\n /**\n * Lets records through again, unless a later rotation waits.\n * @param seq Number of this rotation call.\n */\n endRotation(seq: number): void;\n /**\n * Routes one carried record.\n * @param record The record.\n */\n route(record: LogRecord): void;\n /**\n * Stores the carried batches again under the new context.\n * @param stored The old context's stored batches.\n */\n adopt(stored: LogBatch[]): Promise<void>;\n}\n\n/** A checked rotation, ready to apply. */\ninterface RotationPlan {\n /** The config of the next context. */\n next: ResolvedConfig;\n /** The next context's ambient attributes, or undefined to clear them. */\n context: Record<string, unknown> | undefined;\n /** What to do with the old context's records. */\n pending: PendingRule;\n /** Maximum wait for an old-context flush, in milliseconds. */\n timeoutMs: number;\n /** The old context's id. */\n previous: string;\n}\n\n/**\n * Returns the routing keys that the next config doesn't hold as the rotation gave them. A URL\n * goes through the same check as in configure(), so the endpoint rules live in config.ts only.\n * A warning, for example a pair of settings that does nothing, isn't such a key.\n * @param input The rotation's routing settings.\n * @param next The resolved config of the next context.\n * @param quiet A reporter that nobody reads, because the real resolve reported every fault.\n * @returns The keys whose value couldn't be applied.\n */\nfunction unapplied(\n input: Partial<ObservabilityConfig>,\n next: ResolvedConfig,\n quiet: Diagnostics,\n): string[] {\n return ROUTING_KEYS.filter((key) => {\n const given: unknown = input[key];\n const applied: unknown = next[key];\n\n // An undefined key resets to its default.\n if (given === undefined) {\n return false;\n }\n\n // A refused URL gives back the marker, and an accepted one its stored form. The serializer\n // check can still turn an accepted signal endpoint off, and that doesn't match either.\n if (key === \"endpoint\") {\n return resolveEndpoint(given, REFUSED, quiet) !== applied;\n }\n\n if (key === \"metricsEndpoint\" || key === \"tracesEndpoint\") {\n return resolveDestination(key, given, REFUSED, quiet) !== applied;\n }\n\n // null removes a hook or the headers.\n return given === null ? applied !== undefined : applied !== given;\n });\n}\n\n/**\n * Copies the routing settings of a rotation update. Each other key is reported and left out,\n * so a rotation can't remove redact or change a capture setting.\n * @param routing The update's routing settings.\n * @param runtime The runtime that reports a key it ignores.\n * @returns The reset routing settings with the update's values on top.\n */\nfunction routingOf(\n routing: RoutingOptions,\n runtime: ObservabilityRuntime,\n): Partial<ObservabilityConfig> {\n const copy: Partial<ObservabilityConfig> = { ...ROUTING_RESET };\n\n for (const key of Object.keys(routing)) {\n if ((ROUTING_KEYS as readonly string[]).includes(key)) {\n const value: unknown = Reflect.get(routing, key);\n Object.assign(copy, { [key]: value });\n } else {\n runtime.diagnostics.report(\n \"config.invalid\",\n `rotateSecurityContext() ignores routing.${key}. A rotation changes only the routing settings.`,\n );\n }\n }\n\n return copy;\n}\n\n/**\n * Checks whether the rotation options are usable.\n * @param update New identity, routing settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for the old records to flush.\n * @returns True if the call can go ahead.\n */\nfunction validOptions(update: SecurityContextUpdate, pending: string, timeoutMs: number): boolean {\n return (\n isObject(update) &&\n isObject(update.routing) &&\n // A string would give one attribute for each character.\n isObject(update.context ?? {}) &&\n PENDING_RULES.includes(pending) &&\n Number.isFinite(timeoutMs) &&\n timeoutMs >= 0 &&\n timeoutMs <= FLUSH_TIMEOUT_MAX_MS &&\n (update.id === undefined || (typeof update.id === \"string\" && update.id.length > 0))\n );\n}\n\n/**\n * Checks a rotation's arguments and builds the next config. Nothing changes before it returns.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @returns The checked rotation. It rejects for a setting it can't apply.\n */\nasync function planRotation(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n): Promise<RotationPlan> {\n const { runtime } = host;\n // Wait for a delivery stack load first. A rejection then closes the sender that the load\n // built, and no late sender can drain the old batches afterwards.\n await host.senderLoaded();\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? FLUSH_TIMEOUT_MS;\n\n if (!validOptions(update, pending, timeoutMs)) {\n throw new Error(\"Invalid security-context rotation options.\");\n }\n\n const previous = runtime.config.securityContext.id;\n const nextId = update.id ?? newId(runtime.diagnostics);\n\n if (nextId === previous) {\n throw new Error(\"A rotation requires a different security-context id.\");\n }\n\n const input = host.allowed({\n ...routingOf(update.routing, runtime),\n securityContext: { id: nextId },\n });\n // The base has no old routing values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(input, runtime.diagnostics, { ...runtime.config, ...ROUTING_RESET });\n\n if (unapplied(input, next, host.quiet).length > 0) {\n throw new Error(\"Invalid routing settings for the next security context.\");\n }\n\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n return { next, context, pending, timeoutMs, previous };\n}\n\n/**\n * Lists the records that a rotation loses when shutdown() stops it right after the retire.\n * @param rule The rotation's rule for the old records.\n * @param held The records that waited in the runtime.\n * @param live The held records and the old sender's records from memory.\n * @param stored The batches that the retire took from storage.\n * @returns The records that nothing keeps now.\n */\nfunction stoppedLoss(\n rule: PendingRule,\n held: LogRecord[],\n live: LogRecord[],\n stored: readonly LogBatch[],\n): LogRecord[] {\n // retain stored the sender's records, but the held ones wait for keepStored().\n if (rule === \"retain\") {\n return held;\n }\n\n // carry leaves the stored batches in storage, and routes the live records only later.\n if (rule === \"carry\") {\n return live;\n }\n\n // discard and flush removed the stored batches with the retire.\n return [...live, ...stored.flatMap((batch) => batch.records)];\n}\n\n/**\n * Checks the new settings, stops the old delivery and starts the new context. A rejection\n * closes the old context's delivery, because the app asked to leave it.\n * @param host The runtime's rotation operations.\n * @param update New identity, routing settings and attributes.\n * @param options What to do with the old records, and the flush deadline.\n * @param seq Number of this call.\n * @returns Promise that resolves when the context change completes.\n */\nexport async function rotateContext(\n host: RotationHost,\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions,\n seq: number,\n): Promise<void> {\n const { runtime } = host;\n const { config } = runtime;\n let plan: RotationPlan;\n\n try {\n plan = await planRotation(host, update, options);\n } catch (error) {\n await host.closeDelivery();\n throw error;\n }\n\n // shutdown() ran while the plan waited for the sender load. A discard already stopped that\n // sender, so a retire now would drain and remove the old context's stored batches.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n const { next, context, pending, timeoutMs, previous } = plan;\n\n // The plan's base has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n config.endpoint,\n config.metricsEndpoint,\n config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n host.closeContext();\n const { held, sender: old, closed, carried } = host.takeOld();\n // After a failed rotation, the parked sender holds the closed context's records. They must\n // never go out with the old settings, so \"flush\" removes them as \"discard\" does.\n const rule = closed && pending === \"flush\" ? \"discard\" : pending;\n const retired = (await old?.retire(rule, timeoutMs, previous)) ?? { buffered: [], stored: [] };\n const live = [...held, ...retired.buffered];\n // A carry during a pause left stored batches that no sender adopted. This rule covers them too.\n const stored = [...carried, ...retired.stored];\n\n // shutdown() ran during the retire, so the rotation didn't happen and mustn't resolve. What the\n // retire took out of memory or storage has no owner now. The carried batches go back, so the\n // shutdown's clearStorage can still find them.\n if (runtime.isDestroyed()) {\n host.drop(stoppedLoss(rule, held, live, retired.stored));\n await host.adopt(carried);\n throw new Error(\"The runtime has stopped.\");\n }\n\n if (rule !== \"retain\" && rule !== \"carry\") {\n host.drop([...live, ...stored.flatMap((batch) => batch.records)]);\n }\n\n // With no old sender, nothing else removes the old context's stored batches, and a logout\n // must. Deleting is the one storage access that a pause or a consent flow allows.\n const { diagnostics } = runtime;\n if (!old && (rule === \"discard\" || rule === \"flush\")) {\n const ids = carried.map((batch) => batch.id);\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove the stored batches of the old context.\",\n () => clearStored(host.storeAccess(), \"context\", ids),\n );\n }\n\n // Retain keeps what waited in memory under the old context, as a sender does with its own.\n if (rule === \"retain\" && (held.length > 0 || carried.length > 0)) {\n await diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not store the records of the old context.\",\n () => keepStored(host.storeAccess(), held, carried),\n );\n }\n\n // shutdown() ran during the storage step. Applying the new context now would make its\n // clearStorage remove the wrong context's batches. Nothing is lost here: discard and flush\n // reported their records above, and retain stored its records under the old context.\n if (runtime.isDestroyed()) {\n throw new Error(\"The runtime has stopped.\");\n }\n\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = config.lockConfiguration;\n // Replace all routing settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(config, next);\n host.advanceIdentity();\n runtime.context.clear();\n\n if (context) {\n runtime.context.merge(context);\n }\n\n runtime.breadcrumbs.clear();\n runtime.newSession();\n runtime.builder.invalidateResource();\n await host.openDelivery();\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n host.endRotation(seq);\n\n if (pending === \"carry\") {\n for (const record of live) {\n host.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n await host.adopt(stored);\n }\n\n runtime.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n}\n"],"mappings":";;;;;;AA2BA,IAAMO,IAAmC;CAAC;CAAW;CAAS;CAAU;AAAO,GAGzEC,IAAU,OAAO,SAAS;AAoFhC,SAASC,EACP,GACA,GACA,GACU;CACV,OAAOT,EAAa,QAAQ,MAAQ;EAClC,IAAMU,IAAiBC,EAAMC,IACvBC,IAAmBC,EAAKF;EAkB9B,OAfIF,MAAU,KAAA,IACL,KAKLE,MAAQ,aACHT,EAAgBO,GAAOF,GAASO,CAAK,MA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AS;EACvB,KAAK,IAAM+B,KAAUpB,GACnB,EAAK,MAAMoB,CAAM;EAInB,MAAM5B,EAAK,MAAMS,CAAM;CACzB;CAEA,EAAQ,YAAY,OAAO,oBAAoB,6CAA6C,EAC1F,WACF,CAAC;AACH"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CqdJhTxH.cjs"),t=require("./guards-EjG3ahFp.cjs"),n=require("./identity-DlWRIuwy.cjs"),r=require("./config-DUs7uHHt.cjs"),i=require("./stored-context-CXt7eHZL.cjs");var a=[`discard`,`flush`,`retain`,`carry`],o=Symbol(`refused`);function s(t,n,i){return e.An.filter(e=>{let a=t[e],s=n[e];return a===void 0?!1:e===`endpoint`?r.a(a,o,i)!==s:e===`metricsEndpoint`||e===`tracesEndpoint`?r.i(e,a,o,i)!==s:a===null?s!==void 0:s!==a})}function c(t,n){let r={...e.jn};for(let i of Object.keys(t))if(e.An.includes(i)){let e=Reflect.get(t,i);Object.assign(r,{[i]:e})}else n.diagnostics.report(`config.invalid`,`rotateSecurityContext() ignores routing.${i}. A rotation changes only the routing settings.`);return r}function l(e,n,r){return t.n(e)&&t.n(e.routing)&&t.n(e.context??{})&&a.includes(n)&&Number.isFinite(r)&&r>=0&&r<=6e5&&(e.id===void 0||typeof e.id==`string`&&e.id.length>0)}async function u(t,i,a){let{runtime:o}=t;await t.senderLoaded();let u=a.pending??`discard`,d=a.timeoutMs??5e3;if(!l(i,u,d))throw Error(`Invalid security-context rotation options.`);let f=o.config.securityContext.id,p=i.id??n.i(o.diagnostics);if(p===f)throw Error(`A rotation requires a different security-context id.`);let m=t.allowed({...c(i.routing,o),securityContext:{id:p}}),h=r.r(m,o.diagnostics,{...o.config,...e.jn});if(s(m,h,t.quiet).length>0)throw Error(`Invalid routing settings for the next security context.`);return{next:h,context:i.context?Object.fromEntries(Object.entries(i.context)):void 0,pending:u,timeoutMs:d,previous:f}}function d(e,t,n,r){return e===`retain`?t:e===`carry`?n:[...n,...r.flatMap(e=>e.records)]}async function f(e,t,n,a){let{runtime:o}=e,{config:s}=o,c;try{c=await u(e,t,n)}catch(t){throw await e.closeDelivery(),t}if(o.isDestroyed())throw Error(`The runtime has stopped.`);let{next:l,context:f,pending:p,timeoutMs:m,previous:h}=c,g=new Set([s.endpoint,s.metricsEndpoint,s.tracesEndpoint]),_=new Set([l.endpoint,l.metricsEndpoint,l.tracesEndpoint]);l.capture.ignoreUrls=l.capture.ignoreUrls.filter(e=>!g.has(e)||_.has(e)),e.closeContext();let{held:v,sender:y,closed:b,carried:x}=e.takeOld(),S=b&&p===`flush`?`discard`:p,C=await y?.retire(S,m,h)??{buffered:[],stored:[]},w=[...v,...C.buffered],T=[...x,...C.stored];if(o.isDestroyed())throw e.drop(d(S,v,w,C.stored)),await e.adopt(x),Error(`The runtime has stopped.`);S!==`retain`&&S!==`carry`&&e.drop([...w,...T.flatMap(e=>e.records)]);let{diagnostics:E}=o;if(!y&&(S===`discard`||S===`flush`)){let t=x.map(e=>e.id);await E.guardAsync(`storage.degraded`,`The library could not remove the stored batches of the old context.`,()=>i.clearStored(e.storeAccess(),`context`,t))}if(S===`retain`&&(v.length>0||x.length>0)&&await E.guardAsync(`storage.degraded`,`The library could not store the records of the old context.`,()=>i.keepStored(e.storeAccess(),v,x)),o.isDestroyed())throw Error(`The runtime has stopped.`);if(l.lockConfiguration=s.lockConfiguration,r.n(s,l),e.advanceIdentity(),o.context.clear(),f&&o.context.merge(f),o.breadcrumbs.clear(),o.newSession(),o.builder.invalidateResource(),await e.openDelivery(),e.endRotation(a),p===`carry`){for(let t of w)e.route(t);await e.adopt(T)}o.diagnostics.report(`security.rotated`,`The runtime rotated its security context.`,{pending:p})}exports.rotateContext=f;
|
|
2
|
-
//# sourceMappingURL=rotation-D4qUAHAu.cjs.map
|