@utk09/ui-observability 1.1.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 +42 -0
- package/dist/{batch-D3NHhF9L.js → batch-120Kc9jr.js} +3 -3
- package/dist/{batch-D3NHhF9L.js.map → batch-120Kc9jr.js.map} +1 -1
- package/dist/{batch-DnYRJqhU.cjs → batch-C3uNp5kU.cjs} +2 -2
- package/dist/{batch-DnYRJqhU.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
- package/dist/bus/bus.d.cts +5 -0
- package/dist/bus/bus.d.ts +5 -0
- package/dist/bus-Dj8IEVcC.cjs +2 -0
- package/dist/bus-Dj8IEVcC.cjs.map +1 -0
- package/dist/{bus-dw7T92sO.js → bus-DyNafxZN.js} +104 -94
- 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/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-SHPAvS4U.js → compression-BWkDWY3v.js} +2 -2
- package/dist/{compression-SHPAvS4U.js.map → compression-BWkDWY3v.js.map} +1 -1
- package/dist/{compression-C0hUHKR-.cjs → compression-CEVe7NPX.cjs} +2 -2
- package/dist/{compression-C0hUHKR-.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-CSNcS7OZ.js → config-DK1Zf7jn.js} +83 -85
- package/dist/config-DK1Zf7jn.js.map +1 -0
- package/dist/{console-BsM-fSCQ.js → console-CAyCQOpm.js} +5 -5
- package/dist/{console-BsM-fSCQ.js.map → console-CAyCQOpm.js.map} +1 -1
- package/dist/{console-Dkxs6IVQ.cjs → console-Dk6GH4yj.cjs} +2 -2
- package/dist/{console-Dkxs6IVQ.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
- package/dist/{constants-BwJDXzj6.js → constants-CEHN6KuY.js} +42 -21
- 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 +11 -0
- package/dist/constants.d.ts +11 -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/sender.d.cts +3 -2
- package/dist/core/sender.d.ts +3 -2
- package/dist/{debug-bundle-B2v6Cym-.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
- package/dist/{debug-bundle-B2v6Cym-.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
- package/dist/{debug-bundle-Cs_YWzTa.js → debug-bundle-w78W46zr.js} +4 -4
- package/dist/{debug-bundle-Cs_YWzTa.js.map → debug-bundle-w78W46zr.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.js +22 -22
- 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-Q3Ng1ciC.js → errors-C-LYbqyB.js} +27 -24
- package/dist/errors-C-LYbqyB.js.map +1 -0
- package/dist/{factory-DV17sm2p.js → factory-BHYrcSaU.js} +42 -31
- 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-BgtHyY4u.js → identity-Byh3gCdT.js} +11 -11
- package/dist/{identity-BgtHyY4u.js.map → identity-Byh3gCdT.js.map} +1 -1
- package/dist/{identity-CvuyqZk7.cjs → identity-BzAzdQyv.cjs} +2 -2
- package/dist/{identity-CvuyqZk7.cjs.map → identity-BzAzdQyv.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +539 -534
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-e-13ZLWm.js → indexeddb-storage-BYywz-v6.js} +4 -4
- package/dist/{indexeddb-storage-e-13ZLWm.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
- package/dist/{indexeddb-storage-D4KVcqdD.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
- package/dist/{indexeddb-storage-D4KVcqdD.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
- package/dist/{interactions-OK85T-Dk.cjs → interactions-BXzEel4F.cjs} +2 -2
- package/dist/interactions-BXzEel4F.cjs.map +1 -0
- package/dist/{interactions-Byxf1C82.js → interactions-DdKPMWIN.js} +12 -12
- package/dist/interactions-DdKPMWIN.js.map +1 -0
- package/dist/{journey-nMbob3OB.cjs → journey-BUmsrgaw.cjs} +2 -2
- package/dist/{journey-nMbob3OB.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
- package/dist/{journey-C93FTYcs.js → journey-Nu655gEO.js} +3 -3
- package/dist/{journey-C93FTYcs.js.map → journey-Nu655gEO.js.map} +1 -1
- package/dist/{library-console-DJUQzcgM.cjs → library-console-DdIlzzph.cjs} +2 -2
- package/dist/{library-console-DJUQzcgM.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
- package/dist/{library-console-DklSmucS.js → library-console-amePMnP8.js} +2 -2
- package/dist/{library-console-DklSmucS.js.map → library-console-amePMnP8.js.map} +1 -1
- package/dist/{library-request-UGEwOHpf.js → library-request-Cv7C05jf.js} +2 -2
- package/dist/{library-request-UGEwOHpf.js.map → library-request-Cv7C05jf.js.map} +1 -1
- package/dist/{library-request-kY9iTpIF.cjs → library-request-DO3Ec7KE.cjs} +2 -2
- package/dist/{library-request-kY9iTpIF.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
- package/dist/{lifecycle-DaMdH_X7.cjs → lifecycle-B5yfH5is.cjs} +2 -2
- package/dist/{lifecycle-DaMdH_X7.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
- package/dist/{lifecycle-B2PlIuQu.js → lifecycle-CMHz2Zbs.js} +2 -2
- package/dist/{lifecycle-B2PlIuQu.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
- package/dist/{log-record-DSt2P-Sr.js → log-record-B_nSqxoe.js} +2 -2
- package/dist/{log-record-DSt2P-Sr.js.map → log-record-B_nSqxoe.js.map} +1 -1
- package/dist/{log-record-Bmx6etMh.cjs → log-record-Bdywwg0k.cjs} +2 -2
- package/dist/{log-record-Bmx6etMh.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
- package/dist/{long-frames-Bamjs1WV.js → long-frames-6NGl1-uN.js} +3 -3
- package/dist/{long-frames-Bamjs1WV.js.map → long-frames-6NGl1-uN.js.map} +1 -1
- package/dist/{long-frames-lhtONgGt.cjs → long-frames-D9DfSWqv.cjs} +2 -2
- package/dist/{long-frames-lhtONgGt.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
- package/dist/models/config.d.cts +4 -3
- package/dist/models/config.d.ts +4 -3
- package/dist/{network-BCn8Gn47.cjs → network-BNHBI0Fc.cjs} +2 -2
- package/dist/{network-BCn8Gn47.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
- package/dist/{network-Cg1L2w2r.js → network-Cc3tSB7e.js} +13 -13
- package/dist/{network-Cg1L2w2r.js.map → network-Cc3tSB7e.js.map} +1 -1
- package/dist/{observed-windows-BrwaJNlj.js → observed-windows-8JtCsIr1.js} +3 -3
- package/dist/{observed-windows-BrwaJNlj.js.map → observed-windows-8JtCsIr1.js.map} +1 -1
- package/dist/{observed-windows-B3gJkdql.cjs → observed-windows-BlE25nrn.cjs} +2 -2
- package/dist/{observed-windows-B3gJkdql.cjs.map → observed-windows-BlE25nrn.cjs.map} +1 -1
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{otlp-D6dRZyB8.js → otlp-Btix3EBa.js} +7 -7
- package/dist/{otlp-D6dRZyB8.js.map → otlp-Btix3EBa.js.map} +1 -1
- package/dist/{otlp-CrAWkQdO.cjs → otlp-CFSW-Dno.cjs} +2 -2
- package/dist/{otlp-CrAWkQdO.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-8DLhjddo.js → platform-Dba6R3Hp.js} +22 -9
- package/dist/platform-Dba6R3Hp.js.map +1 -0
- package/dist/{profiler-BaXSqCfz.js → profiler-DNKcqu09.js} +19 -19
- package/dist/{profiler-BaXSqCfz.js.map → profiler-DNKcqu09.js.map} +1 -1
- package/dist/{profiler-BvWW2kNM.cjs → profiler-DpoPi1hH.cjs} +2 -2
- package/dist/{profiler-BvWW2kNM.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
- package/dist/{profiler-frames-DeaBiB-5.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
- package/dist/{profiler-frames-DeaBiB-5.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
- package/dist/{profiler-frames-C4ySHN0X.js → profiler-frames-CGXZeZ_3.js} +4 -4
- package/dist/{profiler-frames-C4ySHN0X.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
- package/dist/{remote-rules-Dq9xe7Qn.js → remote-rules-DNK96vLa.js} +15 -15
- package/dist/{remote-rules-Dq9xe7Qn.js.map → remote-rules-DNK96vLa.js.map} +1 -1
- package/dist/{remote-rules-D7L6D_D2.cjs → remote-rules-DuMFRlit.cjs} +2 -2
- package/dist/{remote-rules-D7L6D_D2.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-B0M8kWz_.js → replay-Dy6OiaOZ.js} +89 -62
- package/dist/replay-Dy6OiaOZ.js.map +1 -0
- package/dist/{reports-ojuMKGO7.cjs → reports-CGK9YQch.cjs} +2 -2
- package/dist/{reports-ojuMKGO7.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
- package/dist/{reports--8APRLa-.js → reports-CX57-S9s.js} +3 -3
- package/dist/{reports--8APRLa-.js.map → reports-CX57-S9s.js.map} +1 -1
- package/dist/{resource-timing-BzR05rE-.js → resource-timing-CWVDCbrY.js} +4 -4
- package/dist/{resource-timing-BzR05rE-.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
- package/dist/{resource-timing-pAG3ZhB5.cjs → resource-timing-DalulXiR.cjs} +2 -2
- package/dist/{resource-timing-pAG3ZhB5.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-BWvwKQ2p.js → response-body-yi92Rpvo.js} +100 -100
- package/dist/response-body-yi92Rpvo.js.map +1 -0
- package/dist/{rotation-BylN1B9e.js → rotation-ChBbNDE2.js} +24 -24
- 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-zXA6r-Nw.js → sampling-DZTOD28D.js} +6 -6
- package/dist/{sampling-zXA6r-Nw.js.map → sampling-DZTOD28D.js.map} +1 -1
- package/dist/{sampling-B46LW0cy.cjs → sampling-wAVJIZXp.cjs} +2 -2
- package/dist/{sampling-B46LW0cy.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
- package/dist/{sanitize-DjnR6RXR.js → sanitize-B2GKlSFp.js} +2 -2
- package/dist/{sanitize-DjnR6RXR.js.map → sanitize-B2GKlSFp.js.map} +1 -1
- package/dist/{sanitize-Qj6LuZqp.cjs → sanitize-BZdhoghq.cjs} +2 -2
- package/dist/{sanitize-Qj6LuZqp.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
- package/dist/{sender-Bdp-TAS4.js → sender-BRSpc7R8.js} +175 -161
- 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-CSttrAsw.js → stored-context-df1dEnht.js} +10 -8
- package/dist/stored-context-df1dEnht.js.map +1 -0
- package/dist/{storm-DKlpv0FL.js → storm-U3_ek1nA.js} +2 -2
- package/dist/{storm-DKlpv0FL.js.map → storm-U3_ek1nA.js.map} +1 -1
- package/dist/{storm-BHgI12iS.cjs → storm-qiE_AMC7.cjs} +2 -2
- package/dist/{storm-BHgI12iS.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-BcOB8A2e.js → unclean-exit-Bj6gYHeL.js} +2 -2
- package/dist/{unclean-exit-BcOB8A2e.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
- package/dist/{unclean-exit-BYPYYkQ5.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
- package/dist/{unclean-exit-BYPYYkQ5.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
- package/dist/{user-timing-BsU2wQKE.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
- package/dist/{user-timing-BsU2wQKE.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
- package/dist/{user-timing-4KIJ74Vi.js → user-timing-Duz0d-OA.js} +2 -2
- package/dist/{user-timing-4KIJ74Vi.js.map → user-timing-Duz0d-OA.js.map} +1 -1
- 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-Zg0hj1LB.js → web-socket-CE_9Q22z.js} +5 -5
- package/dist/{web-socket-Zg0hj1LB.js.map → web-socket-CE_9Q22z.js.map} +1 -1
- package/dist/{web-socket-Cs1ZbmmN.cjs → web-socket-sm3rD-A_.cjs} +2 -2
- package/dist/{web-socket-Cs1ZbmmN.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-DFYXIFus.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
- package/dist/{worker-protocol-DFYXIFus.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
- package/dist/{worker-protocol-CYpAbrVl.js → worker-protocol-h4-tRWqy.js} +6 -6
- package/dist/{worker-protocol-CYpAbrVl.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
- package/dist/{worker-server--yGTadTA.cjs → worker-server-CF1yatXq.cjs} +2 -2
- package/dist/{worker-server--yGTadTA.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
- package/dist/worker-server-FYfKHQhJ.js +94 -0
- package/dist/{worker-server-BokySIII.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
- package/dist/{worker-transport-BdEvh_-a.cjs → worker-transport-COgY4RX8.cjs} +2 -2
- package/dist/{worker-transport-BdEvh_-a.cjs.map → worker-transport-COgY4RX8.cjs.map} +1 -1
- package/dist/{worker-transport-JK-Fby9J.js → worker-transport-jzX1IusG.js} +34 -34
- package/dist/{worker-transport-JK-Fby9J.js.map → worker-transport-jzX1IusG.js.map} +1 -1
- package/llms.txt +1 -2
- package/package.json +1 -1
- package/dist/bus-B__467mL.cjs +0 -2
- package/dist/bus-B__467mL.cjs.map +0 -1
- package/dist/bus-dw7T92sO.js.map +0 -1
- package/dist/config-CSNcS7OZ.js.map +0 -1
- package/dist/config-CybPP5VM.cjs +0 -2
- package/dist/config-CybPP5VM.cjs.map +0 -1
- package/dist/constants-BwJDXzj6.js.map +0 -1
- package/dist/constants-CtF52hIV.cjs +0 -2
- package/dist/constants-CtF52hIV.cjs.map +0 -1
- package/dist/errors-DP2RUm4V.cjs +0 -3
- package/dist/errors-DP2RUm4V.cjs.map +0 -1
- package/dist/errors-Q3Ng1ciC.js.map +0 -1
- package/dist/factory-DV17sm2p.js.map +0 -1
- package/dist/factory-K8O6gpux.cjs +0 -2
- package/dist/factory-K8O6gpux.cjs.map +0 -1
- package/dist/interactions-Byxf1C82.js.map +0 -1
- package/dist/interactions-OK85T-Dk.cjs.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-8DLhjddo.js.map +0 -1
- package/dist/platform-BqRc-7RO.cjs +0 -2
- package/dist/platform-BqRc-7RO.cjs.map +0 -1
- package/dist/replay-B0M8kWz_.js.map +0 -1
- package/dist/replay-QOFBpAXh.cjs +0 -2
- package/dist/replay-QOFBpAXh.cjs.map +0 -1
- package/dist/response-body-BWvwKQ2p.js.map +0 -1
- package/dist/response-body-CKEJ5itk.cjs +0 -3
- package/dist/response-body-CKEJ5itk.cjs.map +0 -1
- package/dist/rotation-BylN1B9e.js.map +0 -1
- package/dist/rotation-E2eKClIs.cjs +0 -2
- package/dist/rotation-E2eKClIs.cjs.map +0 -1
- package/dist/sender-Bdp-TAS4.js.map +0 -1
- package/dist/sender-DR7ZycZY.cjs +0 -2
- package/dist/sender-DR7ZycZY.cjs.map +0 -1
- package/dist/stored-context-BOu54M8Y.cjs +0 -2
- package/dist/stored-context-BOu54M8Y.cjs.map +0 -1
- package/dist/stored-context-CSttrAsw.js.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-BokySIII.js +0 -94
package/dist/core/sender.d.cts
CHANGED
|
@@ -65,7 +65,8 @@ export declare class Sender {
|
|
|
65
65
|
*/
|
|
66
66
|
static create(deps: SenderDeps): Promise<Sender>;
|
|
67
67
|
/**
|
|
68
|
-
* Adds a record to the pipeline.
|
|
68
|
+
* Adds a record to the pipeline. After a pagehide the exit flush sends it, because the batch
|
|
69
|
+
* timer won't fire in a closing document.
|
|
69
70
|
* @param record Record to deliver.
|
|
70
71
|
*/
|
|
71
72
|
push(record: LogRecord): void;
|
|
@@ -138,7 +139,7 @@ export declare class Sender {
|
|
|
138
139
|
* @param timeoutMs Maximum wait for a flush, in milliseconds.
|
|
139
140
|
* @param contextId Identity of the old delivery context.
|
|
140
141
|
* @returns The records that were in memory and the batches that were stored, after the
|
|
141
|
-
* delivery attempt.
|
|
142
|
+
* delivery attempt. A discard or a flush adds the context's emergency entries it removed.
|
|
142
143
|
*/
|
|
143
144
|
retire(policy: "discard" | "flush" | "retain" | "carry", timeoutMs: number, contextId: string): Promise<{
|
|
144
145
|
buffered: LogRecord[];
|
package/dist/core/sender.d.ts
CHANGED
|
@@ -65,7 +65,8 @@ export declare class Sender {
|
|
|
65
65
|
*/
|
|
66
66
|
static create(deps: SenderDeps): Promise<Sender>;
|
|
67
67
|
/**
|
|
68
|
-
* Adds a record to the pipeline.
|
|
68
|
+
* Adds a record to the pipeline. After a pagehide the exit flush sends it, because the batch
|
|
69
|
+
* timer won't fire in a closing document.
|
|
69
70
|
* @param record Record to deliver.
|
|
70
71
|
*/
|
|
71
72
|
push(record: LogRecord): void;
|
|
@@ -138,7 +139,7 @@ export declare class Sender {
|
|
|
138
139
|
* @param timeoutMs Maximum wait for a flush, in milliseconds.
|
|
139
140
|
* @param contextId Identity of the old delivery context.
|
|
140
141
|
* @returns The records that were in memory and the batches that were stored, after the
|
|
141
|
-
* delivery attempt.
|
|
142
|
+
* delivery attempt. A discard or a flush adds the context's emergency entries it removed.
|
|
142
143
|
*/
|
|
143
144
|
retire(policy: "discard" | "flush" | "retain" | "carry", timeoutMs: number, contextId: string): Promise<{
|
|
144
145
|
buffered: LogRecord[];
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./guards-EjG3ahFp.cjs"),t=require("./platform-
|
|
2
|
-
//# sourceMappingURL=debug-bundle-
|
|
1
|
+
const e=require("./guards-EjG3ahFp.cjs"),t=require("./platform-BZjp9wp1.cjs"),n=require("./sanitize-BZdhoghq.cjs"),r=require("./config-C0PtemvC.cjs");function i(n){return typeof n==`string`?/^[a-z][a-z\d+.-]*:\/\//i.test(n)?t.a(n,!1):n:Array.isArray(n)?n.map(i):e.n(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,i(t)])):n}function a(e,a,o){let s=e=>typeof e==`string`?t.a(e,!1):e,{capture:c,serializer:l}=e,u={...e,endpoint:s(e.endpoint),metricsEndpoint:s(e.metricsEndpoint),tracesEndpoint:s(e.tracesEndpoint),serializer:typeof l==`string`?l:l.name,redact:e.redact===r.t?`refused`:e.redact,processors:e.processors.map(e=>e===r.t?`refused`:e),capture:{...c,ignoreUrls:c.ignoreUrls.map(s),plugins:c.plugins.map(e=>e.name)},replay:{...e.replay,endpoint:s(e.replay.endpoint),headers:e.replay.headers!==null,plugins:e.replay.plugins.length,recordOptions:Object.keys(e.replay.recordOptions)}};return Reflect.deleteProperty(u,`headers`),i(n.n(u,a,o))}exports.configSummary=a;
|
|
2
|
+
//# sourceMappingURL=debug-bundle-DMzUfiQc.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-bundle-
|
|
1
|
+
{"version":3,"file":"debug-bundle-DMzUfiQc.cjs","names":["recordedUrl","isObject","REFUSE_RECORDS","sanitize","require_guards","require_platform","require_sanitize","require_config","stripUrls","value","key","entry","configSummary","cut","config","copy","serializer","hook","capture","plugin","limits","diagnostics"],"sources":["../src/core/debug-bundle.ts"],"sourcesContent":["// src/core/debug-bundle.ts\n//\n// Builds the config summary for a debug bundle. The runtime loads this module only when the\n// app asks for a bundle.\n\nimport type { ResolvedConfig } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { sanitize, type SanitizeLimits } from \"../utils/sanitize\";\nimport { REFUSE_RECORDS } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Strips the user info, query and fragment from every absolute URL in a JSON-safe value. The\n * endpoints also end up in `capture.ignoreUrls`, where the library puts them.\n * @param value JSON-safe value.\n * @returns The value with every URL trimmed.\n */\nfunction stripUrls(value: unknown): unknown {\n if (typeof value === \"string\") {\n return /^[a-z][a-z\\d+.-]*:\\/\\//i.test(value) ? recordedUrl(value, false) : value;\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUrls);\n }\n\n if (isObject(value)) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, stripUrls(entry)]));\n }\n\n return value;\n}\n\n/**\n * Copies the config for a support ticket, without the headers and with every URL trimmed. A\n * function becomes its name and a RegExp its text.\n * @param config Active configuration.\n * @param limits Limits for the copy, the same as for record attributes.\n * @param diagnostics Diagnostics reporter.\n * @returns JSON-safe copy of the config.\n */\nexport function configSummary(\n config: ResolvedConfig,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n // A relative endpoint has no scheme, so stripUrls() doesn't see it as a URL.\n const cut = (value: unknown): unknown =>\n typeof value === \"string\" ? recordedUrl(value, false) : value;\n const { capture, serializer } = config;\n const copy: Record<string, unknown> = {\n ...config,\n endpoint: cut(config.endpoint),\n metricsEndpoint: cut(config.metricsEndpoint),\n tracesEndpoint: cut(config.tracesEndpoint),\n // An object from the app can hold a key in any field, so only its name goes out.\n serializer: typeof serializer === \"string\" ? serializer : serializer.name,\n // The stand-in for a bad hook value shows as \"refused\", so the bundle says why nothing sends.\n redact: config.redact === REFUSE_RECORDS ? \"refused\" : config.redact,\n processors: config.processors.map((hook) => (hook === REFUSE_RECORDS ? \"refused\" : hook)),\n capture: {\n ...capture,\n ignoreUrls: capture.ignoreUrls.map(cut),\n plugins: capture.plugins.map((plugin) => plugin.name),\n },\n // The replay headers can carry a token, and recordOptions is the app's own object.\n replay: {\n ...config.replay,\n endpoint: cut(config.replay.endpoint),\n headers: config.replay.headers !== null,\n plugins: config.replay.plugins.length,\n recordOptions: Object.keys(config.replay.recordOptions),\n },\n };\n // Static headers can hold a token.\n Reflect.deleteProperty(copy, \"headers\");\n\n return stripUrls(sanitize(copy, limits, diagnostics)) as Record<string, unknown>;\n}\n"],"mappings":"A,sJAkBA,SAASQ,EAAU,EAAyB,CAa1C,OAZI,OAAOC,GAAU,SACZ,0BAA0B,KAAKA,CAAK,EAAIT,EAAAA,EAAYS,EAAO,EAAK,EAAIA,EAGzE,MAAM,QAAQA,CAAK,EACdA,EAAM,IAAID,CAAS,EAGxBP,EAAAA,EAASQ,CAAK,EACT,OAAO,YAAY,OAAO,QAAQA,CAAK,CAAC,CAAC,KAAK,CAACC,EAAKC,KAAW,CAACD,EAAKF,EAAUG,CAAK,CAAC,CAAC,CAAC,EAGzFF,CACT,CAUA,SAAgBG,EACd,EACA,EACA,EACyB,CAEzB,IAAMC,EAAO,GACX,OAAOJ,GAAU,SAAWT,EAAAA,EAAYS,EAAO,EAAK,EAAIA,EACpD,CAAE,UAAS,cAAeK,EAC1BC,EAAgC,CACpC,GAAGD,EACH,SAAUD,EAAIC,EAAO,QAAQ,EAC7B,gBAAiBD,EAAIC,EAAO,eAAe,EAC3C,eAAgBD,EAAIC,EAAO,cAAc,EAEzC,WAAY,OAAOE,GAAe,SAAWA,EAAaA,EAAW,KAErE,OAAQF,EAAO,SAAWZ,EAAAA,EAAiB,UAAYY,EAAO,OAC9D,WAAYA,EAAO,WAAW,IAAK,GAAUG,IAASf,EAAAA,EAAiB,UAAYe,CAAK,EACxF,QAAS,CACP,GAAGC,EACH,WAAYA,EAAQ,WAAW,IAAIL,CAAG,EACtC,QAASK,EAAQ,QAAQ,IAAK,GAAWC,EAAO,IAAI,CACtD,EAEA,OAAQ,CACN,GAAGL,EAAO,OACV,SAAUD,EAAIC,EAAO,OAAO,QAAQ,EACpC,QAASA,EAAO,OAAO,UAAY,KACnC,QAASA,EAAO,OAAO,QAAQ,OAC/B,cAAe,OAAO,KAAKA,EAAO,OAAO,aAAa,CACxD,CACF,EAIA,OAFA,QAAQ,eAAeC,EAAM,SAAS,EAE/BP,EAAUL,EAAAA,EAASY,EAAMK,EAAQC,CAAW,CAAC,CACtD,C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as e } from "./guards-BlYGRK4l.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n } from "./sanitize-
|
|
4
|
-
import { t as r } from "./config-
|
|
2
|
+
import { a as t } from "./platform-Dba6R3Hp.js";
|
|
3
|
+
import { n } from "./sanitize-B2GKlSFp.js";
|
|
4
|
+
import { t as r } from "./config-DK1Zf7jn.js";
|
|
5
5
|
// src/core/debug-bundle.ts
|
|
6
6
|
function i(n) {
|
|
7
7
|
return typeof n == "string" ? /^[a-z][a-z\d+.-]*:\/\//i.test(n) ? t(n, !1) : n : Array.isArray(n) ? n.map(i) : e(n) ? Object.fromEntries(Object.entries(n).map(([e, t]) => [e, i(t)])) : n;
|
|
@@ -32,4 +32,4 @@ function a(e, a, o) {
|
|
|
32
32
|
}
|
|
33
33
|
export { a as configSummary };
|
|
34
34
|
|
|
35
|
-
//# sourceMappingURL=debug-bundle-
|
|
35
|
+
//# sourceMappingURL=debug-bundle-w78W46zr.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-bundle-
|
|
1
|
+
{"version":3,"file":"debug-bundle-w78W46zr.js","names":["isObject","recordedUrl","REFUSE_RECORDS","stripUrls","value","key","entry","configSummary","cut","config","copy","serializer","hook","capture","plugin","sanitize","limits","diagnostics"],"sources":["../src/core/debug-bundle.ts"],"sourcesContent":["// src/core/debug-bundle.ts\n//\n// Builds the config summary for a debug bundle. The runtime loads this module only when the\n// app asks for a bundle.\n\nimport type { ResolvedConfig } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { sanitize, type SanitizeLimits } from \"../utils/sanitize\";\nimport { REFUSE_RECORDS } from \"./config\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Strips the user info, query and fragment from every absolute URL in a JSON-safe value. The\n * endpoints also end up in `capture.ignoreUrls`, where the library puts them.\n * @param value JSON-safe value.\n * @returns The value with every URL trimmed.\n */\nfunction stripUrls(value: unknown): unknown {\n if (typeof value === \"string\") {\n return /^[a-z][a-z\\d+.-]*:\\/\\//i.test(value) ? recordedUrl(value, false) : value;\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUrls);\n }\n\n if (isObject(value)) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, stripUrls(entry)]));\n }\n\n return value;\n}\n\n/**\n * Copies the config for a support ticket, without the headers and with every URL trimmed. A\n * function becomes its name and a RegExp its text.\n * @param config Active configuration.\n * @param limits Limits for the copy, the same as for record attributes.\n * @param diagnostics Diagnostics reporter.\n * @returns JSON-safe copy of the config.\n */\nexport function configSummary(\n config: ResolvedConfig,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n // A relative endpoint has no scheme, so stripUrls() doesn't see it as a URL.\n const cut = (value: unknown): unknown =>\n typeof value === \"string\" ? recordedUrl(value, false) : value;\n const { capture, serializer } = config;\n const copy: Record<string, unknown> = {\n ...config,\n endpoint: cut(config.endpoint),\n metricsEndpoint: cut(config.metricsEndpoint),\n tracesEndpoint: cut(config.tracesEndpoint),\n // An object from the app can hold a key in any field, so only its name goes out.\n serializer: typeof serializer === \"string\" ? serializer : serializer.name,\n // The stand-in for a bad hook value shows as \"refused\", so the bundle says why nothing sends.\n redact: config.redact === REFUSE_RECORDS ? \"refused\" : config.redact,\n processors: config.processors.map((hook) => (hook === REFUSE_RECORDS ? \"refused\" : hook)),\n capture: {\n ...capture,\n ignoreUrls: capture.ignoreUrls.map(cut),\n plugins: capture.plugins.map((plugin) => plugin.name),\n },\n // The replay headers can carry a token, and recordOptions is the app's own object.\n replay: {\n ...config.replay,\n endpoint: cut(config.replay.endpoint),\n headers: config.replay.headers !== null,\n plugins: config.replay.plugins.length,\n recordOptions: Object.keys(config.replay.recordOptions),\n },\n };\n // Static headers can hold a token.\n Reflect.deleteProperty(copy, \"headers\");\n\n return stripUrls(sanitize(copy, limits, diagnostics)) as Record<string, unknown>;\n}\n"],"mappings":";;;;;AAkBA,SAASG,EAAU,GAAyB;CAa1C,OAZI,OAAOC,KAAU,WACZ,0BAA0B,KAAKA,CAAK,IAAIH,EAAYG,GAAO,EAAK,IAAIA,IAGzE,MAAM,QAAQA,CAAK,IACdA,EAAM,IAAID,CAAS,IAGxBH,EAASI,CAAK,IACT,OAAO,YAAY,OAAO,QAAQA,CAAK,CAAC,CAAC,KAAK,CAACC,GAAKC,OAAW,CAACD,GAAKF,EAAUG,CAAK,CAAC,CAAC,CAAC,IAGzFF;AACT;AAUA,SAAgBG,EACd,GACA,GACA,GACyB;CAEzB,IAAMC,KAAO,MACX,OAAOJ,KAAU,WAAWH,EAAYG,GAAO,EAAK,IAAIA,GACpD,EAAE,YAAS,kBAAeK,GAC1BC,IAAgC;EACpC,GAAGD;EACH,UAAUD,EAAIC,EAAO,QAAQ;EAC7B,iBAAiBD,EAAIC,EAAO,eAAe;EAC3C,gBAAgBD,EAAIC,EAAO,cAAc;EAEzC,YAAY,OAAOE,KAAe,WAAWA,IAAaA,EAAW;EAErE,QAAQF,EAAO,WAAWP,IAAiB,YAAYO,EAAO;EAC9D,YAAYA,EAAO,WAAW,KAAK,MAAUG,MAASV,IAAiB,YAAYU,CAAK;EACxF,SAAS;GACP,GAAGC;GACH,YAAYA,EAAQ,WAAW,IAAIL,CAAG;GACtC,SAASK,EAAQ,QAAQ,KAAK,MAAWC,EAAO,IAAI;EACtD;EAEA,QAAQ;GACN,GAAGL,EAAO;GACV,UAAUD,EAAIC,EAAO,OAAO,QAAQ;GACpC,SAASA,EAAO,OAAO,YAAY;GACnC,SAASA,EAAO,OAAO,QAAQ;GAC/B,eAAe,OAAO,KAAKA,EAAO,OAAO,aAAa;EACxD;CACF;CAIA,OAFA,QAAQ,eAAeC,GAAM,SAAS,GAE/BP,EAAUY,EAASL,GAAMM,GAAQC,CAAW,CAAC;AACtD"}
|
package/dist/doctor.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-NtiQDWL_.cjs"),t=require("./compression-CEVe7NPX.cjs"),n=require("./otlp-CFSW-Dno.cjs");var r=1e4,i=0,a=1,o=2,s=`Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header "Name: value"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.`,c=`--header`,l=`--replay`,u=`--credentials`,d=`include`,f=5e6,p=5,m=`uiobs-doctor`,h=/^([\w!#$%&'*+.^`|~-]+): *([\x20-\x7e]+)$/,g=`<hidden>`,_=`Access-Control-Expose-Headers`,v=`Access-Control-Allow-Origin`,y=`Access-Control-Allow-Headers`,b=`Access-Control-Allow-Credentials`,x=`A browser refuses * with credentials: "include".`,S=`A browser does not read * as a wildcard with credentials: "include".`,C=`A browser never lets * cover authorization.`,w=`Add --credentials include to check that case.`,T=[e.pt,e.ft,e.dt,e.ut].map(e=>e.toLowerCase()),E=[...T,`origin`],D=[e.gt,e.mt].map(e=>e.toLowerCase()),O=`authorization`,k=[e.ht.toLowerCase()],A=[...k,...D];function j(){let t=crypto.randomUUID().replaceAll(`-`,``);return{timeUnixNano:`${String(Date.now())}000000`,traceId:t,spanId:t.slice(0,16),traceFlags:1,severityNumber:e.Gn.INFO,severityText:`INFO`,body:`uiobs doctor test record`,attributes:{},resource:{"service.name":m}}}async function M(e,t,n=r){try{return await fetch(e,{...t,redirect:`manual`,signal:AbortSignal.timeout(n)})}catch(e){let t=e instanceof Error?e.cause??e:e;return`The request failed. ${t instanceof Error?t.message:String(t)}`}}function N(e,t){return(e.headers.get(t)??``).toLowerCase().split(`,`).map(e=>e.trim())}function P(e,t,n,r){let i=N(e,t),a=r&&i.includes(`*`);return n.filter(e=>!i.includes(e)&&!(a&&e!==O))}var F=e=>e.ok?void 0:`The server returned ${String(e.status)}.`,I=e=>e.status===415?`The server returned ${String(e.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`:void 0;function L(e,t,n,...r){let i=typeof t==`string`?t:r.map(e=>e(t)).find(e=>e!==void 0);return{rule:e,pass:i===void 0,detail:i??n}}function R(e,t,n,r){let i=Object.keys(n).map(e=>e.toLowerCase());return{url:e,origin:t,custom:n,requestHeaders:[...T,...i],credentials:r}}function z({origin:e,credentials:t}){return n=>{let r=n.headers.get(v);return r===`*`&&t?`${v} is *. ${x} It must be ${e}.`:r!==e&&r!==`*`?`${v} is ${String(r)}. It must allow ${e}.`:t?B(n):void 0}}var B=e=>{let t=e.headers.get(b);return t===`true`?void 0:`${b} is ${String(t)}. It must be true with credentials: "include".`};function V(e){return typeof e==`string`?null:e.headers.get(v)}function H(e,{credentials:t},n=x){return e&&!t?` ${n} ${w}`:``}function U(e,t,{credentials:n}){return n&&N(e,t).includes(`*`)?` ${S}`:``}function W(e,t,n){return typeof e!=`string`&&N(e,t).includes(`*`)&&P(e,t,n,!1).length>0}function G({url:e,origin:t,requestHeaders:n}){return M(e,{method:`OPTIONS`,headers:{Origin:t,"Access-Control-Request-Method":`POST`,"Access-Control-Request-Headers":n.join(`, `)}})}function K(e,t){let n=H(V(e)===`*`,t),r=H(W(e,y,t.requestHeaders),t,S);return[L(`preflight`,e,`The server permits POST from this origin.${n}`,F,z(t)),L(`allowed headers`,e,`The server allows each request header of the library.${r}`,e=>{let n=P(e,y,t.requestHeaders,!t.credentials);if(n.length===0)return;let r=U(e,y,t),i=n.includes(O)&&N(e,y).includes(`*`)?` ${C}`:``;return`${y} must include ${n.join(`, `)}.${r}${i}`})]}function q({url:t,origin:n,custom:r},i,a){return(o,s,c,l={})=>M(t,{method:`POST`,headers:{...r,Origin:n,[e.pt]:i,[e.dt]:o,[e.ut]:String(s),...l},body:c},a)}async function J(n,r,i){let a=await t.t(i);return a?n(r,0,a,{[e.ft]:e.nt}):`This Node version has no CompressionStream.`}async function Y(t,r,i={},a=!1){let o=R(t,r,i,a),s=z(o),c=await G(o),{body:l,contentType:u}=n.r.serialize([j()]),d=q(o,u),f=crypto.randomUUID(),p=await d(f,0,l),m=await d(f,1,l),h=await J(d,crypto.randomUUID(),l),g=new URL(t);g.searchParams.set(e.an,crypto.randomUUID()),g.searchParams.set(e.on,`pagehide`);let v=o.requestHeaders.length>T.length?void 0:await M(g.toString(),{method:`POST`,headers:{Origin:r,[e.pt]:e.V},body:l}),y=typeof p==`string`?[]:P(p,_,D,!o.credentials),b=y.length>0?` Optional headers stay hidden: ${y.join(`, `)}.`:``,x=H(W(p,_,A),o,S);return[...K(c,o),L(`test batch`,p,`The server accepted a test batch.${H(V(p)===`*`,o)}`,F,s),L(`exposed headers`,p,`The server exposes Retry-After.${b}${x}`,e=>P(e,_,k,!o.credentials).length===0?void 0:`${_} must include retry-after.${U(e,_,o)}`),L(`gzip`,h,`The server accepted a gzip batch.`,F),L(`deduplication`,m,`The server accepted a repeated batch id. A client cannot see if it stored the batch again.`,F),v===void 0?{rule:`beacon`,pass:!0,detail:`The library sends no beacon with custom headers. The tool sent no beacon.`}:L(`beacon`,v,`The server accepted a text/plain batch.`,I,F)]}async function X(t,n,r={},i=!1){let a=R(t,n,r,i),o=z(a),s=await G(a),c=crypto.randomUUID(),l={"replay.id":c,"session.id":crypto.randomUUID(),"tab.id":crypto.randomUUID(),"service.name":m},u=(e,t)=>{let n=[{type:p,timestamp:Date.now(),data:{tag:m,payload:t}}];return JSON.stringify({...l,sequence:e,bytes:JSON.stringify(n).length,events:n})},d=e=>`${c}-${String(e)}`,h=q(a,e.z),g=u(0,`uiobs doctor test event`),_=await h(d(0),0,g),v=await h(d(0),1,g),y=await J(h,d(1),u(1,`uiobs doctor gzip event`)),b=await q(a,e.z,e._n)(d(2),0,u(2,`x`.repeat(f)));return[...K(s,a),L(`test segment`,_,`The server accepted a test segment.${H(V(_)===`*`,a)}`,F,o),L(`gzip`,y,`The server accepted a gzip segment.`,F),L(`large segment`,b,`The server accepted a segment of ${String(f)} bytes without gzip.`,e=>e.ok?void 0:`The server returned ${String(e.status)} for a segment of ${String(f)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`),L(`deduplication`,v,`The server accepted a repeated batch id. A client cannot see if it stored the segment again.`,F)]}function Z(e){let t=[],n=!1;for(let r=0;r<e.length;r+=2){if(e[r]===u&&e[r+1]===d){n=!0;continue}let i=e[r]===c?h.exec(e[r+1]):null;if(!i||E.includes(i[1].toLowerCase()))return;t.push([i[1],i[2]])}return{headers:Object.fromEntries(t),credentials:n}}function Q(e){if(!/^https?:\/\//i.test(e)||!URL.canParse(e))return!1;let{username:t,password:n}=new URL(e);return t===``&&n===``}var $=[`doctor`,`--origin`,l,c,u,d];function ee(e){if($.includes(e))return e;if(/^https?:\/\//i.test(e)&&URL.canParse(e)){let{origin:t,pathname:n}=new URL(e);return`${t}${n===`/`&&!e.endsWith(`/`)?``:n}`}return g}function te(e){return URL.canParse(e)&&new URL(e).origin===e}async function ne(e,t){let[n,r,c,u,...d]=e,f=d[0]===l,p=Z(f?d.slice(1):d);if(n!==`doctor`||c!==`--origin`||!Q(r)||!te(u)||!p)return t(s),t(`Received: ${JSON.stringify(e.map(ee))}`),o;let{headers:m,credentials:h}=p,g=await(f?X:Y)(r,u,m,h);for(let{rule:e,pass:n,detail:r}of g)t(`${n?`PASS`:`FAIL`} ${e}: ${r}`);return g.every(({pass:e})=>e)?i:a}exports.main=ne,exports.runDoctor=Y,exports.runReplayDoctor=X;
|
|
2
2
|
//# sourceMappingURL=doctor.cjs.map
|
package/dist/doctor.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as m } from "./compression-
|
|
3
|
-
import { r as h } from "./otlp-
|
|
1
|
+
import { Gn as e, V as t, _n as n, an as r, dt as i, ft as a, gt as o, ht as s, mt as c, nt as l, on as u, pt as d, ut as f, z as p } from "./constants-CEHN6KuY.js";
|
|
2
|
+
import { t as m } from "./compression-BWkDWY3v.js";
|
|
3
|
+
import { r as h } from "./otlp-Btix3EBa.js";
|
|
4
4
|
// src/doctor.ts
|
|
5
5
|
var g = 1e4, _ = 0, v = 1, y = 2, b = "Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.", x = "--header", S = "--replay", C = "--credentials", w = "include", T = 5e6, ee = 5, E = "uiobs-doctor", te = /^([\w!#$%&'*+.^`|~-]+): *([\x20-\x7e]+)$/, ne = "<hidden>", D = "Access-Control-Expose-Headers", O = "Access-Control-Allow-Origin", k = "Access-Control-Allow-Headers", A = "Access-Control-Allow-Credentials", j = "A browser refuses * with credentials: \"include\".", M = "A browser does not read * as a wildcard with credentials: \"include\".", re = "A browser never lets * cover authorization.", ie = "Add --credentials include to check that case.", N = [
|
|
6
6
|
d,
|
|
7
|
+
a,
|
|
7
8
|
i,
|
|
8
|
-
r,
|
|
9
9
|
f
|
|
10
10
|
].map((e) => e.toLowerCase()), ae = [...N, "origin"], P = [o, c].map((e) => e.toLowerCase()), F = "authorization", I = [s.toLowerCase()], oe = [...I, ...P];
|
|
11
11
|
function se() {
|
|
12
|
-
let
|
|
12
|
+
let t = crypto.randomUUID().replaceAll("-", "");
|
|
13
13
|
return {
|
|
14
14
|
timeUnixNano: `${String(Date.now())}000000`,
|
|
15
|
-
traceId:
|
|
16
|
-
spanId:
|
|
15
|
+
traceId: t,
|
|
16
|
+
spanId: t.slice(0, 16),
|
|
17
17
|
traceFlags: 1,
|
|
18
|
-
severityNumber:
|
|
18
|
+
severityNumber: e.INFO,
|
|
19
19
|
severityText: "INFO",
|
|
20
20
|
body: "uiobs doctor test record",
|
|
21
21
|
attributes: {},
|
|
@@ -101,14 +101,14 @@ function Y(e, t) {
|
|
|
101
101
|
return `${k} must include ${n.join(", ")}.${r}${i}`;
|
|
102
102
|
})];
|
|
103
103
|
}
|
|
104
|
-
function X({ url: e, origin: t, custom: n },
|
|
104
|
+
function X({ url: e, origin: t, custom: n }, r, a) {
|
|
105
105
|
return (o, s, c, l = {}) => L(e, {
|
|
106
106
|
method: "POST",
|
|
107
107
|
headers: {
|
|
108
108
|
...n,
|
|
109
109
|
Origin: t,
|
|
110
|
-
[d]:
|
|
111
|
-
[
|
|
110
|
+
[d]: r,
|
|
111
|
+
[i]: o,
|
|
112
112
|
[f]: String(s),
|
|
113
113
|
...l
|
|
114
114
|
},
|
|
@@ -117,16 +117,16 @@ function X({ url: e, origin: t, custom: n }, i, a) {
|
|
|
117
117
|
}
|
|
118
118
|
async function Z(e, t, n) {
|
|
119
119
|
let r = await m(n);
|
|
120
|
-
return r ? e(t, 0, r, { [
|
|
120
|
+
return r ? e(t, 0, r, { [a]: l }) : "This Node version has no CompressionStream.";
|
|
121
121
|
}
|
|
122
|
-
async function Q(
|
|
123
|
-
let o = H(
|
|
124
|
-
y.searchParams.set(
|
|
122
|
+
async function Q(e, n, i = {}, a = !1) {
|
|
123
|
+
let o = H(e, n, i, a), s = U(o), c = await J(o), { body: l, contentType: f } = h.serialize([se()]), p = X(o, f), m = crypto.randomUUID(), g = await p(m, 0, l), _ = await p(m, 1, l), v = await Z(p, crypto.randomUUID(), l), y = new URL(e);
|
|
124
|
+
y.searchParams.set(r, crypto.randomUUID()), y.searchParams.set(u, "pagehide");
|
|
125
125
|
let b = o.requestHeaders.length > N.length ? void 0 : await L(y.toString(), {
|
|
126
126
|
method: "POST",
|
|
127
127
|
headers: {
|
|
128
|
-
Origin:
|
|
129
|
-
[d]:
|
|
128
|
+
Origin: n,
|
|
129
|
+
[d]: t
|
|
130
130
|
},
|
|
131
131
|
body: l
|
|
132
132
|
}), x = typeof g == "string" ? [] : z(g, D, P, !o.credentials), S = x.length > 0 ? ` Optional headers stay hidden: ${x.join(", ")}.` : "", C = G(q(g, D, oe), o, M);
|
|
@@ -143,8 +143,8 @@ async function Q(t, r, i = {}, a = !1) {
|
|
|
143
143
|
} : V("beacon", b, "The server accepted a text/plain batch.", ce, B)
|
|
144
144
|
];
|
|
145
145
|
}
|
|
146
|
-
async function $(e, t,
|
|
147
|
-
let
|
|
146
|
+
async function $(e, t, r = {}, i = !1) {
|
|
147
|
+
let a = H(e, t, r, i), o = U(a), s = await J(a), c = crypto.randomUUID(), l = {
|
|
148
148
|
"replay.id": c,
|
|
149
149
|
"session.id": crypto.randomUUID(),
|
|
150
150
|
"tab.id": crypto.randomUUID(),
|
|
@@ -164,10 +164,10 @@ async function $(e, t, n = {}, r = !1) {
|
|
|
164
164
|
bytes: JSON.stringify(n).length,
|
|
165
165
|
events: n
|
|
166
166
|
});
|
|
167
|
-
}, d = (e) => `${c}-${String(e)}`, f = X(
|
|
167
|
+
}, d = (e) => `${c}-${String(e)}`, f = X(a, p), m = u(0, "uiobs doctor test event"), h = await f(d(0), 0, m), g = await f(d(0), 1, m), _ = await Z(f, d(1), u(1, "uiobs doctor gzip event")), v = await X(a, p, n)(d(2), 0, u(2, "x".repeat(T)));
|
|
168
168
|
return [
|
|
169
|
-
...Y(s,
|
|
170
|
-
V("test segment", h, `The server accepted a test segment.${G(W(h) === "*",
|
|
169
|
+
...Y(s, a),
|
|
170
|
+
V("test segment", h, `The server accepted a test segment.${G(W(h) === "*", a)}`, B, o),
|
|
171
171
|
V("gzip", _, "The server accepted a gzip segment.", B),
|
|
172
172
|
V("large segment", v, `The server accepted a segment of ${String(T)} bytes without gzip.`, (e) => e.ok ? void 0 : `The server returned ${String(e.status)} for a segment of ${String(T)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`),
|
|
173
173
|
V("deduplication", g, "The server accepted a repeated batch id. A client cannot see if it stored the segment again.", B)
|
package/dist/doctor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","CONTENT_TYPE_TEXT_PLAIN","SEVERITY_NUMBER","QUERY_PARAM_BATCH_ID","HEADER_BATCH_ID","HEADER_CONTENT_ENCODING","REQUEST_TIMEOUT_MS$1","HEADER_SAMPLING","HEADER_RETRY_AFTER","HEADER_DATE","ENCODING_GZIP","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtB3B;CACAP;CACAD;CACAS;AACF,CAAC,CAAC,KAAK,MAAS2B,EAAK,YAAY,CAAC,GAG5BC,KAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACnC,GAAiBE,CAAW,CAAC,CAAC,KAAK,MAAS+B,EAAK,YAAY,CAAC,GAGlFG,IAAsB,iBAGtBC,IAAmB,CAACpC,EAAmB,YAAY,CAAC,GAGpDqC,KAAiB,CAAC,GAAGD,GAAkB,GAAGF,CAAgB;AAmBhE,SAASI,KAAwB;CAC/B,IAAMC,IAAU,OAAO,WAAW,CAAC,CAAC,WAAW,KAAK,EAAE;CAEtD,OAAO;EACL,cAAc,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;EACpC;EACA,QAAQA,EAAQ,MAAM,GAAG,EAAE;EAC3B,YAAY;EACZ,gBAAgB7C,EAAgB;EAChC,cAAc;EACd,MAAM;EACN,YAAY,CAAC;EACb,UAAU,EAAE,gBAAgB0B,EAAY;CAC1C;AACF;AAGA,eAAeoB,EACb,GACA,GACA,IAAY/B,GACK;CACjB,IAAI;EAEF,OAAO,MAAM,MAAMgC,GAAK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ERY_PARAM_BATCH_ID","HEADER_BATCH_ID","HEADER_CONTENT_ENCODING","HEADER_SAMPLING","HEADER_RETRY_AFTER","HEADER_DATE","ENCODING_GZIP","QUERY_PARAM_EXIT_REASON","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","CONTENT_TYPE_JSON","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","CREDENTIALS_FLAG","CREDENTIALS_INCLUDE","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","ALLOW_ORIGIN","ALLOW_HEADERS","ALLOW_CREDENTIALS","STAR_REFUSED","STAR_PLAIN","STAR_AUTHORIZATION","STAR_HINT","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","NON_WILDCARD_HEADER","REQUIRED_EXPOSED","WANTED_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","valuesOf","response","value","absent","values","star","wildcard","wanted","statusProblem","mediaTypeProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","credentials","origin","allowsCredentials","allowedOrigin","starNote","earnedByStar","starWhy","coveredByStar","sendPreflight","requestHeaders","preflightResults","originNote","preflight","target","headersNote","missing","why","authorization","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","hiddenNote","exposedNote","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","parseOptions","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","options","print","results","headers","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server, or a replay endpoint, against its contract in docs/ingest-server.md.\n// The `uiobs doctor` command calls main(). Only web APIs are used here, and the browser build\n// replaces every \"node:\" import.\n\nimport {\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_TEXT_PLAIN,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n HEADER_DATE,\n HEADER_RETRY_AFTER,\n HEADER_SAMPLING,\n HTTP_UNSUPPORTED_MEDIA_TYPE,\n QUERY_PARAM_BATCH_ID,\n QUERY_PARAM_EXIT_REASON,\n REQUEST_TIMEOUT_MS as LIBRARY_TIMEOUT_MS,\n SEVERITY_NUMBER,\n} from \"./constants\";\nimport type { LogRecord } from \"./models/log-record\";\nimport { gzip } from \"./transport/compression\";\nimport { otlpSerializer } from \"./transport/serializers/otlp\";\n\n/** How long to wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when every rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code for a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Printed for a wrong command. */\nconst USAGE =\n 'Usage: uiobs doctor <url> --origin <origin> [--replay] [--credentials include] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint. With --credentials include, a * in a CORS header fails.';\n\n/** Adds a request header, e.g. an Authorization header. */\nconst HEADER_FLAG = \"--header\";\n\n/** Says that the URL is a replay endpoint, so the tool sends segments instead of batches. */\nconst REPLAY_FLAG = \"--replay\";\n\n/** Says that the app sets `credentials: \"include\"`, so a browser refuses a * in a CORS header. */\nconst CREDENTIALS_FLAG = \"--credentials\";\n\n/** The only value of CREDENTIALS_FLAG. */\nconst CREDENTIALS_INCLUDE = \"include\";\n\n/**\n * Size of the event in the large test segment, in characters. The first segment of a real\n * upload holds a full snapshot, and one of a page with 35,000 table cells measured 4.7 MB.\n */\nconst LARGE_EVENT_CHARS = 5_000_000;\n\n/** The recorder's custom event type. A player skips a custom event it doesn't know. */\nconst CUSTOM_EVENT = 5;\n\n/** Marks everything the tool stores, so an operator can find and delete it. */\nconst DOCTOR_NAME = \"uiobs-doctor\";\n\n/** A header name, a colon, then a value of printable ASCII. */\nconst HEADER_PATTERN = /^([\\w!#$%&'*+.^`|~-]+): *([\\x20-\\x7e]+)$/;\n\n/** Printed in place of any argument that might contain a secret. */\nconst HIDDEN = \"<hidden>\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Response header that names the origin that may read the answer. */\nconst ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n\n/** Response header of a preflight that lists the request headers the server accepts. */\nconst ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n\n/** Response header that lets a browser send and read an answer with credentials. */\nconst ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n\n/** Why a * in Access-Control-Allow-Origin fails with credentials. */\nconst STAR_REFUSED = 'A browser refuses * with credentials: \"include\".';\n\n/** Why a * in a list of header names fails with credentials. */\nconst STAR_PLAIN = 'A browser does not read * as a wildcard with credentials: \"include\".';\n\n/** Why a * in Access-Control-Allow-Headers fails for Authorization, with or without credentials. */\nconst STAR_AUTHORIZATION = \"A browser never lets * cover authorization.\";\n\n/** Ends the note of a PASS line that only a * earned, so the run without credentials says so. */\nconst STAR_HINT = \"Add --credentials include to check that case.\";\n\n/** The library's request headers. The server must allow every one of them. */\nconst REQUEST_HEADERS = [\n HEADER_CONTENT_TYPE,\n HEADER_CONTENT_ENCODING,\n HEADER_BATCH_ID,\n HEADER_ATTEMPT,\n].map((name) => name.toLowerCase());\n\n/** Headers the tool sets itself. A custom header can't reuse one of these names. */\nconst RESERVED_HEADERS = [...REQUEST_HEADERS, \"origin\"];\n\n/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** The one request header that a * in Access-Control-Allow-Headers never covers. */\nconst NON_WILDCARD_HEADER = \"authorization\";\n\n/** The response header that the library can't work without when it is hidden. */\nconst REQUIRED_EXPOSED = [HEADER_RETRY_AFTER.toLowerCase()];\n\n/** Every response header that the library reads. */\nconst WANTED_EXPOSED = [...REQUIRED_EXPOSED, ...OPTIONAL_EXPOSED];\n\n/** The result of one ingest contract rule. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Why the rule passed or failed. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Returns a description of the problem, or undefined when the answer passes the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it like any other record. */\nfunction testRecord(): LogRecord {\n const traceId = crypto.randomUUID().replaceAll(\"-\", \"\");\n\n return {\n timeUnixNano: `${String(Date.now())}000000`,\n traceId,\n spanId: traceId.slice(0, 16),\n traceFlags: 1,\n severityNumber: SEVERITY_NUMBER.INFO,\n severityText: \"INFO\",\n body: \"uiobs doctor test record\",\n attributes: {},\n resource: { \"service.name\": DOCTOR_NAME },\n };\n}\n\n/** Sends one request. A failure shows up in the result line, as the tool has no diagnostics. */\nasync function request(\n url: string,\n init: RequestInit,\n timeoutMs = REQUEST_TIMEOUT_MS,\n): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects, and a redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n // Node only says \"fetch failed\". The cause holds the real reason, for example ECONNREFUSED.\n const reason: unknown =\n error instanceof Error ? ((error as Error & { cause?: unknown }).cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the lowercase values of a comma-separated response header. */\nfunction valuesOf(response: Response, name: string): string[] {\n return (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n}\n\n/**\n * Returns the wanted values a comma-separated header leaves out. With wildcard, a * covers them\n * all but Authorization, which the Fetch standard never lets a * cover. A run with credentials\n * passes false, because a browser reads * as a plain name then.\n */\nfunction absent(\n response: Response,\n name: string,\n wanted: readonly string[],\n wildcard: boolean,\n): string[] {\n const values = valuesOf(response, name);\n const star = wildcard && values.includes(\"*\");\n\n return wanted.filter(\n (value) => !values.includes(value) && !(star && value !== NON_WILDCARD_HEADER),\n );\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/**\n * Names the collector case for a 415 answer to the beacon batch, because the bare status doesn't\n * say that only the exit batches are lost or how to fix it.\n */\nconst mediaTypeProblem: AnswerTest = (response) =>\n response.status === HTTP_UNSUPPORTED_MEDIA_TYPE\n ? `The server returned ${String(response.status)} to a text/plain batch, as a stock OpenTelemetry Collector does. The library loses the exit batches of a page on another origin. Set headers in the app, or put a same-origin proxy in front of the server.`\n : undefined;\n\n/** Builds the result for one rule. The first problem found becomes the detail. */\nfunction judge(rule: string, answer: Answer, passed: string, ...tests: AnswerTest[]): DoctorResult {\n const problem =\n typeof answer === \"string\"\n ? answer\n : tests.map((test) => test(answer)).find((found) => found !== undefined);\n\n return { rule, pass: problem === undefined, detail: problem ?? passed };\n}\n\n/** One endpoint under test: where it is, who calls it and with which headers. */\ninterface Target {\n /** Endpoint URL. */\n url: string;\n /** The app's origin. */\n origin: string;\n /** The app's headers for each POST, e.g. an Authorization header. */\n custom: Readonly<Record<string, string>>;\n /** Lowercase names of every header a POST carries. The preflight asks for them. */\n requestHeaders: string[];\n /** True with `--credentials include`. A browser then refuses a * in a CORS header. */\n credentials: boolean;\n}\n\n/** Sends one POST the way the library does. Extra headers go on top. */\ntype Post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra?: Record<string, string>,\n) => Promise<Answer>;\n\n/** Builds the target for one run. */\nfunction targetOf(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>>,\n credentials: boolean,\n): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return {\n url,\n origin,\n custom,\n requestHeaders: [...REQUEST_HEADERS, ...customNames],\n credentials,\n };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest({ origin, credentials }: Target): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(ALLOW_ORIGIN);\n\n if (allowed === \"*\" && credentials) {\n return `${ALLOW_ORIGIN} is *. ${STAR_REFUSED} It must be ${origin}.`;\n }\n\n if (allowed !== origin && allowed !== \"*\") {\n return `${ALLOW_ORIGIN} is ${String(allowed)}. It must allow ${origin}.`;\n }\n\n // A browser rejects a credentialed answer without this header. The library then sees a\n // network error and sends the batch again.\n return credentials ? allowsCredentials(response) : undefined;\n };\n}\n\n/** Checks that an answer lets the browser send and read credentials. */\nconst allowsCredentials: AnswerTest = (response) => {\n const allowed = response.headers.get(ALLOW_CREDENTIALS);\n\n return allowed === \"true\"\n ? undefined\n : `${ALLOW_CREDENTIALS} is ${String(allowed)}. It must be true with credentials: \"include\".`;\n};\n\n/** Returns the origin an answer allows, or null for a failed request or a missing header. */\nfunction allowedOrigin(answer: Answer): string | null {\n return typeof answer === \"string\" ? null : answer.headers.get(ALLOW_ORIGIN);\n}\n\n/**\n * Returns the note for a PASS that only a * earned. With credentials the rule fails on that *,\n * so the note is for the run without them.\n */\nfunction starNote(earnedByStar: boolean, { credentials }: Target, reason = STAR_REFUSED): string {\n return earnedByStar && !credentials ? ` ${reason} ${STAR_HINT}` : \"\";\n}\n\n/** Returns the reason that a * doesn't help a list of header names with credentials, or \"\". */\nfunction starWhy(response: Response, name: string, { credentials }: Target): string {\n return credentials && valuesOf(response, name).includes(\"*\") ? ` ${STAR_PLAIN}` : \"\";\n}\n\n/** True when a list of header names passes only because of its *: it has one and misses a name. */\nfunction coveredByStar(answer: Answer, name: string, wanted: readonly string[]): boolean {\n return (\n typeof answer !== \"string\" &&\n valuesOf(answer, name).includes(\"*\") &&\n absent(answer, name, wanted, false).length > 0\n );\n}\n\n/** Sends the preflight a browser sends before the library's POST. */\nfunction sendPreflight({ url, origin, requestHeaders }: Target): Promise<Answer> {\n return request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": requestHeaders.join(\", \"),\n },\n });\n}\n\n/** Builds the two results every preflight gives. */\nfunction preflightResults(preflight: Answer, target: Target): DoctorResult[] {\n const originNote = starNote(allowedOrigin(preflight) === \"*\", target);\n const headersByStar = coveredByStar(preflight, ALLOW_HEADERS, target.requestHeaders);\n const headersNote = starNote(headersByStar, target, STAR_PLAIN);\n\n return [\n judge(\n \"preflight\",\n preflight,\n `The server permits POST from this origin.${originNote}`,\n statusProblem,\n originTest(target),\n ),\n judge(\n \"allowed headers\",\n preflight,\n `The server allows each request header of the library.${headersNote}`,\n (response) => {\n const missing = absent(response, ALLOW_HEADERS, target.requestHeaders, !target.credentials);\n if (missing.length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, ALLOW_HEADERS, target);\n const authorization =\n missing.includes(NON_WILDCARD_HEADER) && valuesOf(response, ALLOW_HEADERS).includes(\"*\")\n ? ` ${STAR_AUTHORIZATION}`\n : \"\";\n\n return `${ALLOW_HEADERS} must include ${missing.join(\", \")}.${why}${authorization}`;\n },\n ),\n ];\n}\n\n/** Builds the POST function for one target and content type. */\nfunction poster({ url, origin, custom }: Target, contentType: string, timeoutMs?: number): Post {\n return (id, attempt, payload, extra = {}) =>\n request(\n url,\n {\n method: \"POST\",\n headers: {\n ...custom,\n Origin: origin,\n [HEADER_CONTENT_TYPE]: contentType,\n [HEADER_BATCH_ID]: id,\n [HEADER_ATTEMPT]: String(attempt),\n ...extra,\n },\n body: payload,\n },\n timeoutMs,\n );\n}\n\n/** Sends a body with gzip. Gives the text of the problem if this Node can't compress. */\nasync function postZipped(post: Post, id: string, body: string): Promise<Answer> {\n const compressed = await gzip(body);\n\n return compressed\n ? post(id, 0, compressed, { [HEADER_CONTENT_ENCODING]: ENCODING_GZIP })\n : \"This Node version has no CompressionStream.\";\n}\n\n/**\n * Runs each rule's requests one at a time. Two requests with the same batch id must not overlap.\n * @param url Ingest URL.\n * @param origin The app's origin.\n * @param custom The app's headers for each batch, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. A * in a CORS header then\n * fails, and the preflight must allow credentials.\n * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = poster(target, contentType);\n\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const zipped = await postZipped(post, crypto.randomUUID(), body);\n\n // sendBeacon can't set headers, so the id and the reason go in the query, like the exit flush.\n const beaconUrl = new URL(url);\n beaconUrl.searchParams.set(QUERY_PARAM_BATCH_ID, crypto.randomUUID());\n beaconUrl.searchParams.set(QUERY_PARAM_EXIT_REASON, \"pagehide\");\n\n // With custom headers the library's exit flush uses a keepalive fetch instead of a beacon.\n const beacon =\n target.requestHeaders.length > REQUEST_HEADERS.length\n ? undefined\n : await request(beaconUrl.toString(), {\n method: \"POST\",\n headers: { Origin: origin, [HEADER_CONTENT_TYPE]: CONTENT_TYPE_TEXT_PLAIN },\n body,\n });\n\n const hidden =\n typeof first === \"string\"\n ? []\n : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED, !target.credentials);\n const hiddenNote =\n hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n const exposedNote = starNote(\n coveredByStar(first, EXPOSE_HEADERS, WANTED_EXPOSED),\n target,\n STAR_PLAIN,\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test batch\",\n first,\n `The server accepted a test batch.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\n \"exposed headers\",\n first,\n `The server exposes Retry-After.${hiddenNote}${exposedNote}`,\n (response) => {\n if (absent(response, EXPOSE_HEADERS, REQUIRED_EXPOSED, !target.credentials).length === 0) {\n return undefined;\n }\n\n const why = starWhy(response, EXPOSE_HEADERS, target);\n\n return `${EXPOSE_HEADERS} must include retry-after.${why}`;\n },\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip batch.\", statusProblem),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the batch again.\",\n statusProblem,\n ),\n beacon === undefined\n ? {\n rule: \"beacon\",\n pass: true,\n detail: \"The library sends no beacon with custom headers. The tool sent no beacon.\",\n }\n : judge(\n \"beacon\",\n beacon,\n \"The server accepted a text/plain batch.\",\n mediaTypeProblem,\n statusProblem,\n ),\n ];\n}\n\n/**\n * Checks a replay endpoint the way runDoctor() checks an ingest server. A segment has its own\n * body and its own batch id form, and its first one can be several megabytes.\n * @param url Replay endpoint URL, the value of replay.endpoint.\n * @param origin The app's origin.\n * @param custom The app's replay.headers, e.g. an Authorization header.\n * @param credentials True when the app sets `credentials: \"include\"`. See runDoctor().\n * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n credentials = false,\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom, credentials);\n const originProblem = originTest(target);\n const preflight = await sendPreflight(target);\n\n const replayId = crypto.randomUUID();\n const head = {\n \"replay.id\": replayId,\n \"session.id\": crypto.randomUUID(),\n \"tab.id\": crypto.randomUUID(),\n \"service.name\": DOCTOR_NAME,\n };\n // The body the uploader sends: the ids, the sequence, the JSON length of the events, and the\n // events themselves.\n const segment = (sequence: number, text: string): string => {\n const events = [\n { type: CUSTOM_EVENT, timestamp: Date.now(), data: { tag: DOCTOR_NAME, payload: text } },\n ];\n\n return JSON.stringify({ ...head, sequence, bytes: JSON.stringify(events).length, events });\n };\n // The uploader's batch id is the replay id plus the sequence.\n const idOf = (sequence: number): string => `${replayId}-${String(sequence)}`;\n const post = poster(target, CONTENT_TYPE_JSON);\n const small = segment(0, \"uiobs doctor test event\");\n\n const first = await post(idOf(0), 0, small);\n const repeated = await post(idOf(0), 1, small);\n const zipped = await postZipped(post, idOf(1), segment(1, \"uiobs doctor gzip event\"));\n // No gzip here. That is the worst case: compression off, or a browser without\n // CompressionStream. The library gives a segment delivery.requestTimeoutMs, so the tool\n // waits for the default of that. A shorter wait would fail a slow link the library can use.\n const large = await poster(target, CONTENT_TYPE_JSON, LIBRARY_TIMEOUT_MS)(\n idOf(2),\n 0,\n segment(2, \"x\".repeat(LARGE_EVENT_CHARS)),\n );\n\n return [\n ...preflightResults(preflight, target),\n judge(\n \"test segment\",\n first,\n `The server accepted a test segment.${starNote(allowedOrigin(first) === \"*\", target)}`,\n statusProblem,\n originProblem,\n ),\n judge(\"gzip\", zipped, \"The server accepted a gzip segment.\", statusProblem),\n judge(\n \"large segment\",\n large,\n `The server accepted a segment of ${String(LARGE_EVENT_CHARS)} bytes without gzip.`,\n // The library drops a segment after a 413, so a low body limit loses every replay.\n (response) =>\n response.ok\n ? undefined\n : `The server returned ${String(response.status)} for a segment of ${String(LARGE_EVENT_CHARS)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`,\n ),\n judge(\n \"deduplication\",\n repeated,\n \"The server accepted a repeated batch id. A client cannot see if it stored the segment again.\",\n statusProblem,\n ),\n ];\n}\n\n/** The options after the origin and the replay flag. */\ninterface Options {\n /** The headers of the --header options. */\n headers: Record<string, string>;\n /** True with `--credentials include`. */\n credentials: boolean;\n}\n\n/**\n * Parses the options. Each one is a flag and its value: a \"Name: value\" argument for a header,\n * or `include` for the credentials.\n * @param args The arguments after the origin.\n * @returns The options, or undefined if an option is malformed.\n */\nfunction parseOptions(args: readonly string[]): Options | undefined {\n const pairs: [string, string][] = [];\n let credentials = false;\n\n for (let index = 0; index < args.length; index += 2) {\n if (args[index] === CREDENTIALS_FLAG && args[index + 1] === CREDENTIALS_INCLUDE) {\n credentials = true;\n continue;\n }\n\n // A flag without a value leaves undefined here, which exec() treats as text with no colon.\n const match = args[index] === HEADER_FLAG ? HEADER_PATTERN.exec(args[index + 1]) : null;\n\n if (!match || RESERVED_HEADERS.includes(match[1].toLowerCase())) {\n return undefined;\n }\n\n pairs.push([match[1], match[2]]);\n }\n\n return { headers: Object.fromEntries(pairs), credentials };\n}\n\n/** True for an HTTP URL without a user name or password. Result lines print the URL. */\nfunction isHttpUrl(value: string): boolean {\n if (!/^https?:\\/\\//i.test(value) || !URL.canParse(value)) {\n return false;\n }\n\n const { username, password } = new URL(value);\n return username === \"\" && password === \"\";\n}\n\n/** Command line words that are safe to print. */\nconst SHOWN_WORDS = [\n \"doctor\",\n \"--origin\",\n REPLAY_FLAG,\n HEADER_FLAG,\n CREDENTIALS_FLAG,\n CREDENTIALS_INCLUDE,\n];\n\n/**\n * Turns an argument into something safe to print in the usage message. An argument can be a\n * token, a URL can carry one in its query or user info, and the output may land in a shared log.\n * @param arg Command line argument.\n * @returns The word itself, a URL without query or user info, or a placeholder.\n */\nfunction shownArgument(arg: string): string {\n if (SHOWN_WORDS.includes(arg)) {\n return arg;\n }\n\n if (/^https?:\\/\\//i.test(arg) && URL.canParse(arg)) {\n const { origin, pathname } = new URL(arg);\n return `${origin}${pathname === \"/\" && !arg.endsWith(\"/\") ? \"\" : pathname}`;\n }\n\n return HIDDEN;\n}\n\n/** Checks for an exact browser origin. A path or a trailing slash doesn't match. */\nfunction isOrigin(value: string): boolean {\n return URL.canParse(value) && new URL(value).origin === value;\n}\n\n/**\n * Runs the command line tool.\n * @param args Arguments after the program name.\n * @param print Writes one line of output.\n * @returns The exit code.\n */\nexport async function main(\n args: readonly string[],\n print: (line: string) => void,\n): Promise<number> {\n const [command, url, flag, origin, ...rest] = args;\n // The replay flag comes right after the origin, before any other option.\n const replay = rest[0] === REPLAY_FLAG;\n const options = parseOptions(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !options\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const { headers, credentials } = options;\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers, credentials);\n\n for (const { rule, pass, detail } of results) {\n print(`${pass ? \"PASS\" : \"FAIL\"} ${rule}: ${detail}`);\n }\n\n return results.every(({ pass }) => pass) ? EXIT_PASS : EXIT_FAIL;\n}\n"],"mappings":";;;;AA4BA,IAAMiB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gQAGIC,IAAc,YAGdC,IAAc,YAGdC,IAAmB,iBAGnBC,IAAsB,WAMtBC,IAAoB,KAGpBC,KAAe,GAGfC,IAAc,gBAGdC,KAAiB,4CAGjBC,KAAS,YAGTC,IAAiB,iCAGjBC,IAAe,+BAGfC,IAAgB,gCAGhBC,IAAoB,oCAGpBC,IAAe,sDAGfC,IAAa,0EAGbC,KAAqB,+CAGrBC,KAAY,iDAGZC,IAAkB;CACtB3B;CACAN;CACAD;CACAQ;AACF,CAAC,CAAC,KAAK,MAAS2B,EAAK,YAAY,CAAC,GAG5BC,KAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACnC,GAAiBE,CAAW,CAAC,CAAC,KAAK,MAAS+B,EAAK,YAAY,CAAC,GAGlFG,IAAsB,iBAGtBC,IAAmB,CAACpC,EAAmB,YAAY,CAAC,GAGpDqC,KAAiB,CAAC,GAAGD,GAAkB,GAAGF,CAAgB;AAmBhE,SAASI,KAAwB;CAC/B,IAAMC,IAAU,OAAO,WAAW,CAAC,CAAC,WAAW,KAAK,EAAE;CAEtD,OAAO;EACL,cAAc,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;EACpC;EACA,QAAQA,EAAQ,MAAM,GAAG,EAAE;EAC3B,YAAY;EACZ,gBAAgB9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EAAQ,OAAO,EAAE,cAAWE,CAAI,IAAIjI,IAAYC;AACzD"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-BZjp9wp1.cjs"),n=require("./storm-qiE_AMC7.cjs"),r=require("./defineProperty-X1c4tIPD.cjs");function i(t){if(e.r(t)){let e=(t.stack??``).split(`
|
|
2
|
+
`)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var a=class{constructor(e){r.t(this,`ctx`,void 0),r.t(this,`name`,`errors`),r.t(this,`installed`,!1),r.t(this,`seen`,new Map),r.t(this,`window`,{start:0,count:0}),r.t(this,`onError`,e=>{this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record an error event.`,()=>{`message`in e?this.scriptError(e):this.failedResource(e.target)})}),r.t(this,`onRejection`,e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})}),this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}failedResource(e){let n=e;if(typeof n?.tagName!=`string`||!this.ctx.config.capture.resourceErrors)return;let r=n.tagName.toLowerCase(),i={"error.type":`resource`,"resource.tag":r},a=r,o=n.src??n.href;typeof o==`string`&&o!==``&&(a=t.a(o,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),i[`resource.url`]=a),this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${a}`}),this.ctx.logger.warn(`resource failed to load`,i)}scriptError(e){if(!this.ctx.config.capture.errors)return;let n=e.message===``?`unknown error`:e.message,r=e.error??Error(n);this.report(`window.onerror`,r,{"error.source":t.a(e.filename,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),"error.line":e.lineno,"error.column":e.colno})}report(e,t,r){if(!n.t(this.window,this.ctx.config.captureLimits.errorsPerWindow,this.ctx.diagnostics,`errors`,this.ctx.config.captureLimits.windowMs))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>i(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<this.ctx.config.captureLimits.errorDedupeMs){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...r,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=a;
|
|
3
|
+
//# sourceMappingURL=errors-07pmZ7VY.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-07pmZ7VY.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","require_defineProperty","signatureOf","value","frame","message","ErrorCapture","event","ctx","element","target","tag","attributes","label","source","fallback","errorEvent","error","now","previous","key","suppressed","oldest","reason","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n // The browser calls this listener, so a throw here would be a new uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record an error event.\",\n () => {\n // A failed load fires a plain Event at its element. Only a script error carries the\n // ErrorEvent fields, so a plain Event at the window is neither.\n if (\"message\" in event) {\n this.scriptError(event);\n } else {\n this.failedResource(event.target);\n }\n },\n );\n };\n\n /**\n * Records a failed resource load.\n * @param target The event's target. The window and the document aren't resources.\n */\n private failedResource(target: EventTarget | null): void {\n const element = target as (Element & { src?: unknown; href?: unknown }) | null;\n if (typeof element?.tagName !== \"string\" || !this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n const tag = element.tagName.toLowerCase();\n const attributes: Record<string, unknown> = { \"error.type\": \"resource\", \"resource.tag\": tag };\n // Without a URL, the breadcrumb names the tag.\n let label = tag;\n // An SVG href is an object and an object element has no src, so only a string URL goes in.\n // A cache buster is noise and a signed URL is a credential, so fullUrls decides on both.\n const source = element.src ?? element.href;\n if (typeof source === \"string\" && source !== \"\") {\n label = recordedUrl(\n source,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n attributes[\"resource.url\"] = label;\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${label}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", attributes);\n }\n\n /**\n * Records an uncaught script error.\n * @param errorEvent The window's error event.\n */\n private scriptError(errorEvent: ErrorEvent): void {\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n }\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"A,+JAiCA,SAASO,EAAY,EAA2B,CAC9C,GAAIP,EAAAA,EAAYQ,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,G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IAAI,OAAO,cAAc,cAAe,CAC/E,EAAS,QACT,EAAS,GAAKD,EACd,MACF,CAIA,IAAMG,EAAaF,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOC,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIF,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACI,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMZ,CAAO,EAAIY,EAC1D,KAAK,IAAI,OAAO,MAAMZ,IAAY,GAAKS,EAAST,EAASkB,EAAQ,CAC/D,GAAGC,EACH,oBAAqBV,EACrB,yBAA0BO,CAC5B,CAAC,CACH,CACF,E"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as e } from "./error-like-B11pB4aL.js";
|
|
2
|
-
import {
|
|
3
|
-
import { t as n } from "./storm-
|
|
2
|
+
import { a as t } from "./platform-Dba6R3Hp.js";
|
|
3
|
+
import { t as n } from "./storm-U3_ek1nA.js";
|
|
4
4
|
import { t as r } from "./defineProperty-s2S8BXUc.js";
|
|
5
5
|
// src/capture/errors.ts
|
|
6
6
|
function i(t) {
|
|
@@ -23,27 +23,8 @@ var a = class {
|
|
|
23
23
|
start: 0,
|
|
24
24
|
count: 0
|
|
25
25
|
}), r(this, "onError", (e) => {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if (!this.ctx.config.capture.resourceErrors) return;
|
|
29
|
-
let e = t(r, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics);
|
|
30
|
-
this.ctx.breadcrumbs.push({
|
|
31
|
-
t: Date.now(),
|
|
32
|
-
category: "http",
|
|
33
|
-
message: `resource failed: ${e}`
|
|
34
|
-
}), this.ctx.logger.warn("resource failed to load", {
|
|
35
|
-
"error.type": "resource",
|
|
36
|
-
"resource.url": e,
|
|
37
|
-
"resource.tag": n.tagName.toLowerCase()
|
|
38
|
-
});
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
if (!this.ctx.config.capture.errors) return;
|
|
42
|
-
let i = e, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
|
|
43
|
-
this.report("window.onerror", o, {
|
|
44
|
-
"error.source": t(i.filename, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics),
|
|
45
|
-
"error.line": i.lineno,
|
|
46
|
-
"error.column": i.colno
|
|
26
|
+
this.ctx.diagnostics.guard("capture.record_failed", "The library could not record an error event.", () => {
|
|
27
|
+
"message" in e ? this.scriptError(e) : this.failedResource(e.target);
|
|
47
28
|
});
|
|
48
29
|
}), r(this, "onRejection", (e) => {
|
|
49
30
|
this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
|
|
@@ -55,6 +36,28 @@ var a = class {
|
|
|
55
36
|
uninstall() {
|
|
56
37
|
this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
|
|
57
38
|
}
|
|
39
|
+
failedResource(e) {
|
|
40
|
+
let n = e;
|
|
41
|
+
if (typeof n?.tagName != "string" || !this.ctx.config.capture.resourceErrors) return;
|
|
42
|
+
let r = n.tagName.toLowerCase(), i = {
|
|
43
|
+
"error.type": "resource",
|
|
44
|
+
"resource.tag": r
|
|
45
|
+
}, a = r, o = n.src ?? n.href;
|
|
46
|
+
typeof o == "string" && o !== "" && (a = t(o, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics), i["resource.url"] = a), this.ctx.breadcrumbs.push({
|
|
47
|
+
t: Date.now(),
|
|
48
|
+
category: "http",
|
|
49
|
+
message: `resource failed: ${a}`
|
|
50
|
+
}), this.ctx.logger.warn("resource failed to load", i);
|
|
51
|
+
}
|
|
52
|
+
scriptError(e) {
|
|
53
|
+
if (!this.ctx.config.capture.errors) return;
|
|
54
|
+
let n = e.message === "" ? "unknown error" : e.message, r = e.error ?? Error(n);
|
|
55
|
+
this.report("window.onerror", r, {
|
|
56
|
+
"error.source": t(e.filename, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics),
|
|
57
|
+
"error.line": e.lineno,
|
|
58
|
+
"error.column": e.colno
|
|
59
|
+
});
|
|
60
|
+
}
|
|
58
61
|
report(e, t, r) {
|
|
59
62
|
if (!n(this.window, this.ctx.config.captureLimits.errorsPerWindow, this.ctx.diagnostics, "errors", this.ctx.config.captureLimits.windowMs)) return;
|
|
60
63
|
let a = Date.now(), { message: o, key: s } = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read the error reason. It records the error without its message.", () => i(t)) ?? {
|
|
@@ -83,4 +86,4 @@ var a = class {
|
|
|
83
86
|
};
|
|
84
87
|
export { a as ErrorCapture };
|
|
85
88
|
|
|
86
|
-
//# sourceMappingURL=errors-
|
|
89
|
+
//# sourceMappingURL=errors-C-LYbqyB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-C-LYbqyB.js","names":["isErrorLike","recordedUrl","allowInWindow","_defineProperty","signatureOf","value","frame","message","ErrorCapture","event","ctx","element","target","tag","attributes","label","source","fallback","errorEvent","error","now","previous","key","suppressed","oldest","reason","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { MAX_TRACKED_ERROR_SIGNATURES } from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** When the signature was last reported, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** A thrown value's message and deduplication key. */\ninterface Signature {\n /** The record's message. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads a thrown value's message and deduplication key.\n * Duck typing lets it read an error from another realm, which fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the value's text form throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** This capture's own rate limit. Console noise has a separate window and can't use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context: configuration, diagnostics, logger and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Resource load errors don't bubble, so listen in the capture phase.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n // The browser calls this listener, so a throw here would be a new uncaught error on the page.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not record an error event.\",\n () => {\n // A failed load fires a plain Event at its element. Only a script error carries the\n // ErrorEvent fields, so a plain Event at the window is neither.\n if (\"message\" in event) {\n this.scriptError(event);\n } else {\n this.failedResource(event.target);\n }\n },\n );\n };\n\n /**\n * Records a failed resource load.\n * @param target The event's target. The window and the document aren't resources.\n */\n private failedResource(target: EventTarget | null): void {\n const element = target as (Element & { src?: unknown; href?: unknown }) | null;\n if (typeof element?.tagName !== \"string\" || !this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n const tag = element.tagName.toLowerCase();\n const attributes: Record<string, unknown> = { \"error.type\": \"resource\", \"resource.tag\": tag };\n // Without a URL, the breadcrumb names the tag.\n let label = tag;\n // An SVG href is an object and an object element has no src, so only a string URL goes in.\n // A cache buster is noise and a signed URL is a credential, so fullUrls decides on both.\n const source = element.src ?? element.href;\n if (typeof source === \"string\" && source !== \"\") {\n label = recordedUrl(\n source,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n attributes[\"resource.url\"] = label;\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${label}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", attributes);\n }\n\n /**\n * Records an uncaught script error.\n * @param errorEvent The window's error event.\n */\n private scriptError(errorEvent: ErrorEvent): void {\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n }\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates and logs a captured error.\n * @param source Name of the capture event it came from.\n * @param error The caught error or thrown value.\n * @param extra Extra error attributes for the record.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (\n !allowInWindow(\n this.window,\n this.ctx.config.captureLimits.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.captureLimits.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message,\n // and the record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.captureLimits.errorDedupeMs) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // How many occurrences deduplication dropped since the last report. Without this count,\n // many errors look like a few.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. That keeps the map in\n // least-recently-reported order, which the eviction below relies on.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message on every render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Hand the logger the original value, so it converts the reason and keeps its data.\n // With no reason at all, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;;AAiCA,SAASI,EAAY,GAA2B;CAC9C,IAAIJ,EAAYK,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD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