@utk09/ui-observability 0.11.0 → 0.12.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 +61 -0
- package/README.md +273 -102
- package/bin/uiobs.mjs +1 -1
- package/dist/{batch-CL9uWYY3.js → batch-BjQUwjA6.js} +4 -4
- package/dist/batch-BjQUwjA6.js.map +1 -0
- package/dist/{batch-C8OcWR2L.cjs → batch-D5LlU4Q9.cjs} +2 -2
- package/dist/batch-D5LlU4Q9.cjs.map +1 -0
- package/dist/bus/bus.d.ts +48 -47
- package/dist/bus/links.d.ts +4 -4
- package/dist/bus/validation.d.ts +1 -1
- package/dist/bus-D_7pd7RN.cjs +2 -0
- package/dist/bus-D_7pd7RN.cjs.map +1 -0
- package/dist/{bus-BZ0GldpT.js → bus-ecxUNTja.js} +91 -91
- package/dist/bus-ecxUNTja.js.map +1 -0
- package/dist/capture/console.d.ts +10 -10
- package/dist/capture/errors.d.ts +6 -6
- package/dist/capture/interactions.d.ts +14 -14
- package/dist/capture/lifecycle.d.ts +3 -3
- package/dist/capture/long-frames.d.ts +6 -6
- package/dist/capture/network.d.ts +17 -17
- package/dist/capture/profiler-frames.d.ts +44 -0
- package/dist/capture/replay-buffer.d.ts +46 -0
- package/dist/capture/replay-upload.d.ts +74 -0
- package/dist/capture/replay.d.ts +114 -0
- package/dist/capture/reports.d.ts +2 -2
- package/dist/capture/resource-timing.d.ts +1 -1
- package/dist/capture/server-timing.d.ts +3 -3
- package/dist/capture/storm.d.ts +3 -3
- package/dist/capture/types.d.ts +45 -33
- package/dist/capture/unclean-exit.d.ts +8 -8
- package/dist/capture/user-timing.d.ts +3 -3
- package/dist/capture/web-socket.d.ts +11 -11
- package/dist/capture/web-vitals.d.ts +20 -7
- package/dist/compression-AJJCMBOa.js +11 -0
- package/dist/compression-AJJCMBOa.js.map +1 -0
- package/dist/compression-lD9abCcO.cjs +2 -0
- package/dist/compression-lD9abCcO.cjs.map +1 -0
- package/dist/{console-BPZCuSLc.cjs → console-CLz_PvFn.cjs} +2 -2
- package/dist/console-CLz_PvFn.cjs.map +1 -0
- package/dist/{console-BeCF7n59.js → console-cwgHKXvM.js} +4 -4
- package/dist/console-cwgHKXvM.js.map +1 -0
- package/dist/constants-Bwl_YtQi.js +349 -0
- package/dist/constants-Bwl_YtQi.js.map +1 -0
- package/dist/constants-DakMxVB2.cjs +2 -0
- package/dist/constants-DakMxVB2.cjs.map +1 -0
- package/dist/constants.d.ts +150 -103
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
- package/dist/context-storage-BzkoHzkQ.js.map +1 -1
- package/dist/core/breadcrumbs.d.ts +16 -15
- package/dist/core/config.d.ts +3 -3
- package/dist/core/context.d.ts +7 -7
- package/dist/core/debug-buffer.d.ts +10 -10
- package/dist/core/debug-bundle.d.ts +3 -3
- package/dist/core/deferred.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +24 -21
- package/dist/core/drops.d.ts +7 -7
- package/dist/core/hold-buffer.d.ts +1 -1
- package/dist/core/journey.d.ts +22 -23
- package/dist/core/logger.d.ts +22 -21
- package/dist/core/measure.d.ts +7 -7
- package/dist/core/meter.d.ts +25 -21
- package/dist/core/pipeline.d.ts +42 -41
- package/dist/core/profile-buckets.d.ts +31 -0
- package/dist/core/profiler.d.ts +218 -0
- package/dist/core/record.d.ts +23 -23
- package/dist/core/remote-rules.d.ts +4 -4
- package/dist/core/remote-sampling.d.ts +21 -20
- package/dist/core/runtime.d.ts +206 -137
- package/dist/core/sampling.d.ts +18 -18
- package/dist/core/sender.d.ts +22 -20
- package/dist/core/spans.d.ts +5 -5
- package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
- package/dist/deadline-C4ccAuk5.js.map +1 -0
- package/dist/deadline-CUGbto-y.cjs +2 -0
- package/dist/deadline-CUGbto-y.cjs.map +1 -0
- package/dist/{debug-bundle-C7UkHZ-q.js → debug-bundle-BOdYmCeV.js} +10 -3
- package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
- package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
- package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.cjs.map +1 -1
- package/dist/doctor.d.ts +16 -6
- package/dist/doctor.js +147 -52
- package/dist/doctor.js.map +1 -1
- package/dist/{emergency-queue-Zy6lNafo.js → emergency-queue-B9WZxanZ.js} +4 -4
- package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
- package/dist/{emergency-queue-CNTRui5t.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
- package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
- package/dist/error-like-B11pB4aL.js.map +1 -1
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-Dh7kef0i.js → errors-D6bwgJtO.js} +3 -3
- package/dist/errors-D6bwgJtO.js.map +1 -0
- package/dist/{errors-tfEr48bS.cjs → errors-DCOCRdSi.cjs} +2 -2
- package/dist/errors-DCOCRdSi.cjs.map +1 -0
- package/dist/{factory-CJXVYp0R.cjs → factory-DLFDjdLv.cjs} +2 -2
- package/dist/factory-DLFDjdLv.cjs.map +1 -0
- package/dist/{factory-BonqI3NL.js → factory-e9Qo3K0z.js} +13 -13
- package/dist/factory-e9Qo3K0z.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
- package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/global-scope-D9I8s-oN.js.map +1 -1
- package/dist/guards-Cidk71ME.js.map +1 -1
- package/dist/guards-nJ70syPt.cjs.map +1 -1
- package/dist/{identity-Cxgj6pZX.cjs → identity-BlvlgjrU.cjs} +2 -2
- package/dist/identity-BlvlgjrU.cjs.map +1 -0
- package/dist/{identity-DT5VmvXy.js → identity-BrQp_5J5.js} +19 -19
- package/dist/identity-BrQp_5J5.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +112 -79
- package/dist/index.js +783 -635
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CIoW21Xd.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
- package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
- package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-DLXQzAGh.js} +4 -4
- package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
- package/dist/{interactions-DTgKy_6K.js → interactions-B6z2I4tU.js} +3 -3
- package/dist/interactions-B6z2I4tU.js.map +1 -0
- package/dist/{interactions-fEN6FbVo.cjs → interactions-P6pz08Jn.cjs} +2 -2
- package/dist/interactions-P6pz08Jn.cjs.map +1 -0
- package/dist/{journey-CuJrHzEg.js → journey-35yCMNFo.js} +20 -19
- package/dist/journey-35yCMNFo.js.map +1 -0
- package/dist/journey-DAGh5h9k.cjs +2 -0
- package/dist/journey-DAGh5h9k.cjs.map +1 -0
- package/dist/keys-BHhw_0Wh.cjs.map +1 -1
- package/dist/keys-BU9j5YqW.js.map +1 -1
- package/dist/{library-console-D2GY9Or6.cjs → library-console-BFWEuQsl.cjs} +2 -2
- package/dist/library-console-BFWEuQsl.cjs.map +1 -0
- package/dist/{library-console-C1m6g1BR.js → library-console-Dl_Ly6DQ.js} +2 -2
- package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
- package/dist/{library-request-1BX_UlaX.cjs → library-request-Da-CHKzT.cjs} +2 -2
- package/dist/library-request-Da-CHKzT.cjs.map +1 -0
- package/dist/{library-request-BQBT9N9Q.js → library-request-nI6pvI6I.js} +2 -2
- package/dist/library-request-nI6pvI6I.js.map +1 -0
- package/dist/{lifecycle-2EtUaRpo.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
- package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
- package/dist/{lifecycle-BaKx_-32.js → lifecycle-CZ6RRXc6.js} +2 -2
- package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
- package/dist/{log-record-i9zOTkpQ.cjs → log-record-D7bA1RPb.cjs} +2 -2
- package/dist/log-record-D7bA1RPb.cjs.map +1 -0
- package/dist/{log-record-CAoGBBf3.js → log-record-DIA6McNr.js} +2 -2
- package/dist/log-record-DIA6McNr.js.map +1 -0
- package/dist/{long-frames-Czk7IupC.js → long-frames-430_85Da.js} +8 -6
- package/dist/long-frames-430_85Da.js.map +1 -0
- package/dist/long-frames-Dd8tsi2U.cjs +2 -0
- package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
- package/dist/models/batch.d.ts +14 -15
- package/dist/models/bus.d.ts +24 -24
- package/dist/models/config.d.ts +402 -216
- package/dist/models/drop.d.ts +13 -11
- package/dist/models/health.d.ts +13 -13
- package/dist/models/log-record.d.ts +13 -14
- package/dist/models/metric.d.ts +82 -17
- package/dist/models/plugin.d.ts +13 -13
- package/dist/models/replay.d.ts +60 -0
- package/dist/models/serializer.d.ts +2 -3
- package/dist/models/stats.d.ts +2 -2
- package/dist/models/storage.d.ts +12 -11
- package/dist/{network-DBNwApoF.js → network-C7SkLf4v.js} +12 -12
- package/dist/network-C7SkLf4v.js.map +1 -0
- package/dist/{network-xbbuvG_6.cjs → network-pEX3PAJv.cjs} +2 -2
- package/dist/network-pEX3PAJv.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/otlp-2MCrC3kd.cjs +2 -0
- package/dist/otlp-2MCrC3kd.cjs.map +1 -0
- package/dist/{otlp-BTJdIa6F.js → otlp-COq033e3.js} +25 -32
- package/dist/otlp-COq033e3.js.map +1 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -1
- package/dist/patch-UdPz1ea8.js.map +1 -1
- package/dist/{platform-C2Ez5kDc.cjs → platform-12uR7kBQ.cjs} +2 -2
- package/dist/platform-12uR7kBQ.cjs.map +1 -0
- package/dist/{platform-DkcuXwe-.js → platform-CVewe4wQ.js} +7 -7
- package/dist/platform-CVewe4wQ.js.map +1 -0
- package/dist/profiler-BVWIOgnq.js +310 -0
- package/dist/profiler-BVWIOgnq.js.map +1 -0
- package/dist/profiler-eVCknCzS.cjs +2 -0
- package/dist/profiler-eVCknCzS.cjs.map +1 -0
- package/dist/profiler-frames-CLXlT_xL.js +86 -0
- package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
- package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
- package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
- package/dist/{remote-rules-Cfb4K-Nl.js → remote-rules-BJGDJGwA.js} +27 -27
- package/dist/remote-rules-BJGDJGwA.js.map +1 -0
- package/dist/{remote-rules-vzvk7aKf.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
- package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
- package/dist/replay-0zAJv9T3.js +338 -0
- package/dist/replay-0zAJv9T3.js.map +1 -0
- package/dist/replay-DomJpXqW.cjs +2 -0
- package/dist/replay-DomJpXqW.cjs.map +1 -0
- package/dist/{reports-Dk2YhKIh.cjs → reports-BsbqmP8h.cjs} +2 -2
- package/dist/reports-BsbqmP8h.cjs.map +1 -0
- package/dist/{reports-TA-zInnq.js → reports-BuXekPOS.js} +3 -3
- package/dist/reports-BuXekPOS.js.map +1 -0
- package/dist/{resource-timing-BLv3EA2A.js → resource-timing-CXGHwFRD.js} +4 -4
- package/dist/resource-timing-CXGHwFRD.js.map +1 -0
- package/dist/{resource-timing-Cysw1S1f.cjs → resource-timing-DkycFGDa.cjs} +2 -2
- package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
- package/dist/{sampling-Ckh2yW9k.cjs → sampling-Dd0wllyq.cjs} +2 -2
- package/dist/sampling-Dd0wllyq.cjs.map +1 -0
- package/dist/{sampling-C4VV-1MS.js → sampling-UUDbi3K0.js} +9 -9
- package/dist/sampling-UUDbi3K0.js.map +1 -0
- package/dist/{sanitize-6ymPlVvP.js → sanitize-CNmsD9r3.js} +2 -2
- package/dist/sanitize-CNmsD9r3.js.map +1 -0
- package/dist/{sanitize-BAWzkZt0.cjs → sanitize-ChLn97Ch.cjs} +2 -2
- package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
- package/dist/{select-ZF4by-lF.cjs → select-CTk-K5mG.cjs} +3 -3
- package/dist/select-CTk-K5mG.cjs.map +1 -0
- package/dist/{select-xtQaenIi.js → select-DPv_j6wq.js} +61 -61
- package/dist/select-DPv_j6wq.js.map +1 -0
- package/dist/{sender-CiMHC9YG.js → sender-15zEsZpr.js} +61 -60
- package/dist/sender-15zEsZpr.js.map +1 -0
- package/dist/sender-Bfpv9tad.cjs +2 -0
- package/dist/sender-Bfpv9tad.cjs.map +1 -0
- package/dist/storage/context-storage.d.ts +34 -33
- package/dist/storage/emergency-queue.d.ts +9 -9
- package/dist/storage/eviction.d.ts +12 -12
- package/dist/storage/factory.d.ts +8 -7
- package/dist/storage/gap.d.ts +6 -6
- package/dist/storage/idb-driver.d.ts +31 -32
- package/dist/storage/indexeddb-storage.d.ts +26 -27
- package/dist/storage/keys.d.ts +7 -7
- package/dist/storage/local-storage.d.ts +38 -38
- package/dist/storage/memory-storage.d.ts +21 -22
- package/dist/storage/persistence.d.ts +1 -1
- package/dist/storage-BA9RqRO-.cjs.map +1 -1
- package/dist/storage-DZwed89z.js.map +1 -1
- package/dist/{storm-VR024_QN.js → storm-BTSNTIWI.js} +2 -2
- package/dist/storm-BTSNTIWI.js.map +1 -0
- package/dist/{storm-CYi9Swpx.cjs → storm-D0_qZOEg.cjs} +2 -2
- package/dist/storm-D0_qZOEg.cjs.map +1 -0
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +7 -7
- package/dist/transport/exit-flush.d.ts +39 -39
- package/dist/transport/headers.d.ts +2 -2
- package/dist/transport/http-transport.d.ts +28 -27
- package/dist/transport/memory-transport.d.ts +6 -6
- package/dist/transport/retry-engine.d.ts +35 -34
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
- package/dist/transport/serializers/otlp-traces.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +16 -16
- package/dist/transport/serializers/select.d.ts +7 -7
- package/dist/transport/status-transport.d.ts +20 -20
- package/dist/transport/worker-protocol.d.ts +3 -3
- package/dist/types-BAerHgCq.js.map +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-DFUN57wY.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
- package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
- package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-Cob_jyTv.js} +2 -2
- package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
- package/dist/unref-CU9Nyz_9.cjs +2 -0
- package/dist/unref-CU9Nyz_9.cjs.map +1 -0
- package/dist/unref-DgHPQeWv.js +7 -0
- package/dist/unref-DgHPQeWv.js.map +1 -0
- package/dist/user-timing-CdYqx3PF.cjs +2 -0
- package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
- package/dist/{user-timing-_jZIhDKI.js → user-timing-DgHubxCI.js} +5 -3
- package/dist/user-timing-DgHubxCI.js.map +1 -0
- package/dist/utils/console.d.ts +2 -2
- package/dist/utils/deadline.d.ts +4 -4
- package/dist/utils/error-like.d.ts +7 -7
- package/dist/utils/fixed-window.d.ts +9 -8
- package/dist/utils/global-scope.d.ts +8 -8
- package/dist/utils/guards.d.ts +2 -2
- package/dist/utils/identity.d.ts +17 -17
- package/dist/utils/library-console.d.ts +4 -4
- package/dist/utils/library-request.d.ts +10 -10
- package/dist/utils/lock.d.ts +10 -9
- package/dist/utils/openfin.d.ts +5 -5
- package/dist/utils/patch.d.ts +6 -6
- package/dist/utils/platform.d.ts +13 -11
- package/dist/utils/sanitize.d.ts +4 -4
- package/dist/utils/timer.d.ts +1 -1
- package/dist/utils/tracing.d.ts +38 -38
- package/dist/utils/unref.d.ts +3 -3
- package/dist/{web-socket-BWUoqBh8.cjs → web-socket-BTuvYoJI.cjs} +2 -2
- package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
- package/dist/{web-socket-CV7yIMnm.js → web-socket-DthJuSAg.js} +4 -4
- package/dist/web-socket-DthJuSAg.js.map +1 -0
- package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
- package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
- package/dist/web-vitals-CsGCWnUr.js +77 -0
- package/dist/web-vitals-CsGCWnUr.js.map +1 -0
- package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-B0_8rWy5.js} +4 -4
- package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
- package/dist/{worker-protocol-Bai7GAIA.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
- package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
- package/dist/worker-server-4en-Lt-3.cjs +2 -0
- package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
- package/dist/{worker-server-Dp5HYm4b.js → worker-server-Cne9MX9I.js} +8 -8
- package/dist/{worker-server-Dp5HYm4b.js.map → worker-server-Cne9MX9I.js.map} +1 -1
- package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
- package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
- package/dist/{worker-transport-D6jtgpqN.js → worker-transport-C3SjJAEC.js} +62 -61
- package/dist/worker-transport-C3SjJAEC.js.map +1 -0
- package/package.json +8 -2
- package/dist/batch-C8OcWR2L.cjs.map +0 -1
- package/dist/batch-CL9uWYY3.js.map +0 -1
- package/dist/bus-BZ0GldpT.js.map +0 -1
- package/dist/bus-VWlmM5xs.cjs +0 -2
- package/dist/bus-VWlmM5xs.cjs.map +0 -1
- package/dist/console-BPZCuSLc.cjs.map +0 -1
- package/dist/console-BeCF7n59.js.map +0 -1
- package/dist/constants-DqKJH_MP.cjs +0 -2
- package/dist/constants-DqKJH_MP.cjs.map +0 -1
- package/dist/constants-zyrqveN4.js +0 -304
- package/dist/constants-zyrqveN4.js.map +0 -1
- package/dist/deadline-BOjOxNHj.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
- package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
- package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
- package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
- package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
- package/dist/errors-Dh7kef0i.js.map +0 -1
- package/dist/errors-tfEr48bS.cjs.map +0 -1
- package/dist/factory-BonqI3NL.js.map +0 -1
- package/dist/factory-CJXVYp0R.cjs.map +0 -1
- package/dist/identity-Cxgj6pZX.cjs.map +0 -1
- package/dist/identity-DT5VmvXy.js.map +0 -1
- package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
- package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
- package/dist/interactions-DTgKy_6K.js.map +0 -1
- package/dist/interactions-fEN6FbVo.cjs.map +0 -1
- package/dist/journey-CuJrHzEg.js.map +0 -1
- package/dist/journey-pffMVMfa.cjs +0 -2
- package/dist/journey-pffMVMfa.cjs.map +0 -1
- package/dist/library-console-C1m6g1BR.js.map +0 -1
- package/dist/library-console-D2GY9Or6.cjs.map +0 -1
- package/dist/library-request-1BX_UlaX.cjs.map +0 -1
- package/dist/library-request-BQBT9N9Q.js.map +0 -1
- package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
- package/dist/lifecycle-BaKx_-32.js.map +0 -1
- package/dist/log-record-CAoGBBf3.js.map +0 -1
- package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
- package/dist/long-frames-BVg4i5SC.cjs +0 -2
- package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
- package/dist/long-frames-Czk7IupC.js.map +0 -1
- package/dist/network-DBNwApoF.js.map +0 -1
- package/dist/network-xbbuvG_6.cjs.map +0 -1
- package/dist/otlp-BDvFrLnc.cjs +0 -2
- package/dist/otlp-BDvFrLnc.cjs.map +0 -1
- package/dist/otlp-BTJdIa6F.js.map +0 -1
- package/dist/platform-C2Ez5kDc.cjs.map +0 -1
- package/dist/platform-DkcuXwe-.js.map +0 -1
- package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
- package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
- package/dist/reports-Dk2YhKIh.cjs.map +0 -1
- package/dist/reports-TA-zInnq.js.map +0 -1
- package/dist/resource-timing-BLv3EA2A.js.map +0 -1
- package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
- package/dist/sampling-C4VV-1MS.js.map +0 -1
- package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
- package/dist/sanitize-6ymPlVvP.js.map +0 -1
- package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
- package/dist/select-ZF4by-lF.cjs.map +0 -1
- package/dist/select-xtQaenIi.js.map +0 -1
- package/dist/sender-CiMHC9YG.js.map +0 -1
- package/dist/sender-D5wBoXA8.cjs +0 -2
- package/dist/sender-D5wBoXA8.cjs.map +0 -1
- package/dist/storm-CYi9Swpx.cjs.map +0 -1
- package/dist/storm-VR024_QN.js.map +0 -1
- package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
- package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
- package/dist/user-timing-C9kfRq3J.cjs +0 -2
- package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
- package/dist/user-timing-_jZIhDKI.js.map +0 -1
- package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
- package/dist/web-socket-CV7yIMnm.js.map +0 -1
- package/dist/web-vitals-Bq4WFHQo.js +0 -52
- package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
- package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
- package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
- package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
- package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
- package/dist/worker-server-BrIYkfoa.cjs +0 -2
- package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
- package/dist/worker-transport-Bwej4N2e.cjs +0 -2
- package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
- package/dist/worker-transport-D6jtgpqN.js.map +0 -1
package/dist/doctor.js
CHANGED
|
@@ -1,44 +1,45 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { B as e, Mn as t, Qt as n, R as r, Zt as i, cn as a, ct as o, ft as s, lt as c, ot as l, st as u, tt as d, ut as f } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
import { t as p } from "./compression-AJJCMBOa.js";
|
|
3
|
+
import { r as m } from "./otlp-COq033e3.js";
|
|
3
4
|
// src/doctor.ts
|
|
4
|
-
var
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
].map((e) => e.toLowerCase()),
|
|
10
|
-
function
|
|
11
|
-
let
|
|
5
|
+
var h = 1e4, g = 0, _ = 1, v = 2, y = "Usage: uiobs doctor <url> --origin <origin> [--replay] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint.", b = "--header", x = "--replay", S = 5e6, C = 5, w = "uiobs-doctor", T = /^([\w!#$%&'*+.^`|~-]+): *([\x20-\x7e]+)$/, E = "<hidden>", D = "Access-Control-Expose-Headers", O = [
|
|
6
|
+
c,
|
|
7
|
+
o,
|
|
8
|
+
u,
|
|
9
|
+
l
|
|
10
|
+
].map((e) => e.toLowerCase()), k = [...O, "origin"], A = [s, f].map((e) => e.toLowerCase());
|
|
11
|
+
function j() {
|
|
12
|
+
let e = crypto.randomUUID().replaceAll("-", "");
|
|
12
13
|
return {
|
|
13
14
|
timeUnixNano: `${String(Date.now())}000000`,
|
|
14
|
-
traceId:
|
|
15
|
-
spanId:
|
|
15
|
+
traceId: e,
|
|
16
|
+
spanId: e.slice(0, 16),
|
|
16
17
|
traceFlags: 1,
|
|
17
|
-
severityNumber:
|
|
18
|
+
severityNumber: t.INFO,
|
|
18
19
|
severityText: "INFO",
|
|
19
20
|
body: "uiobs doctor test record",
|
|
20
21
|
attributes: {},
|
|
21
|
-
resource: { "service.name":
|
|
22
|
+
resource: { "service.name": w }
|
|
22
23
|
};
|
|
23
24
|
}
|
|
24
|
-
async function
|
|
25
|
+
async function M(e, t, n = h) {
|
|
25
26
|
try {
|
|
26
27
|
return await fetch(e, {
|
|
27
28
|
...t,
|
|
28
29
|
redirect: "manual",
|
|
29
|
-
signal: AbortSignal.timeout(
|
|
30
|
+
signal: AbortSignal.timeout(n)
|
|
30
31
|
});
|
|
31
32
|
} catch (e) {
|
|
32
33
|
let t = e instanceof Error ? e.cause ?? e : e;
|
|
33
34
|
return `The request failed. ${t instanceof Error ? t.message : String(t)}`;
|
|
34
35
|
}
|
|
35
36
|
}
|
|
36
|
-
function
|
|
37
|
+
function N(e, t, n) {
|
|
37
38
|
let r = (e.headers.get(t) ?? "").toLowerCase().split(",").map((e) => e.trim());
|
|
38
39
|
return r.includes("*") ? [] : n.filter((e) => !r.includes(e));
|
|
39
40
|
}
|
|
40
|
-
var
|
|
41
|
-
function
|
|
41
|
+
var P = (e) => e.ok ? void 0 : `The server returned ${String(e.status)}.`;
|
|
42
|
+
function F(e, t, n, ...r) {
|
|
42
43
|
let i = typeof t == "string" ? t : r.map((e) => e(t)).find((e) => e !== void 0);
|
|
43
44
|
return {
|
|
44
45
|
rule: e,
|
|
@@ -46,53 +47,147 @@ function S(e, t, n, ...r) {
|
|
|
46
47
|
detail: i ?? n
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
|
-
|
|
50
|
-
let
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
50
|
+
function I(e, t, n) {
|
|
51
|
+
let r = Object.keys(n).map((e) => e.toLowerCase());
|
|
52
|
+
return {
|
|
53
|
+
url: e,
|
|
54
|
+
origin: t,
|
|
55
|
+
custom: n,
|
|
56
|
+
requestHeaders: [...O, ...r]
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function L(e) {
|
|
60
|
+
return (t) => {
|
|
61
|
+
let n = t.headers.get("Access-Control-Allow-Origin");
|
|
62
|
+
return n === e || n === "*" ? void 0 : `Access-Control-Allow-Origin is ${String(n)}. It must allow ${e}.`;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function R({ url: e, origin: t, requestHeaders: n }) {
|
|
66
|
+
return M(e, {
|
|
54
67
|
method: "OPTIONS",
|
|
55
68
|
headers: {
|
|
56
|
-
Origin:
|
|
69
|
+
Origin: t,
|
|
57
70
|
"Access-Control-Request-Method": "POST",
|
|
58
|
-
"Access-Control-Request-Headers":
|
|
71
|
+
"Access-Control-Request-Headers": n.join(", ")
|
|
59
72
|
}
|
|
60
|
-
})
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function z(e, t) {
|
|
76
|
+
return [F("preflight", e, "The server permits POST from this origin.", P, L(t.origin)), F("allowed headers", e, "The server allows each request header of the library.", (e) => {
|
|
77
|
+
let n = N(e, "Access-Control-Allow-Headers", t.requestHeaders);
|
|
78
|
+
return n.length > 0 ? `Access-Control-Allow-Headers must include ${n.join(", ")}.` : void 0;
|
|
79
|
+
})];
|
|
80
|
+
}
|
|
81
|
+
function B({ url: e, origin: t, custom: n }, r, i) {
|
|
82
|
+
return (a, o, s, d = {}) => M(e, {
|
|
61
83
|
method: "POST",
|
|
62
84
|
headers: {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
[
|
|
66
|
-
[
|
|
67
|
-
|
|
85
|
+
...n,
|
|
86
|
+
Origin: t,
|
|
87
|
+
[c]: r,
|
|
88
|
+
[u]: a,
|
|
89
|
+
[l]: String(o),
|
|
90
|
+
...d
|
|
68
91
|
},
|
|
69
92
|
body: s
|
|
70
|
-
}
|
|
93
|
+
}, i);
|
|
94
|
+
}
|
|
95
|
+
async function V(e, t, n) {
|
|
96
|
+
let r = await p(n);
|
|
97
|
+
return r ? e(t, 0, r, { [o]: d }) : "This Node version has no CompressionStream.";
|
|
98
|
+
}
|
|
99
|
+
async function H(t, r, a = {}) {
|
|
100
|
+
let o = I(t, r, a), s = L(r), l = await R(o), { body: u, contentType: d } = m.serialize([j()]), f = B(o, d), p = crypto.randomUUID(), h = await f(p, 0, u), g = await f(p, 1, u), _ = await V(f, crypto.randomUUID(), u), v = new URL(t);
|
|
101
|
+
v.searchParams.set(i, crypto.randomUUID()), v.searchParams.set(n, "pagehide");
|
|
102
|
+
let y = o.requestHeaders.length > O.length ? void 0 : await M(v.toString(), {
|
|
103
|
+
method: "POST",
|
|
104
|
+
headers: {
|
|
105
|
+
Origin: r,
|
|
106
|
+
[c]: e
|
|
107
|
+
},
|
|
108
|
+
body: u
|
|
109
|
+
}), b = typeof h == "string" ? [] : N(h, D, A), x = b.length > 0 ? ` Optional headers stay hidden: ${b.join(", ")}.` : "";
|
|
110
|
+
return [
|
|
111
|
+
...z(l, o),
|
|
112
|
+
F("test batch", h, "The server accepted a test batch.", P, s),
|
|
113
|
+
F("exposed headers", h, `The server exposes Retry-After.${x}`, (e) => N(e, D, ["retry-after"]).length > 0 ? `${D} must include retry-after.` : void 0),
|
|
114
|
+
F("gzip", _, "The server accepted a gzip batch.", P),
|
|
115
|
+
F("deduplication", g, "The server accepted a repeated batch id. A client cannot see if it stored the batch again.", P),
|
|
116
|
+
y === void 0 ? {
|
|
117
|
+
rule: "beacon",
|
|
118
|
+
pass: !0,
|
|
119
|
+
detail: "The library sends no beacon with custom headers. The tool sent no beacon."
|
|
120
|
+
} : F("beacon", y, "The server accepted a text/plain batch.", P)
|
|
121
|
+
];
|
|
122
|
+
}
|
|
123
|
+
async function U(e, t, n = {}) {
|
|
124
|
+
let i = I(e, t, n), o = L(t), s = await R(i), c = crypto.randomUUID(), l = {
|
|
125
|
+
"replay.id": c,
|
|
126
|
+
"session.id": crypto.randomUUID(),
|
|
127
|
+
"tab.id": crypto.randomUUID(),
|
|
128
|
+
"service.name": w
|
|
129
|
+
}, u = (e, t) => {
|
|
130
|
+
let n = [{
|
|
131
|
+
type: C,
|
|
132
|
+
timestamp: Date.now(),
|
|
133
|
+
data: {
|
|
134
|
+
tag: w,
|
|
135
|
+
payload: t
|
|
136
|
+
}
|
|
137
|
+
}];
|
|
138
|
+
return JSON.stringify({
|
|
139
|
+
...l,
|
|
140
|
+
sequence: e,
|
|
141
|
+
bytes: JSON.stringify(n).length,
|
|
142
|
+
events: n
|
|
143
|
+
});
|
|
144
|
+
}, d = (e) => `${c}-${String(e)}`, f = B(i, r), p = u(0, "uiobs doctor test event"), m = await f(d(0), 0, p), h = await f(d(0), 1, p), g = await V(f, d(1), u(1, "uiobs doctor gzip event")), _ = await B(i, r, a)(d(2), 0, u(2, "x".repeat(S)));
|
|
71
145
|
return [
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
S("test batch", C, "The server accepted a test batch.", x, s),
|
|
78
|
-
S("exposed headers", C, `The server exposes Retry-After.${O}`, (e) => b(e, h, ["retry-after"]).length > 0 ? `${h} must include retry-after.` : void 0),
|
|
79
|
-
S("gzip", E, "The server accepted a gzip batch.", x),
|
|
80
|
-
S("deduplication", w, "The server accepted a repeated batch id. A client cannot see if it stored the batch again.", x)
|
|
146
|
+
...z(s, i),
|
|
147
|
+
F("test segment", m, "The server accepted a test segment.", P, o),
|
|
148
|
+
F("gzip", g, "The server accepted a gzip segment.", P),
|
|
149
|
+
F("large segment", _, `The server accepted a segment of ${String(S)} bytes without gzip.`, (e) => e.ok ? void 0 : `The server returned ${String(e.status)} for a segment of ${String(S)} bytes. The first segment of an upload has a full snapshot of the page. Raise the body limit of the server.`),
|
|
150
|
+
F("deduplication", h, "The server accepted a repeated batch id. A client cannot see if it stored the segment again.", P)
|
|
81
151
|
];
|
|
82
152
|
}
|
|
83
|
-
function
|
|
84
|
-
|
|
153
|
+
function W(e) {
|
|
154
|
+
let t = [];
|
|
155
|
+
for (let n = 0; n < e.length; n += 2) {
|
|
156
|
+
let r = e[n] === b ? T.exec(e[n + 1]) : null;
|
|
157
|
+
if (!r || k.includes(r[1].toLowerCase())) return;
|
|
158
|
+
t.push([r[1], r[2]]);
|
|
159
|
+
}
|
|
160
|
+
return Object.fromEntries(t);
|
|
161
|
+
}
|
|
162
|
+
function G(e) {
|
|
163
|
+
if (!/^https?:\/\//i.test(e) || !URL.canParse(e)) return !1;
|
|
164
|
+
let { username: t, password: n } = new URL(e);
|
|
165
|
+
return t === "" && n === "";
|
|
166
|
+
}
|
|
167
|
+
var K = [
|
|
168
|
+
"doctor",
|
|
169
|
+
"--origin",
|
|
170
|
+
x,
|
|
171
|
+
b
|
|
172
|
+
];
|
|
173
|
+
function q(e) {
|
|
174
|
+
if (K.includes(e)) return e;
|
|
175
|
+
if (/^https?:\/\//i.test(e) && URL.canParse(e)) {
|
|
176
|
+
let { origin: t, pathname: n } = new URL(e);
|
|
177
|
+
return `${t}${n === "/" && !e.endsWith("/") ? "" : n}`;
|
|
178
|
+
}
|
|
179
|
+
return E;
|
|
85
180
|
}
|
|
86
|
-
function
|
|
181
|
+
function J(e) {
|
|
87
182
|
return URL.canParse(e) && new URL(e).origin === e;
|
|
88
183
|
}
|
|
89
|
-
async function
|
|
90
|
-
let [n, r, i, a] = e;
|
|
91
|
-
if (n !== "doctor" || i !== "--origin" || !
|
|
92
|
-
let
|
|
93
|
-
for (let { rule: e, pass: n, detail: r } of
|
|
94
|
-
return
|
|
184
|
+
async function Y(e, t) {
|
|
185
|
+
let [n, r, i, a, ...o] = e, s = o[0] === x, c = W(s ? o.slice(1) : o);
|
|
186
|
+
if (n !== "doctor" || i !== "--origin" || !G(r) || !J(a) || !c) return t(y), t(`Received: ${JSON.stringify(e.map(q))}`), v;
|
|
187
|
+
let l = await (s ? U : H)(r, a, c);
|
|
188
|
+
for (let { rule: e, pass: n, detail: r } of l) t(`${n ? "PASS" : "FAIL"} ${e}: ${r}`);
|
|
189
|
+
return l.every(({ pass: e }) => e) ? g : _;
|
|
95
190
|
}
|
|
96
|
-
export {
|
|
191
|
+
export { Y as main, H as runDoctor, U as runReplayDoctor };
|
|
97
192
|
|
|
98
193
|
//# sourceMappingURL=doctor.js.map
|
package/dist/doctor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor.js","names":["SEVERITY_NUMBER","HEADER_CONTENT_ENCODING","HEADER_SAMPLING","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","HEADER_BATCH_ID","ENCODING_GZIP","HEADER_DATE","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","EXPOSE_HEADERS","REQUEST_HEADERS","name","OPTIONAL_EXPOSED","testRecord","traceId","request","url","init","error","reason","absent","values","response","value","wanted","statusProblem","judge","tests","problem","answer","test","found","passed","runDoctor","originProblem","allowed","origin","preflight","post","contentType","id","attempt","extra","payload","batchId","first","body","repeated","compressed","zipped","hidden","note","missing","isHttpUrl","isOrigin","main","command","flag","args","print","results","pass","rule","detail"],"sources":["../src/doctor.ts"],"sourcesContent":["// src/doctor.ts\n//\n// Checks an ingest server against the ingest contract in the README. The `uiobs doctor` command\n// calls main(). The code uses web APIs only. The browser build replaces each \"node:\" import.\n\nimport {\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 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/** Maximum wait for one answer, in milliseconds. */\nconst REQUEST_TIMEOUT_MS = 10000;\n\n/** Exit code when each rule passes. */\nconst EXIT_PASS = 0;\n\n/** Exit code when a rule fails. */\nconst EXIT_FAIL = 1;\n\n/** Exit code of a wrong command. */\nconst EXIT_USAGE = 2;\n\n/** Text of a wrong command. */\nconst USAGE =\n \"Usage: uiobs doctor <url> --origin <origin>. An origin has no path and no trailing slash.\";\n\n/** Response header that lists the headers a page can read. */\nconst EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n\n/** Request headers of the library. The server must allow each one. */\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/** Response headers that only an optional feature reads. */\nconst OPTIONAL_EXPOSED = [HEADER_SAMPLING, HEADER_DATE].map((name) => name.toLowerCase());\n\n/** Result of one rule of the ingest contract. */\nexport interface DoctorResult {\n /** Rule name. */\n rule: string;\n /** True when the server meets the rule. */\n pass: boolean;\n /** Reason of the result. */\n detail: string;\n}\n\n/** An HTTP answer, or the text of a failed request. */\ntype Answer = Response | string;\n\n/** Gives the text of a problem, or undefined when the answer meets the test. */\ntype AnswerTest = (response: Response) => string | undefined;\n\n/** Builds the test record. The server stores it as an ordinary 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\": \"uiobs-doctor\" },\n };\n}\n\n/** Sends one request. The result line reports a failure. The tool has no diagnostics instance. */\nasync function request(url: string, init: RequestInit): Promise<Answer> {\n try {\n // A browser refuses a preflight that redirects. A redirect can also name another host.\n return await fetch(url, {\n ...init,\n redirect: \"manual\",\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n // Node gives only \"fetch failed\". The cause holds the reason, for example ECONNREFUSED.\n const reason: unknown = error instanceof Error ? (error.cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Gives the wanted values that a comma-separated header omits. A wildcard has each value. */\nfunction absent(response: Response, name: string, wanted: readonly string[]): string[] {\n const values = (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n\n return values.includes(\"*\") ? [] : wanted.filter((value) => !values.includes(value));\n}\n\n/** Tests the status of an answer. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\n\n/** Builds the result of one rule. The first problem is 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/**\n * Sends the requests of each rule, one at a time. Two requests with one batch id must not overlap.\n * @param url Ingest URL.\n * @param origin Origin of the app.\n * @returns One result for each rule.\n */\nexport async function runDoctor(url: string, origin: string): Promise<DoctorResult[]> {\n const originProblem: AnswerTest = (response) => {\n const allowed = response.headers.get(\"Access-Control-Allow-Origin\");\n\n return allowed === origin || allowed === \"*\"\n ? undefined\n : `Access-Control-Allow-Origin is ${String(allowed)}. It must allow ${origin}.`;\n };\n\n const preflight = await request(url, {\n method: \"OPTIONS\",\n headers: {\n Origin: origin,\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": REQUEST_HEADERS.join(\", \"),\n },\n });\n\n const { body, contentType } = otlpSerializer.serialize([testRecord()]);\n const post = (\n id: string,\n attempt: number,\n payload: BodyInit,\n extra: Record<string, string> = {},\n ): Promise<Answer> =>\n request(url, {\n method: \"POST\",\n headers: {\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\n const batchId = crypto.randomUUID();\n const first = await post(batchId, 0, body);\n const repeated = await post(batchId, 1, body);\n const compressed = await gzip(body);\n const zipped = compressed\n ? await post(crypto.randomUUID(), 0, compressed, {\n [HEADER_CONTENT_ENCODING]: ENCODING_GZIP,\n })\n : \"This Node version has no CompressionStream.\";\n\n const hidden = typeof first === \"string\" ? [] : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED);\n const note = hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n\n return [\n judge(\n \"preflight\",\n preflight,\n \"The server permits POST from this origin.\",\n statusProblem,\n originProblem,\n ),\n judge(\n \"allowed headers\",\n preflight,\n \"The server allows each request header of the library.\",\n (response) => {\n const missing = absent(response, \"Access-Control-Allow-Headers\", REQUEST_HEADERS);\n\n return missing.length > 0\n ? `Access-Control-Allow-Headers must include ${missing.join(\", \")}.`\n : undefined;\n },\n ),\n judge(\"test batch\", first, \"The server accepted a test batch.\", statusProblem, originProblem),\n judge(\"exposed headers\", first, `The server exposes Retry-After.${note}`, (response) =>\n absent(response, EXPOSE_HEADERS, [HEADER_RETRY_AFTER.toLowerCase()]).length > 0\n ? `${EXPOSE_HEADERS} must include retry-after.`\n : undefined,\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 ];\n}\n\n/** Tests an HTTP URL. */\nfunction isHttpUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value) && URL.canParse(value);\n}\n\n/** Tests an exact browser origin. A path or a trailing slash does not 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] = args;\n\n if (command !== \"doctor\" || flag !== \"--origin\" || !isHttpUrl(url) || !isOrigin(origin)) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args)}`);\n return EXIT_USAGE;\n }\n\n const results = await runDoctor(url, origin);\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":";;;AAqBA,IAAMU,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,6FAGIC,IAAiB,iCAGjBC,IAAkB;CACtBb;CACAF;CACAI;CACAD;AACF,CAAC,CAAC,KAAK,MAASa,EAAK,YAAY,CAAC,GAG5BC,IAAmB,CAAChB,GAAiBK,CAAW,CAAC,CAAC,KAAK,MAASU,EAAK,YAAY,CAAC;AAmBxF,SAASE,IAAwB;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,gBAAgBpB,EAAgB;EAChC,cAAc;EACd,MAAM;EACN,YAAY,CAAC;EACb,UAAU,EAAE,gBAAgB,eAAe;CAC7C;AACF;AAGA,eAAeqB,EAAQ,GAAa,GAAoC;CACtE,IAAI;EAEF,OAAO,MAAM,MAAMC,GAAK;GACtB,GAAGC;GACH,UAAU;GACV,QAAQ,YAAY,QAAQb,CAAkB;EAChD,CAAC;CACH,SAASc,GAAO;EAEd,IAAMC,IAAkBD,aAAiB,QAASA,EAAM,SAASA,IAASA;EAE1E,OAAO,uBAAuBC,aAAkB,QAAQA,EAAO,UAAU,OAAOA,CAAM;CACxF;AACF;AAGA,SAASC,EAAO,GAAoB,GAAc,GAAqC;CACrF,IAAMC,KAAUC,EAAS,QAAQ,IAAIX,CAAI,KAAK,GAAA,CAC3C,YAAY,CAAC,CACb,MAAM,GAAG,CAAC,CACV,KAAK,MAAUY,EAAM,KAAK,CAAC;CAE9B,OAAOF,EAAO,SA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AU,MAAM3B,EAAUjB,GAAKoB,CAAM;CAE3C,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYwB,GACnC,EAAM,GAAGC,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOH,EAAQ,OAAO,EAAE,cAAWC,CAAI,IAAIxD,IAAYC;AACzD"}
|
|
1
|
+
{"version":3,"file":"doctor.js","names":["LIBRARY_TIMEOUT_MS","CONTENT_TYPE_TEXT_PLAIN","SEVERITY_NUMBER","QUERY_PARAM_EXIT_REASON","CONTENT_TYPE_JSON","QUERY_PARAM_BATCH_ID","REQUEST_TIMEOUT_MS$1","HEADER_CONTENT_ENCODING","HEADER_SAMPLING","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","HEADER_BATCH_ID","ENCODING_GZIP","HEADER_DATE","gzip","otlpSerializer","REQUEST_TIMEOUT_MS","EXIT_PASS","EXIT_FAIL","EXIT_USAGE","USAGE","HEADER_FLAG","REPLAY_FLAG","LARGE_EVENT_CHARS","CUSTOM_EVENT","DOCTOR_NAME","HEADER_PATTERN","HIDDEN","EXPOSE_HEADERS","REQUEST_HEADERS","name","RESERVED_HEADERS","OPTIONAL_EXPOSED","testRecord","traceId","request","url","init","timeoutMs","error","reason","absent","values","response","value","wanted","statusProblem","judge","tests","problem","answer","test","found","passed","targetOf","customNames","custom","originTest","allowed","origin","sendPreflight","requestHeaders","preflightResults","preflight","target","missing","poster","contentType","id","attempt","extra","payload","postZipped","compressed","body","post","runDoctor","originProblem","batchId","first","repeated","zipped","beaconUrl","beacon","hidden","note","runReplayDoctor","replayId","head","segment","events","text","idOf","sequence","small","large","customHeaders","pairs","index","args","match","isHttpUrl","username","password","SHOWN_WORDS","shownArgument","arg","pathname","isOrigin","main","command","flag","rest","replay","headers","print","results","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 the README. The\n// `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 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] [--header \"Name: value\"]. An origin has no path and no trailing slash. With --replay, the URL is a replay endpoint.';\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/**\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/** 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 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 = error instanceof Error ? (error.cause ?? error) : error;\n\n return `The request failed. ${reason instanceof Error ? reason.message : String(reason)}`;\n }\n}\n\n/** Returns the wanted values a comma-separated header leaves out. A wildcard covers them all. */\nfunction absent(response: Response, name: string, wanted: readonly string[]): string[] {\n const values = (response.headers.get(name) ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((value) => value.trim());\n\n return values.includes(\"*\") ? [] : wanted.filter((value) => !values.includes(value));\n}\n\n/** Checks an answer's status. */\nconst statusProblem: AnswerTest = (response) =>\n response.ok ? undefined : `The server returned ${String(response.status)}.`;\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}\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(url: string, origin: string, custom: Readonly<Record<string, string>>): Target {\n const customNames = Object.keys(custom).map((name) => name.toLowerCase());\n\n return { url, origin, custom, requestHeaders: [...REQUEST_HEADERS, ...customNames] };\n}\n\n/** Builds the test that an answer lets the app's origin read it. */\nfunction originTest(origin: string): AnswerTest {\n return (response) => {\n const allowed = response.headers.get(\"Access-Control-Allow-Origin\");\n\n return allowed === origin || allowed === \"*\"\n ? undefined\n : `Access-Control-Allow-Origin is ${String(allowed)}. It must allow ${origin}.`;\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 return [\n judge(\n \"preflight\",\n preflight,\n \"The server permits POST from this origin.\",\n statusProblem,\n originTest(target.origin),\n ),\n judge(\n \"allowed headers\",\n preflight,\n \"The server allows each request header of the library.\",\n (response) => {\n const missing = absent(response, \"Access-Control-Allow-Headers\", target.requestHeaders);\n\n return missing.length > 0\n ? `Access-Control-Allow-Headers must include ${missing.join(\", \")}.`\n : undefined;\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 * @returns One result per rule.\n */\nexport async function runDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom);\n const originProblem = originTest(origin);\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 = typeof first === \"string\" ? [] : absent(first, EXPOSE_HEADERS, OPTIONAL_EXPOSED);\n const note = hidden.length > 0 ? ` Optional headers stay hidden: ${hidden.join(\", \")}.` : \"\";\n\n return [\n ...preflightResults(preflight, target),\n judge(\"test batch\", first, \"The server accepted a test batch.\", statusProblem, originProblem),\n judge(\"exposed headers\", first, `The server exposes Retry-After.${note}`, (response) =>\n absent(response, EXPOSE_HEADERS, [HEADER_RETRY_AFTER.toLowerCase()]).length > 0\n ? `${EXPOSE_HEADERS} must include retry-after.`\n : undefined,\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(\"beacon\", beacon, \"The server accepted a text/plain batch.\", statusProblem),\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 * @returns One result per rule.\n */\nexport async function runReplayDoctor(\n url: string,\n origin: string,\n custom: Readonly<Record<string, string>> = {},\n): Promise<DoctorResult[]> {\n const target = targetOf(url, origin, custom);\n const originProblem = originTest(origin);\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.\",\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/**\n * Parses the header options. Each one is the flag followed by a \"Name: value\" argument.\n * @param args The arguments after the origin.\n * @returns The headers, or undefined if an option is malformed.\n */\nfunction customHeaders(args: readonly string[]): Record<string, string> | undefined {\n const pairs: [string, string][] = [];\n\n for (let index = 0; index < args.length; index += 2) {\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 Object.fromEntries(pairs);\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 = [\"doctor\", \"--origin\", REPLAY_FLAG, HEADER_FLAG];\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 header option.\n const replay = rest[0] === REPLAY_FLAG;\n const headers = customHeaders(replay ? rest.slice(1) : rest);\n\n if (\n command !== \"doctor\" ||\n flag !== \"--origin\" ||\n !isHttpUrl(url) ||\n !isOrigin(origin) ||\n !headers\n ) {\n print(USAGE);\n print(`Received: ${JSON.stringify(args.map(shownArgument))}`);\n return EXIT_USAGE;\n }\n\n const results = await (replay ? runReplayDoctor : runDoctor)(url, origin, headers);\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":";;;;AA2BA,IAAMgB,IAAqB,KAGrBC,IAAY,GAGZC,IAAY,GAGZC,IAAa,GAGbC,IACJ,gLAGIC,IAAc,YAGdC,IAAc,YAMdC,IAAoB,KAGpBC,IAAe,GAGfC,IAAc,gBAGdC,IAAiB,4CAGjBC,IAAS,YAGTC,IAAiB,iCAGjBC,IAAkB;CACtBpB;CACAF;CACAI;CACAD;AACF,CAAC,CAAC,KAAK,MAASoB,EAAK,YAAY,CAAC,GAG5BC,IAAmB,CAAC,GAAGF,GAAiB,QAAQ,GAGhDG,IAAmB,CAACxB,GAAiBK,CAAW,CAAC,CAAC,KAAK,MAASiB,EAAK,YAAY,CAAC;AAmBxF,SAASG,IAAwB;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,gBAAgBhC,EAAgB;EAChC,cAAc;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eAAsBiE,EACpB,GACA,GACiB;CACjB,IAAM,CAACC,GAAS1E,GAAK2E,GAAMpD,GAAQ,GAAGqD,KAAQb,GAExCc,IAASD,EAAK,OAAO1F,GACrB4F,IAAUlB,EAAciB,IAASD,EAAK,MAAM,CAAC,IAAIA,CAAI;CAE3D,IACEF,MAAY,YACZC,MAAS,cACT,CAACV,EAAUjE,CAAG,KACd,CAACwE,EAASjD,CAAM,KAChB,CAACuD,GAID,OAFAC,EAAM/F,CAAK,GACX+F,EAAM,aAAa,KAAK,UAAUhB,EAAK,IAAIM,CAAa,CAAC,GAAG,GACrDtF;CAGT,IAAMiG,IAAU,OAAOH,IAAS3B,IAAkBV,EAAA,CAAWxC,GAAKuB,GAAQuD,CAAO;CAEjF,KAAK,IAAM,EAAE,SAAM,SAAM,eAAYE,GACnC,EAAM,GAAGC,IAAO,SAAS,OAAO,GAAGC,EAAK,IAAIC,GAAQ;CAGtD,OAAOH,EAAQ,OAAO,EAAE,cAAWC,CAAI,IAAIpG,IAAYC;AACzD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as n } from "./batch-
|
|
3
|
-
import { n as r } from "./deadline-
|
|
1
|
+
import { Fn as e, et as t } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
import { i as n } from "./batch-BjQUwjA6.js";
|
|
3
|
+
import { n as r } from "./deadline-C4ccAuk5.js";
|
|
4
4
|
import { n as i, t as a } from "./keys-BU9j5YqW.js";
|
|
5
5
|
// src/utils/lock.ts
|
|
6
6
|
function o(e, t, n, { skipIfBusy: r = !0 } = {}) {
|
|
@@ -64,4 +64,4 @@ function p(e = "") {
|
|
|
64
64
|
}
|
|
65
65
|
export { f as clearEmergencyContext, d as drainEmergencyQueue, o as n, u as saveToEmergencyQueue, s as t };
|
|
66
66
|
|
|
67
|
-
//# sourceMappingURL=emergency-queue-
|
|
67
|
+
//# sourceMappingURL=emergency-queue-B9WZxanZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emergency-queue-B9WZxanZ.js","names":["STORAGE_DEADLINE_MS","EMERGENCY_STORAGE_KEY_PREFIX","isLogBatch","withDeadline","keysWithPrefix","batchKey","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates batch draining across the origin with the Web Locks API. Without the lock,\n// every window on the origin would drain and send the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock isn't available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Runs an async function under an origin-wide Web Locks API lock. Runs the task directly when\n * the Web Locks API isn't available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn The async task to run while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task doesn't run if another context holds the lock.\n * @returns A promise of the task's result. Resolves to undefined when another context holds\n * the lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API isn't available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Returns the lock name for one application namespace, so two namespaces on one origin don't\n * wait for each other. Otherwise one application's retry pass would be skipped while the\n * other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns The lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// A synchronous localStorage queue that holds oversized batches during unload, to be recovered\n// on the next startup. Everything here is synchronous and never throws, because it runs while\n// the browser is destroying the document and no promise settles at that point.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw The raw serialized string from storage.\n * @param diagnostics Diagnostics reporter.\n * @returns The validated LogBatch, or null if it can't be parsed or is malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports every emergency queue entry into the target adapter, in FIFO order.\n * @param storage The destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns The total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save, so a second\n // window importing at the same time can't take the same batch. Each entry is parsed once.\n // A batch that belongs to another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // This runs during startup, so set a deadline. A save that never settles would keep the\n // runtime from becoming ready, and every record would go to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Synchronously writes an unsent batch to the emergency queue during unload.\n * @param batch The oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of old entries the queue drops, and of a batch the\n * store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count, because a full localStorage drops this batch for good. Removing\n // emergency keys can't free quota that other applications' keys are using.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window already removed reads as null, and readBatch rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this, and a throw here would skip the sender's shutdown.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage The destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns A promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes one context's emergency entries, or every entry in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace The application's storage namespace.\n * @param all True to remove the entries of every context in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Returns the emergency storage prefix for one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns The prefix of this application's emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":";;;;;AAoCA,SAAgBM,EACd,GACA,GACA,GACA,EAAE,gBAAa,OAAmC,CAAC,GAC3B;CACxB,IAAMC,IAAS,WAA2D,WAAW;CAOrF,OAJKA,GAAO,UAILC,EAAY,WACjB,oBACA,sCAAsCC,EAAK,UAEzCF,EAAM,QAAQE,GAAM,EAAE,aAAaC,EAAW,IAAI,MAChDC,IAAOC,EAAG,IAAI,QAAQ,QAAQ,KAAA,CAAS,CACzC,CACJ,IAVSA,EAAG;AAWd;AAUA,SAAgBC,EAAS,GAAc,GAA2B;CAChE,OAAOC,IAAY,GAAGL,EAAK,GAAG,mBAAmBK,CAAS,MAAML;AAClE;;AC3CA,SAASM,EAAU,GAAa,GAA2C;CACzE,IAAMC,IAASR,EAAY,MACzB,oBACA,uEACM,KAAK,MAAMS,CAAG,CACtB;CAeA,OAZID,MAAW,KAAA,IACN,OAGJd,EAAWc,CAAM,IAQfA,KAPLR,EAAY,OACV,oBACA,4DACF,GACO;AAIX;AAQA,eAAeU,EACb,GACA,GACA,GACA,GACiB;CACjB,IAAIC,IAAQ;CAEZ,KAAK,IAAMC,KAAOhB,EAAeiB,GAAQb,CAAW,GAAG;EAIrD,IAAMc,IAAQd,EAAY,MACxB,uBACA,yDACuB;GACrB,IAAMe,IAAQ,aAAa,QAAQH,CAAG,GAChCJ,IAASO,IAAQR,EAAUQ,GAAOf,CAAW,IAAI;GAKvD,OAJIQ,KAAU,CAACQ,EAAQR,CAAM,IACpB,QAET,aAAa,WAAWI,CAAG,GACpBJ;EACT,CACF;EAEA,IAAKM,GAIL,IAAI;GAIF,AADA,MAAMnB,EAAasB,EA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,SAAgByB,EACd,GACA,GACA,IAAY,IACZ,IAAM,IACA;CACN,IAAMlB,IAASO,EAAgBd,CAAS;CACxC,EAAY,MACV,uBACA,kEACM;EACJ,KAAK,IAAMM,KAAOhB,EAAeiB,GAAQb,CAAW,GAAG;GACrD,IAAMS,IAAM,aAAa,QAAQG,CAAG;GACpC,AAAIH,MAAQuB,KAAOzB,EAAUE,GAAKT,CAAW,CAAC,EAAE,qBAAqBiC,MACnE,aAAa,WAAWrB,CAAG;EAC/B;CACF,CACF;AACF;AAOA,SAASQ,EAAgB,IAAY,IAAY;CAC/C,OAAOd,IACH,+BAA+B,mBAAmBA,CAAS,EAAE,eAC7Db;AACN"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=emergency-queue-
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs"),t=require("./batch-D5LlU4Q9.cjs"),n=require("./deadline-CUGbto-y.cjs"),r=require("./keys-BHhw_0Wh.cjs");function i(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function a(e,t){return t?`${e}:${encodeURIComponent(t)}`:e}function o(e,n){let r=n.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return r===void 0?null:t.i(r)?r:(n.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function s(t,i,a,s){let c=0;for(let l of r.n(s,i)){let r=i.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(l),t=e?o(e,i):null;return t&&!a(t)?null:(localStorage.removeItem(l),t)});if(r)try{await n.n(t.save(r),e.Fn),c++}catch(e){i.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:l},e)}}return c}function c(e,t,n){let i=d(e.persistenceNamespace),a=`writing the emergency queue, ${String(e.records.length)} records`,s=[],c=t.guard(`storage.quota_exceeded`,a,()=>{let n=r.n(i,t);for(let e of n.slice(0,Math.max(0,n.length-20+1))){let n=o(String(localStorage.getItem(e)),t);n!==null&&s.push(n),localStorage.removeItem(e)}return localStorage.setItem(r.t(i,e),JSON.stringify(e)),!0});t.guard(`pipeline.crashed`,`The loss report of the emergency queue failed.`,()=>{if(s.length>0){let e=s.flatMap(e=>e.records);n?.(`exit_queue_full`,e,s.map(e=>e.id))}c!==!0&&n?.(`quota`,e.records,[e.id])})}async function l(e,t,n=()=>!0,r=``){return await i(a(`ui-observability.emergency`,r),t,()=>s(e,t,n,d(r)),{skipIfBusy:!1})??0}function u(e,t,n=``,i=!1){let a=d(n);t.guard(`storage.unavailable`,`The library could not clear the retired emergency queue.`,()=>{for(let n of r.n(a,t)){let r=localStorage.getItem(n);r&&(i||o(r,t)?.routingContextId===e)&&localStorage.removeItem(n)}})}function d(t=``){return t?`ui-observability:namespaced:${encodeURIComponent(t)}:emergency:`:e.et}exports.clearEmergencyContext=u,exports.drainEmergencyQueue=l,exports.n=i,exports.saveToEmergencyQueue=c,exports.t=a;
|
|
2
|
+
//# sourceMappingURL=emergency-queue-HBpL5r3V.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emergency-queue-HBpL5r3V.cjs","names":["isLogBatch","keysWithPrefix","withDeadline","STORAGE_DEADLINE_MS","batchKey","EMERGENCY_STORAGE_KEY_PREFIX","require_constants","require_batch","require_deadline","require_keys","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates batch draining across the origin with the Web Locks API. Without the lock,\n// every window on the origin would drain and send the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock isn't available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Runs an async function under an origin-wide Web Locks API lock. Runs the task directly when\n * the Web Locks API isn't available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn The async task to run while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task doesn't run if another context holds the lock.\n * @returns A promise of the task's result. Resolves to undefined when another context holds\n * the lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API isn't available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Returns the lock name for one application namespace, so two namespaces on one origin don't\n * wait for each other. Otherwise one application's retry pass would be skipped while the\n * other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns The lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// A synchronous localStorage queue that holds oversized batches during unload, to be recovered\n// on the next startup. Everything here is synchronous and never throws, because it runs while\n// the browser is destroying the document and no promise settles at that point.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw The raw serialized string from storage.\n * @param diagnostics Diagnostics reporter.\n * @returns The validated LogBatch, or null if it can't be parsed or is malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports every emergency queue entry into the target adapter, in FIFO order.\n * @param storage The destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns The total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save, so a second\n // window importing at the same time can't take the same batch. Each entry is parsed once.\n // A batch that belongs to another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // This runs during startup, so set a deadline. A save that never settles would keep the\n // runtime from becoming ready, and every record would go to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Synchronously writes an unsent batch to the emergency queue during unload.\n * @param batch The oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of old entries the queue drops, and of a batch the\n * store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count, because a full localStorage drops this batch for good. Removing\n // emergency keys can't free quota that other applications' keys are using.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window already removed reads as null, and readBatch rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this, and a throw here would skip the sender's shutdown.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage The destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns A promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes one context's emergency entries, or every entry in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace The application's storage namespace.\n * @param all True to remove the entries of every context in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Returns the emergency storage prefix for one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns The prefix of this application's emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":"A,oJAoCA,SAAgBU,EACd,EACA,EACA,EACA,CAAE,aAAa,IAAmC,CAAC,EAC3B,CACxB,IAAMC,EAAS,WAA2D,WAAW,MAOrF,OAJKA,GAAO,QAILC,EAAY,WACjB,mBACA,sCAAsCC,EAAK,OAEzCF,EAAM,QAAQE,EAAM,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AAS,EAAE,aAC7Db,EAAAA,EACN,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-like-B11pB4aL.js","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/**
|
|
1
|
+
{"version":3,"file":"error-like-B11pB4aL.js","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/** The standard error fields. Any other own field is written as error data. */\nexport const ERROR_OWN_KEYS: ReadonlySet<string> = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * Checks whether a value is a field that error data keeps. An object field, such as an\n * AxiosError's config, holds credentials and request bodies.\n * @param value Field value.\n * @returns True for a string, a number or a boolean.\n */\nexport function isDataField(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\n/** The error fields that the library reads. */\nexport interface ErrorLike {\n /** Error class name, for example \"TypeError\". */\n name: string;\n /** Error message. */\n message: string;\n /** Stack trace text. */\n stack?: string;\n}\n\n/**\n * Checks whether a value has the shape of an error. A getter on a hostile value can throw, so\n * call this inside a diagnostics guard.\n * @param value The value to check.\n * @returns True for an object with a string name, a string message and a string or no stack.\n */\nexport function isErrorLike(value: unknown): value is ErrorLike {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n return (\n typeof candidate.name === \"string\" &&\n typeof candidate.message === \"string\" &&\n (candidate.stack === undefined || typeof candidate.stack === \"string\")\n );\n}\n"],"mappings":";AAMA,IAAaA,oBAAsC,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAS;AAAO,CAAC;AAQhG,SAAgBC,EAAY,GAAyB;CACnD,OAAO,OAAOC,KAAU,YAAY,OAAOA,KAAU,YAAY,OAAOA,KAAU;AACpF;AAkBA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAME,IAAYF;CAClB,OACE,OAAOE,EAAU,QAAS,YAC1B,OAAOA,EAAU,WAAY,aAC5BA,EAAU,UAAU,KAAA,KAAa,OAAOA,EAAU,SAAU;AAEjE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-like-gGRx2s36.cjs","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/**
|
|
1
|
+
{"version":3,"file":"error-like-gGRx2s36.cjs","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/** The standard error fields. Any other own field is written as error data. */\nexport const ERROR_OWN_KEYS: ReadonlySet<string> = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * Checks whether a value is a field that error data keeps. An object field, such as an\n * AxiosError's config, holds credentials and request bodies.\n * @param value Field value.\n * @returns True for a string, a number or a boolean.\n */\nexport function isDataField(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\n/** The error fields that the library reads. */\nexport interface ErrorLike {\n /** Error class name, for example \"TypeError\". */\n name: string;\n /** Error message. */\n message: string;\n /** Stack trace text. */\n stack?: string;\n}\n\n/**\n * Checks whether a value has the shape of an error. A getter on a hostile value can throw, so\n * call this inside a diagnostics guard.\n * @param value The value to check.\n * @returns True for an object with a string name, a string message and a string or no stack.\n */\nexport function isErrorLike(value: unknown): value is ErrorLike {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n return (\n typeof candidate.name === \"string\" &&\n typeof candidate.message === \"string\" &&\n (candidate.stack === undefined || typeof candidate.stack === \"string\")\n );\n}\n"],"mappings":"AAMA,IAAaA,EAAsC,IAAI,IAAI,CAAC,OAAQ,UAAW,QAAS,OAAO,CAAC,EAQhG,SAAgBC,EAAY,EAAyB,CACnD,OAAO,OAAOC,GAAU,UAAY,OAAOA,GAAU,UAAY,OAAOA,GAAU,SACpF,CAkBA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAGT,IAAME,EAAYF,EAClB,OACE,OAAOE,EAAU,MAAS,UAC1B,OAAOA,EAAU,SAAY,WAC5BA,EAAU,QAAU,IAAA,IAAa,OAAOA,EAAU,OAAU,SAEjE,C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as e } from "./error-like-B11pB4aL.js";
|
|
2
|
-
import { i as t } from "./platform-
|
|
3
|
-
import { t as n } from "./storm-
|
|
2
|
+
import { i as t } from "./platform-CVewe4wQ.js";
|
|
3
|
+
import { t as n } from "./storm-BTSNTIWI.js";
|
|
4
4
|
// src/capture/errors.ts
|
|
5
5
|
function r(t) {
|
|
6
6
|
if (e(t)) {
|
|
@@ -89,4 +89,4 @@ var i = class {
|
|
|
89
89
|
};
|
|
90
90
|
export { i as ErrorCapture };
|
|
91
91
|
|
|
92
|
-
//# sourceMappingURL=errors-
|
|
92
|
+
//# sourceMappingURL=errors-D6bwgJtO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-D6bwgJtO.js","names":["isErrorLike","recordedUrl","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\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 const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\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.capturePolicy.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.capturePolicy.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.capturePolicy.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 (\n this.ctx.config.capturePolicy.maxErrorSignatures > 0 &&\n this.seen.size > this.ctx.config.capturePolicy.maxErrorSignatures\n ) {\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":";;;;AAgCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAA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zB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMT,CAAO,IAAIS;EAC1D,KAAK,IAAI,OAAO,MAAMT,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-12uR7kBQ.cjs"),n=require("./storm-D0_qZOEg.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
|
|
2
2
|
`)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count:0};constructor(e){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())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=t.i(r,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":t.i(i.filename,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(e,t,i){if(!n.t(this.window,this.ctx.config.capturePolicy.errorsPerWindow,this.ctx.diagnostics,`errors`,this.ctx.config.capturePolicy.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.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<this.ctx.config.capturePolicy.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.ctx.config.capturePolicy.maxErrorSignatures>0&&this.seen.size>this.ctx.config.capturePolicy.maxErrorSignatures){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,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
|
|
3
|
-
//# sourceMappingURL=errors-
|
|
3
|
+
//# sourceMappingURL=errors-DCOCRdSi.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-DCOCRdSi.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\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 const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // An event from an element with a URL is a failed resource load, not a script error.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise and a signed URL is a credential, so the record keeps neither\n // unless you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\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.capturePolicy.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.capturePolicy.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.capturePolicy.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 (\n this.ctx.config.capturePolicy.maxErrorSignatures > 0 &&\n this.seen.size > this.ctx.config.capturePolicy.maxErrorSignatures\n ) {\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,oHAgCA,SAASM,EAAY,EAA2B,CAC9C,GAAIN,EAAAA,EAAYO,CAAK,EAAG,CACtB,IAAMC,GAASD,EAAM,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GACpD,MAAO,CAAE,QAASA,EAAM,QAAS,IAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC,GAAQ,CAClF,CAEA,IAAMC,EAAU,OAAOF,CAAK,EAC5B,MAAO,CAAE,UAAS,IAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ,EAAG,CACvD,CAGA,IAAaC,EAAb,KAA6C,CAgBd,IAd7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAK5D,YAAY,EAAsC,CAArB,KA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require("./batch-D5LlU4Q9.cjs"),n=require("./keys-BHhw_0Wh.cjs");function r(e){return Array.isArray(e.records)&&e.records.some(t.r)}var i=class{howMany;isAudit;plain=[];audit=[];constructor(e,t){this.howMany=e,this.isAudit=t}add(e){return this.isAudit(e)?this.audit.length<this.howMany&&this.audit.push(e):this.plain.push(e),this.plain.length<this.howMany}picked(){return[...this.plain,...this.audit].slice(0,this.howMany)}};function a(e,t,n){let r=new i(t,n);for(let t of e)if(!r.add(t))break;return r.picked()}function o(e,t,n,r){return e.batches+=n,e.records+=r,e.reason=t,{batches:n,records:r,reason:t}}function s(e,t,n,r){n.batches!==0&&(e.report(`storage.evicted`,`The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`,{...n}),t?.(n,r))}function c(e,t){let n=t.length,r=Number(e.slice(n,n+14));return Number.isFinite(r)?r:null}var l=class{limits;diagnostics;onGap;prefix;name=e.Rn;constructor(t,n,r,i=e.E){this.limits=t,this.diagnostics=n,this.onGap=r,this.prefix=i}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`))await this.prune();else if(this.evictForQuota(),!this.write(e,`localStorage refused a batch even after evicting`)){let t={batches:1,records:e.records.length,reason:`quota`};s(this.diagnostics,this.onGap,t,[e])}}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}takeContext(e,t){let n=[];for(let r of this.batches()){if(n.length>=t)break;r.routingContextId===e&&n.push(r)}return Promise.resolve(n)}countContext(e){let t=0;for(let n of this.batches())n.routingContextId===e&&t++;return Promise.resolve(t)}*batches(){for(let e of this.keys()){let t=this.read(e);t===null?this.removeKey(e):yield t}}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=[],r=[];for(let t of this.keys()){let i=c(t,this.prefix);i===null||i<e?n.push(t):r.push(t)}this.drop(t,`expired`,[...this.entries(n)]);let i=r.length-this.limits.maxBatches;return i>0&&this.drop(t,`over_capacity`,this.evictable(r,i)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(n.t(this.prefix,e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`},n=Math.ceil(e.length/4);this.drop(t,`quota`,this.evictable(e,n))}evictable(e,t){return a(this.entries(e),t,e=>e.batch!==null&&r(e.batch))}*entries(e){for(let t of e)yield{key:t,batch:this.read(t)}}drop(e,n,r){if(r.length===0)return;let i=[];for(let{key:e,batch:t}of r)this.removeKey(e),t&&i.push(t);let a=o(e,n,r.length,t.n(i));s(this.diagnostics,this.onGap,a,i)}read(e){let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!n)return null;let r=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(n));return r===void 0?null:t.i(r)?r:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return n.n(this.prefix,this.diagnostics)}},u=class{limits;onGap;name=e.zn;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){let t=this.batches.findIndex(t=>t.id===e.id);t>=0?this.batches[t]=e:this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}takeContext(e,t){return Promise.resolve(this.batches.filter(t=>t.routingContextId===e).slice(0,t))}countContext(e){return Promise.resolve(this.batches.filter(t=>t.routingContextId===e).length)}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),this.report(t,`expired`,n);let i=this.batches.length-this.limits.maxBatches;if(i>0){let e=a(this.batches,i,r);this.batches=this.batches.filter(t=>!e.includes(t)),this.report(t,`over_capacity`,e)}return Promise.resolve(t)}report(e,n,r){if(r.length===0)return;let i=o(e,n,r.length,t.n(r));this.onGap?.(i,r)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}};function d(t){return t?`${e.Pn}:${t}`:e.Pn}var f=t=>({name:e.Bn,save:e=>(t?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),Promise.resolve()),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()});function p(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function m(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e.Vn,`1`),localStorage.removeItem(e.Vn),!0))===!0}async function h(e,t,n,r,i,a=``){if(e===`none`)return f(i);if(e===`memory`)return new u(n,i);if(e===`indexeddb`||e===`auto`){if(p(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-CtLvZH1r.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new u(n,i)}return m(r)?new l(n,r,i,a?`ui-observability:namespaced:${encodeURIComponent(a)}:batch:`:void 0):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new u(n,i))}exports.createStorage=h,exports.i=r,exports.n=s,exports.r=i,exports.storageName=d,exports.t=o;
|
|
2
|
+
//# sourceMappingURL=factory-DLFDjdLv.cjs.map
|