@utk09/ui-observability 0.10.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 +77 -1
- package/README.md +323 -113
- package/bin/uiobs.mjs +1 -1
- package/dist/{batch-BMdT9mKm.js → batch-BjQUwjA6.js} +5 -6
- package/dist/batch-BjQUwjA6.js.map +1 -0
- package/dist/{batch-BHXypM1j.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-DKfBaica.js → bus-ecxUNTja.js} +105 -109
- 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-CLz_PvFn.cjs +2 -0
- package/dist/console-CLz_PvFn.cjs.map +1 -0
- package/dist/{console-BX_0UCV7.js → console-cwgHKXvM.js} +14 -15
- 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-DxZf4Gfh.js → context-storage-BzkoHzkQ.js} +2 -3
- package/dist/context-storage-BzkoHzkQ.js.map +1 -0
- 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-5_PecIl5.js → deadline-C4ccAuk5.js} +4 -9
- 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-CZZ6SQQh.js → debug-bundle-BOdYmCeV.js} +12 -6
- 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 +148 -54
- package/dist/doctor.js.map +1 -1
- package/dist/{emergency-queue-Cs8-i2xw.js → emergency-queue-B9WZxanZ.js} +15 -17
- package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
- package/dist/{emergency-queue-CQ-9acZf.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
- package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
- package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
- package/dist/error-like-B11pB4aL.js.map +1 -0
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-oyxrpHjY.js → errors-D6bwgJtO.js} +5 -6
- package/dist/errors-D6bwgJtO.js.map +1 -0
- package/dist/{errors-CigX45pL.cjs → errors-DCOCRdSi.cjs} +2 -2
- package/dist/errors-DCOCRdSi.cjs.map +1 -0
- package/dist/{factory-BkjNzPYL.cjs → factory-DLFDjdLv.cjs} +2 -2
- package/dist/factory-DLFDjdLv.cjs.map +1 -0
- package/dist/{factory-Bgsky_e0.js → factory-e9Qo3K0z.js} +18 -22
- package/dist/factory-e9Qo3K0z.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
- package/dist/{fixed-window-CtaFHanJ.js → fixed-window-Dq3MLUUv.js} +2 -3
- package/dist/fixed-window-Dq3MLUUv.js.map +1 -0
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/{global-scope-dp2jADRl.js → global-scope-D9I8s-oN.js} +2 -3
- package/dist/global-scope-D9I8s-oN.js.map +1 -0
- package/dist/{guards-CpvOpJL6.js → guards-Cidk71ME.js} +2 -3
- package/dist/guards-Cidk71ME.js.map +1 -0
- package/dist/guards-nJ70syPt.cjs.map +1 -1
- package/dist/{identity-BMlKGHUM.cjs → identity-BlvlgjrU.cjs} +2 -2
- package/dist/identity-BlvlgjrU.cjs.map +1 -0
- package/dist/{identity-DOaHdfhT.js → identity-BrQp_5J5.js} +20 -21
- 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 +797 -659
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CaXGJqDD.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
- package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
- package/dist/{indexeddb-storage-D-lUW_5P.js → indexeddb-storage-DLXQzAGh.js} +5 -6
- package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
- package/dist/{interactions-CqDNrtIR.js → interactions-B6z2I4tU.js} +10 -11
- package/dist/interactions-B6z2I4tU.js.map +1 -0
- package/dist/{interactions-8DgxtmgO.cjs → interactions-P6pz08Jn.cjs} +2 -2
- package/dist/interactions-P6pz08Jn.cjs.map +1 -0
- package/dist/{journey-DgIjhrIc.js → journey-35yCMNFo.js} +21 -21
- 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-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
- package/dist/keys-BU9j5YqW.js.map +1 -0
- package/dist/{library-console-g_VU-wzP.cjs → library-console-BFWEuQsl.cjs} +2 -2
- package/dist/library-console-BFWEuQsl.cjs.map +1 -0
- package/dist/library-console-Dl_Ly6DQ.js +13 -0
- package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
- package/dist/{library-request-FQaiWjCP.cjs → library-request-Da-CHKzT.cjs} +2 -2
- package/dist/library-request-Da-CHKzT.cjs.map +1 -0
- package/dist/{library-request-CyC-9IOk.js → library-request-nI6pvI6I.js} +4 -5
- package/dist/library-request-nI6pvI6I.js.map +1 -0
- package/dist/{lifecycle-C2z_d8OX.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
- package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
- package/dist/{lifecycle-BLC4VU7c.js → lifecycle-CZ6RRXc6.js} +3 -4
- package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
- package/dist/{log-record-DKvo-B-d.cjs → log-record-D7bA1RPb.cjs} +2 -2
- package/dist/log-record-D7bA1RPb.cjs.map +1 -0
- package/dist/{log-record-CndanC-p.js → log-record-DIA6McNr.js} +3 -4
- package/dist/log-record-DIA6McNr.js.map +1 -0
- package/dist/{long-frames-BQef9rXR.js → long-frames-430_85Da.js} +9 -8
- 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-CvkvYzRU.js → network-C7SkLf4v.js} +30 -32
- package/dist/network-C7SkLf4v.js.map +1 -0
- package/dist/{network-CqnQOqon.cjs → network-pEX3PAJv.cjs} +2 -2
- package/dist/network-pEX3PAJv.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js +7 -0
- package/dist/openfin-Bxelt0yg.js.map +1 -0
- 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-CYIL7MOE.js → otlp-COq033e3.js} +26 -35
- package/dist/otlp-COq033e3.js.map +1 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -1
- package/dist/{patch-CCWfuEY7.js → patch-UdPz1ea8.js} +2 -3
- package/dist/patch-UdPz1ea8.js.map +1 -0
- package/dist/{platform-KMWkoI-v.cjs → platform-12uR7kBQ.cjs} +2 -2
- package/dist/platform-12uR7kBQ.cjs.map +1 -0
- package/dist/{platform-wcAkkv9F.js → platform-CVewe4wQ.js} +9 -10
- 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-CH_7PphT.js → remote-rules-BJGDJGwA.js} +29 -30
- package/dist/remote-rules-BJGDJGwA.js.map +1 -0
- package/dist/{remote-rules-BL8km4xk.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-Bh_-KpZ2.cjs → reports-BsbqmP8h.cjs} +2 -2
- package/dist/reports-BsbqmP8h.cjs.map +1 -0
- package/dist/{reports-BOKyY3_A.js → reports-BuXekPOS.js} +4 -5
- package/dist/reports-BuXekPOS.js.map +1 -0
- package/dist/{resource-timing-BROnEJ0E.js → resource-timing-CXGHwFRD.js} +6 -7
- package/dist/resource-timing-CXGHwFRD.js.map +1 -0
- package/dist/{resource-timing-CbgwNpog.cjs → resource-timing-DkycFGDa.cjs} +2 -2
- package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
- package/dist/{sampling-ECGVYiDD.cjs → sampling-Dd0wllyq.cjs} +2 -2
- package/dist/sampling-Dd0wllyq.cjs.map +1 -0
- package/dist/{sampling-BLO_pcV4.js → sampling-UUDbi3K0.js} +11 -12
- package/dist/sampling-UUDbi3K0.js.map +1 -0
- package/dist/{sanitize-DS0G4_ea.js → sanitize-CNmsD9r3.js} +4 -5
- package/dist/sanitize-CNmsD9r3.js.map +1 -0
- package/dist/{sanitize-Bsn8HQWC.cjs → sanitize-ChLn97Ch.cjs} +2 -2
- package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
- package/dist/{select-DWO0-w8_.cjs → select-CTk-K5mG.cjs} +3 -3
- package/dist/select-CTk-K5mG.cjs.map +1 -0
- package/dist/{select-wqt9Wxio.js → select-DPv_j6wq.js} +64 -67
- package/dist/select-DPv_j6wq.js.map +1 -0
- package/dist/{sender-BkAVt-Rq.js → sender-15zEsZpr.js} +98 -101
- 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-w7Tslvlq.js → storage-DZwed89z.js} +2 -3
- package/dist/storage-DZwed89z.js.map +1 -0
- package/dist/{storm-DD4cUkoL.js → storm-BTSNTIWI.js} +4 -5
- package/dist/storm-BTSNTIWI.js.map +1 -0
- package/dist/{storm-DCEsqViG.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-BR9t_w28.js → types-BAerHgCq.js} +2 -3
- package/dist/types-BAerHgCq.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-CwdpbUDg.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
- package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
- package/dist/{unclean-exit-BYZ5yaSI.js → unclean-exit-Cob_jyTv.js} +3 -4
- 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-Di2ra5DB.js → user-timing-DgHubxCI.js} +7 -6
- 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-DwBNhgre.cjs → web-socket-BTuvYoJI.cjs} +2 -2
- package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
- package/dist/{web-socket-B-5qqPy7.js → web-socket-DthJuSAg.js} +14 -15
- 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-0HMf4-kY.js → worker-protocol-B0_8rWy5.js} +6 -7
- package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
- package/dist/{worker-protocol-DXekoADQ.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-CKcmX5m5.js → worker-server-Cne9MX9I.js} +25 -26
- package/dist/{worker-server-CKcmX5m5.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-2220ghFZ.js → worker-transport-C3SjJAEC.js} +64 -65
- package/dist/worker-transport-C3SjJAEC.js.map +1 -0
- package/package.json +33 -41
- package/dist/batch-BHXypM1j.cjs.map +0 -1
- package/dist/batch-BMdT9mKm.js.map +0 -1
- package/dist/bus-DKfBaica.js.map +0 -1
- package/dist/bus-Dea9rVhy.cjs +0 -2
- package/dist/bus-Dea9rVhy.cjs.map +0 -1
- package/dist/console-BX_0UCV7.js.map +0 -1
- package/dist/console-DZEcs7FL.cjs +0 -2
- package/dist/console-DZEcs7FL.cjs.map +0 -1
- package/dist/constants-CL0ZdI2f.cjs +0 -2
- package/dist/constants-CL0ZdI2f.cjs.map +0 -1
- package/dist/constants-CU60FG4w.js +0 -305
- package/dist/constants-CU60FG4w.js.map +0 -1
- package/dist/context-storage-DxZf4Gfh.js.map +0 -1
- package/dist/deadline-5_PecIl5.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/debug-bundle-CZZ6SQQh.js.map +0 -1
- package/dist/debug-bundle-yRkrU1ny.cjs +0 -2
- package/dist/debug-bundle-yRkrU1ny.cjs.map +0 -1
- package/dist/emergency-queue-CQ-9acZf.cjs.map +0 -1
- package/dist/emergency-queue-Cs8-i2xw.js.map +0 -1
- package/dist/error-like-Ywo5uRHo.js.map +0 -1
- package/dist/errors-CigX45pL.cjs.map +0 -1
- package/dist/errors-oyxrpHjY.js.map +0 -1
- package/dist/factory-Bgsky_e0.js.map +0 -1
- package/dist/factory-BkjNzPYL.cjs.map +0 -1
- package/dist/fixed-window-CtaFHanJ.js.map +0 -1
- package/dist/global-scope-dp2jADRl.js.map +0 -1
- package/dist/guards-CpvOpJL6.js.map +0 -1
- package/dist/identity-BMlKGHUM.cjs.map +0 -1
- package/dist/identity-DOaHdfhT.js.map +0 -1
- package/dist/indexeddb-storage-CaXGJqDD.cjs.map +0 -1
- package/dist/indexeddb-storage-D-lUW_5P.js.map +0 -1
- package/dist/interactions-8DgxtmgO.cjs.map +0 -1
- package/dist/interactions-CqDNrtIR.js.map +0 -1
- package/dist/journey-5tcxEbnG.cjs +0 -2
- package/dist/journey-5tcxEbnG.cjs.map +0 -1
- package/dist/journey-DgIjhrIc.js.map +0 -1
- package/dist/keys-D5r_GH9q.js.map +0 -1
- package/dist/library-console-CabK2j2-.js +0 -14
- package/dist/library-console-CabK2j2-.js.map +0 -1
- package/dist/library-console-g_VU-wzP.cjs.map +0 -1
- package/dist/library-request-CyC-9IOk.js.map +0 -1
- package/dist/library-request-FQaiWjCP.cjs.map +0 -1
- package/dist/lifecycle-BLC4VU7c.js.map +0 -1
- package/dist/lifecycle-C2z_d8OX.cjs.map +0 -1
- package/dist/log-record-CndanC-p.js.map +0 -1
- package/dist/log-record-DKvo-B-d.cjs.map +0 -1
- package/dist/long-frames-BQef9rXR.js.map +0 -1
- package/dist/long-frames-CV5ZG2cx.cjs +0 -2
- package/dist/long-frames-CV5ZG2cx.cjs.map +0 -1
- package/dist/network-CqnQOqon.cjs.map +0 -1
- package/dist/network-CvkvYzRU.js.map +0 -1
- package/dist/openfin-BwEN0uj4.js +0 -8
- package/dist/openfin-BwEN0uj4.js.map +0 -1
- package/dist/otlp-CYIL7MOE.js.map +0 -1
- package/dist/otlp-RVbkNQRh.cjs +0 -2
- package/dist/otlp-RVbkNQRh.cjs.map +0 -1
- package/dist/patch-CCWfuEY7.js.map +0 -1
- package/dist/platform-KMWkoI-v.cjs.map +0 -1
- package/dist/platform-wcAkkv9F.js.map +0 -1
- package/dist/remote-rules-BL8km4xk.cjs.map +0 -1
- package/dist/remote-rules-CH_7PphT.js.map +0 -1
- package/dist/reports-BOKyY3_A.js.map +0 -1
- package/dist/reports-Bh_-KpZ2.cjs.map +0 -1
- package/dist/resource-timing-BROnEJ0E.js.map +0 -1
- package/dist/resource-timing-CbgwNpog.cjs.map +0 -1
- package/dist/sampling-BLO_pcV4.js.map +0 -1
- package/dist/sampling-ECGVYiDD.cjs.map +0 -1
- package/dist/sanitize-Bsn8HQWC.cjs.map +0 -1
- package/dist/sanitize-DS0G4_ea.js.map +0 -1
- package/dist/select-DWO0-w8_.cjs.map +0 -1
- package/dist/select-wqt9Wxio.js.map +0 -1
- package/dist/sender-BkAVt-Rq.js.map +0 -1
- package/dist/sender-D82PxlCY.cjs +0 -2
- package/dist/sender-D82PxlCY.cjs.map +0 -1
- package/dist/storage-w7Tslvlq.js.map +0 -1
- package/dist/storm-DCEsqViG.cjs.map +0 -1
- package/dist/storm-DD4cUkoL.js.map +0 -1
- package/dist/types-BR9t_w28.js.map +0 -1
- package/dist/unclean-exit-BYZ5yaSI.js.map +0 -1
- package/dist/unclean-exit-CwdpbUDg.cjs.map +0 -1
- package/dist/user-timing-C1kB3JEg.cjs +0 -2
- package/dist/user-timing-C1kB3JEg.cjs.map +0 -1
- package/dist/user-timing-Di2ra5DB.js.map +0 -1
- package/dist/web-socket-B-5qqPy7.js.map +0 -1
- package/dist/web-socket-DwBNhgre.cjs.map +0 -1
- package/dist/web-vitals-Bflr5jSA.js +0 -53
- package/dist/web-vitals-Bflr5jSA.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-0HMf4-kY.js.map +0 -1
- package/dist/worker-protocol-DXekoADQ.cjs.map +0 -1
- package/dist/worker-server-BQK5z2yl.cjs +0 -2
- package/dist/worker-server-BQK5z2yl.cjs.map +0 -1
- package/dist/worker-transport-2220ghFZ.js.map +0 -1
- package/dist/worker-transport-Dj2yCQN5.cjs +0 -2
- package/dist/worker-transport-Dj2yCQN5.cjs.map +0 -1
|
@@ -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,CA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I,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAIA,IAAMC,EAASN,IAAU,IAAA,GAAgB,MAAMT,CAAO,EAAIS,EAC1D,KAAK,IAAI,OAAO,MAAMT,IAAY,GAAKgB,EAAShB,EAASe,EAAQ,CAC/D,GAAGE,EACH,oBAAqBD,EACrB,yBAA0BH,CAC5B,CAAC,CACH,CACF,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=factory-
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs"),t=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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory-DLFDjdLv.cjs","names":["isActionRecord","STORAGE_NAME_LOCAL","BATCH_STORAGE_KEY_PREFIX","batchKey","countRecords","isLogBatch","keysWithPrefix","STORAGE_NAME_MEMORY","countRecords","STORAGE_DB_NAME","STORAGE_NAME_NONE","STORAGE_PROBE_KEY","require_constants","require_batch","require_keys","hasAction","batch","EvictionPick","howMany","isAudit","item","pickEvictable","pick","items","addDrop","batches","records","reason","reportEviction","gap","diagnostics","onGap","dropped","createdAtOf","start","prefix","at","key","LocalStorageStorage","limits","out","limit","id","count","attempts","cutoff","result","expired","alive","createdAt","excess","context","keys","entry","entries","raw","parsed","MemoryStorage","index","stored","found","evicted","storageName","namespace","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","storage","IndexedDbStorage","dbName"],"sources":["../src/storage/eviction.ts","../src/storage/gap.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts"],"sourcesContent":["// src/storage/eviction.ts\n//\n// Picks which stored batches to evict. An action is an audit fact, so batches without one go\n// first. The walk stops early, because reading the whole store on every save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Checks whether a batch holds an action. Eviction removes such a batch last.\n * @param batch The batch to check.\n * @returns True if any record in the batch is an action.\n */\nexport function hasAction(batch: LogBatch): boolean {\n // Another script on the origin can write to the database. A throw in a cursor handler would\n // stop the eviction walk, and the walk would never settle.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from an oldest-first walk. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** The oldest items with an audit fact. Only used when there aren't enough plain items. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n */\n constructor(\n private readonly howMany: number,\n private readonly isAudit: (item: T) => boolean,\n ) {}\n\n /**\n * Adds the next item of the walk.\n * @param item The next oldest item.\n * @returns False once the pick has enough items without an audit fact, which stops the walk.\n */\n add(item: T): boolean {\n if (!this.isAudit(item)) {\n this.plain.push(item);\n } else if (this.audit.length < this.howMany) {\n this.audit.push(item);\n }\n\n return this.plain.length < this.howMany;\n }\n\n /**\n * Returns the items to evict, with the ones without an audit fact first.\n * @returns The picked items.\n */\n picked(): T[] {\n return [...this.plain, ...this.audit].slice(0, this.howMany);\n }\n}\n\n/**\n * Picks the items to evict from an oldest-first walk, and stops the walk early.\n * @param items Items, oldest first. A generator reads each item only when the walk needs it.\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n * @returns The picked items, with the ones without an audit fact first.\n */\nexport function pickEvictable<T>(\n items: Iterable<T>,\n howMany: number,\n isAudit: (item: T) => boolean,\n): T[] {\n const pick = new EvictionPick(howMany, isAudit);\n\n for (const item of items) {\n if (!pick.add(item)) {\n break;\n }\n }\n\n return pick.picked();\n}\n","// src/storage/gap.ts\n//\n// Counts and reports the batches a storage adapter drops. Every dropped batch is a loss, and\n// the gap handler passes it on to onDrop.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult } from \"../models/storage\";\n\n/**\n * Adds one rule's drop to the prune result.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts for this rule alone, for the gap report.\n */\nexport function addDrop(\n result: PruneResult,\n reason: PruneResult[\"reason\"],\n batches: number,\n records: number,\n): PruneResult {\n result.batches += batches;\n result.records += records;\n result.reason = reason;\n return { batches, records, reason };\n}\n\n/**\n * Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.\n * @param diagnostics Diagnostics reporter.\n * @param onGap The adapter's gap handler.\n * @param gap The drop's counts and reason.\n * @param dropped The dropped batches that the adapter could read.\n */\nexport function reportEviction(\n diagnostics: Diagnostics,\n onGap: GapReporter | undefined,\n gap: PruneResult,\n dropped: readonly LogBatch[],\n): void {\n if (gap.batches === 0) {\n return;\n }\n\n diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(gap.batches)} stored batches (${String(gap.records)} records).`,\n { ...gap },\n );\n onGap?.(gap, dropped);\n}\n","// src/storage/local-storage.ts\n//\n// Stores batches in localStorage under time-ordered keys. The padding makes keys().sort() a\n// sort by creation time. Without it the sort would compare the decimal times as text, so \"10\"\n// sorts before \"9\", and take() would not return the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/** A stored entry. A corrupt entry has no batch. */\ninterface Entry {\n key: string;\n batch: LogBatch | null;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after every save, and reading the\n * time from the batch would parse the whole store each time.\n * @param key The prefixed storage key.\n * @param prefix The storage key prefix.\n * @returns Creation time in epoch milliseconds, or null for a malformed key.\n */\nfunction createdAtOf(key: string, prefix: string): number | null {\n const start = prefix.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** StorageAdapter that keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n private readonly prefix = BATCH_STORAGE_KEY_PREFIX,\n ) {}\n\n /**\n * Writes a batch to localStorage, removing the oldest entries on a quota error.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // A corrupt entry can't be recovered. Remove it without a gap count, because it has no\n // readable record count.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them. Stops\n * at the limit, so later entries are never parsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const batch of this.batches()) {\n if (out.length >= limit) {\n break;\n }\n if (batch.routingContextId === id) {\n out.push(batch);\n }\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Counts one context's stored batches. The context id isn't in the key, so every entry is\n * read.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n let count = 0;\n\n for (const batch of this.batches()) {\n if (batch.routingContextId === id) {\n count++;\n }\n }\n\n return Promise.resolve(count);\n }\n\n /**\n * Reads the valid batches one at a time, oldest first, and removes any corrupt entry.\n * @yields Each valid batch.\n */\n private *batches(): Generator<LogBatch> {\n for (const key of this.keys()) {\n const batch = this.read(key);\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n yield batch;\n }\n }\n\n /**\n * Deletes the batch with the given ID from localStorage.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count. The key doesn't change.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const expired: string[] = [];\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key, this.prefix);\n // A key with no readable time has no place in the sort order either.\n if (createdAt === null || createdAt < cutoff) {\n expired.push(key);\n continue;\n }\n alive.push(key);\n }\n\n // The record count is the one field the key doesn't hold, so parse only the deleted batches.\n this.drop(result, \"expired\", [...this.entries(expired)]);\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n this.drop(result, \"over_capacity\", this.evictable(alive, excess));\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys without deserializing the batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes every batch key from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** Does nothing. localStorage has no connection to close. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch The batch to store.\n * @param context The text diagnostics reports if the write fails.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(batchKey(this.prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Removes a quarter of the store to free quota, and counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n const howMany = Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR);\n\n this.drop(result, \"quota\", this.evictable(keys, howMany));\n }\n\n /**\n * Picks the entries to evict. Entries without an action go first, because an action is an\n * audit fact. A corrupt entry has no action, so it goes first too.\n * @param keys Batch keys, oldest first.\n * @param howMany Number of entries to evict.\n * @returns The picked entries.\n */\n private evictable(keys: string[], howMany: number): Entry[] {\n return pickEvictable(\n this.entries(keys),\n howMany,\n (entry) => entry.batch !== null && hasAction(entry.batch),\n );\n }\n\n /**\n * Reads the entries one at a time. The eviction walk stops early, so later entries are\n * never parsed.\n * @param keys Batch keys.\n * @yields Each key with its batch.\n */\n private *entries(keys: string[]): Generator<Entry> {\n for (const key of keys) {\n yield { key, batch: this.read(key) };\n }\n }\n\n /**\n * Removes entries and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that removes the entries.\n * @param entries The entries to remove.\n */\n private drop(result: PruneResult, reason: PruneResult[\"reason\"], entries: Entry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const dropped: LogBatch[] = [];\n\n for (const { key, batch } of entries) {\n this.removeKey(key);\n if (batch) {\n dropped.push(batch);\n }\n }\n\n // A corrupt entry counts as a batch with no records.\n const gap = addDrop(result, reason, entries.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Reads and validates the stored batch at a key.\n * @param key The storage key to read.\n * @returns The validated LogBatch, or null if it is missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read a stored batch.\",\n () => localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"A stored batch is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report would count one\n // corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\n * @param id Batch identifier.\n * @returns The matching storage key, or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes a list of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns every batch storage key, sorted.\n * @returns The sorted storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// Keeps batches in volatile memory during offline periods, so a reload loses all of them.\n// This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop } from \"./gap\";\n\n/** StorageAdapter that keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** The batches, in FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch and applies retention pruning.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n // A batch with a known id replaces the old copy in place, as IndexedDB put() does.\n const index = this.batches.findIndex((stored) => stored.id === batch.id);\n if (index >= 0) {\n this.batches[index] = batch;\n } else {\n this.batches.push(batch);\n }\n await this.prune();\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return Promise.resolve(\n this.batches.filter((batch) => batch.routingContextId === id).slice(0, limit),\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n return Promise.resolve(this.batches.filter((batch) => batch.routingContextId === id).length);\n }\n\n /**\n * Deletes the batch with the given ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n this.report(result, \"expired\", expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n // An action is an audit fact, so evict the batches without one first.\n const evicted = pickEvictable(this.batches, excess, hasAction);\n this.batches = this.batches.filter((batch) => !evicted.includes(batch));\n this.report(result, \"over_capacity\", evicted);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private report(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n if (dropped.length === 0) {\n return;\n }\n\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n this.onGap?.(gap, dropped);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Deletes every stored batch. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Deletes every stored batch when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Picks a storage adapter, falling back from IndexedDB to localStorage to memory instead of\n// throwing. IndexedDB is unavailable in private mode and in sandboxed frames.\n\nimport {\n STORAGE_DB_NAME,\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * Returns the database name for one application namespace. The sender and the deletion both\n * use this one rule.\n * @param namespace Application namespace. An empty value keeps the name used before namespaces.\n * @returns The IndexedDB database name.\n */\nexport function storageName(namespace: string): string {\n return namespace ? `${STORAGE_DB_NAME}:${namespace}` : STORAGE_DB_NAME;\n}\n\n/**\n * Builds the adapter that keeps nothing, returned for the \"none\" strategy. Every method\n * resolves, so a sender that calls close() on shutdown doesn't crash.\n * @param onGap Receives every batch the adapter doesn't keep. Each one is a loss.\n * @returns The adapter.\n */\nconst noop = (onGap?: GapReporter): StorageAdapter => ({\n name: STORAGE_NAME_NONE,\n save: (batch) => {\n onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return Promise.resolve();\n },\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n});\n\n/**\n * Checks whether IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks whether localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if a probe write to localStorage succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter, falling back to the next one when a dependency is\n * unavailable.\n * @param strategy The configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns A promise that resolves to the selected StorageAdapter.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n namespace = \"\",\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop(onGap);\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // The dynamic import keeps the driver out of the main bundle. If the chunk fails to\n // load, we fall back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here rather than on first use. Private mode, a corrupt profile\n // and some WebViews define indexedDB but reject open(), and only a rejection in\n // this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB is not available. The library uses memory storage instead.\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(\n limits,\n diagnostics,\n onGap,\n namespace ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:batch:` : undefined,\n );\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"No persistent storage is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n"],"mappings":"A,+GAYA,SAAgBe,EAAU,EAA0B,CAGlD,OAAO,MAAM,QAAQC,EAAM,OAAO,GAAKA,EAAM,QAAQ,KAAKhB,EAAAA,CAAc,CAC1E,CAGA,IAAaiB,EAAb,KAA6B,CAYR,QACA,QAXnB,MAA8B,CAAC,EAG/B,MAA8B,CAAC,EAM/B,YACE,EACA,EACA,CAFiB,KAAA,QAAAC,EACA,KAAA,QAAAC,CAChB,CAOH,IAAI,EAAkB,CAOpB,OANK,KAAK,QAAQC,CAAI,EAEX,KAAK,MAAM,OAAS,KAAK,SAClC,KAAK,MAAM,KAAKA,CAAI,EAFpB,KAAK,MAAM,KAAKA,CAAI,EAKf,KAAK,MAAM,OAAS,KAAK,OAClC,CAMA,QAAc,CACZ,MAAO,CAAC,GAAG,KAAK,MAAO,GAAG,KAAK,KAAK,CAAC,CAAC,MAAM,EAAG,KAAK,OAAO,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@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as o, n as s, r as c } from "./batch-
|
|
3
|
-
import { n as l, t as u } from "./keys-
|
|
4
|
-
|
|
1
|
+
import { Bn as e, E as t, Pn as n, Rn as r, Vn as i, zn as a } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
import { i as o, n as s, r as c } from "./batch-BjQUwjA6.js";
|
|
3
|
+
import { n as l, t as u } from "./keys-BU9j5YqW.js";
|
|
4
|
+
// src/storage/eviction.ts
|
|
5
5
|
function d(e) {
|
|
6
6
|
return Array.isArray(e.records) && e.records.some(c);
|
|
7
7
|
}
|
|
@@ -25,8 +25,7 @@ function p(e, t, n) {
|
|
|
25
25
|
for (let t of e) if (!r.add(t)) break;
|
|
26
26
|
return r.picked();
|
|
27
27
|
}
|
|
28
|
-
|
|
29
|
-
//#region src/storage/gap.ts
|
|
28
|
+
// src/storage/gap.ts
|
|
30
29
|
function m(e, t, n, r) {
|
|
31
30
|
return e.batches += n, e.records += r, e.reason = t, {
|
|
32
31
|
batches: n,
|
|
@@ -37,8 +36,7 @@ function m(e, t, n, r) {
|
|
|
37
36
|
function h(e, t, n, r) {
|
|
38
37
|
n.batches !== 0 && (e.report("storage.evicted", `The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`, { ...n }), t?.(n, r));
|
|
39
38
|
}
|
|
40
|
-
|
|
41
|
-
//#region src/storage/local-storage.ts
|
|
39
|
+
// src/storage/local-storage.ts
|
|
42
40
|
function g(e, t) {
|
|
43
41
|
let n = t.length, r = Number(e.slice(n, n + 14));
|
|
44
42
|
return Number.isFinite(r) ? r : null;
|
|
@@ -48,7 +46,7 @@ var _ = class {
|
|
|
48
46
|
diagnostics;
|
|
49
47
|
onGap;
|
|
50
48
|
prefix;
|
|
51
|
-
name =
|
|
49
|
+
name = r;
|
|
52
50
|
constructor(e, n, r, i = t) {
|
|
53
51
|
this.limits = e, this.diagnostics = n, this.onGap = r, this.prefix = i;
|
|
54
52
|
}
|
|
@@ -175,7 +173,7 @@ var _ = class {
|
|
|
175
173
|
}, v = class {
|
|
176
174
|
limits;
|
|
177
175
|
onGap;
|
|
178
|
-
name =
|
|
176
|
+
name = a;
|
|
179
177
|
batches = [];
|
|
180
178
|
constructor(e, t) {
|
|
181
179
|
this.limits = e, this.onGap = t;
|
|
@@ -229,18 +227,17 @@ var _ = class {
|
|
|
229
227
|
return this.batches = [], Promise.resolve();
|
|
230
228
|
}
|
|
231
229
|
};
|
|
232
|
-
|
|
233
|
-
//#region src/storage/factory.ts
|
|
230
|
+
// src/storage/factory.ts
|
|
234
231
|
function y(e) {
|
|
235
|
-
return e ? `${
|
|
232
|
+
return e ? `${n}:${e}` : n;
|
|
236
233
|
}
|
|
237
|
-
var b = (
|
|
238
|
-
name:
|
|
239
|
-
save: (
|
|
234
|
+
var b = (t) => ({
|
|
235
|
+
name: e,
|
|
236
|
+
save: (e) => (t?.({
|
|
240
237
|
batches: 1,
|
|
241
|
-
records:
|
|
238
|
+
records: e.records.length,
|
|
242
239
|
reason: "not_stored"
|
|
243
|
-
}, [
|
|
240
|
+
}, [e]), Promise.resolve()),
|
|
244
241
|
take: () => Promise.resolve([]),
|
|
245
242
|
remove: () => Promise.resolve(),
|
|
246
243
|
bumpAttempts: () => Promise.resolve(),
|
|
@@ -257,7 +254,7 @@ function x(e) {
|
|
|
257
254
|
return e.guard("storage.unavailable", "The library could not read indexedDB.", () => globalThis.indexedDB != null) === !0;
|
|
258
255
|
}
|
|
259
256
|
function S(e) {
|
|
260
|
-
return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(
|
|
257
|
+
return e.guard("storage.unavailable", "The library could not write a test key to localStorage.", () => (localStorage.setItem(i, "1"), localStorage.removeItem(i), !0)) === !0;
|
|
261
258
|
}
|
|
262
259
|
async function C(e, t, n, r, i, a = "") {
|
|
263
260
|
if (e === "none") return b(i);
|
|
@@ -265,7 +262,7 @@ async function C(e, t, n, r, i, a = "") {
|
|
|
265
262
|
if (e === "indexeddb" || e === "auto") {
|
|
266
263
|
if (x(r)) {
|
|
267
264
|
let e = await r.guardAsync("storage.unavailable", "The library could not open IndexedDB.", async () => {
|
|
268
|
-
let { IndexedDbStorage: e } = await import("./indexeddb-storage-
|
|
265
|
+
let { IndexedDbStorage: e } = await import("./indexeddb-storage-DLXQzAGh.js"), a = new e(t, n, r, i);
|
|
269
266
|
return await a.open(), a;
|
|
270
267
|
});
|
|
271
268
|
if (e) return e;
|
|
@@ -274,7 +271,6 @@ async function C(e, t, n, r, i, a = "") {
|
|
|
274
271
|
}
|
|
275
272
|
return S(r) ? new _(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 v(n, i));
|
|
276
273
|
}
|
|
277
|
-
//#endregion
|
|
278
274
|
export { C as createStorage, d as i, h as n, f as r, y as storageName, m as t };
|
|
279
275
|
|
|
280
|
-
//# sourceMappingURL=factory-
|
|
276
|
+
//# sourceMappingURL=factory-e9Qo3K0z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory-e9Qo3K0z.js","names":["STORAGE_NAME_NONE","BATCH_STORAGE_KEY_PREFIX","STORAGE_DB_NAME","STORAGE_NAME_LOCAL","STORAGE_PROBE_KEY","STORAGE_NAME_MEMORY","isLogBatch","countRecords","isActionRecord","keysWithPrefix","batchKey","hasAction","batch","EvictionPick","howMany","isAudit","item","pickEvictable","pick","items","addDrop","batches","records","reason","reportEviction","gap","diagnostics","onGap","dropped","createdAtOf","start","prefix","at","key","LocalStorageStorage","limits","out","limit","id","count","attempts","cutoff","result","expired","alive","createdAt","excess","context","keys","entry","entries","raw","parsed","MemoryStorage","index","stored","found","evicted","storageName","namespace","noop","hasIndexedDb","hasLocalStorage","createStorage","strategy","adapter","storage","IndexedDbStorage","dbName"],"sources":["../src/storage/eviction.ts","../src/storage/gap.ts","../src/storage/local-storage.ts","../src/storage/memory-storage.ts","../src/storage/factory.ts"],"sourcesContent":["// src/storage/eviction.ts\n//\n// Picks which stored batches to evict. An action is an audit fact, so batches without one go\n// first. The walk stops early, because reading the whole store on every save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Checks whether a batch holds an action. Eviction removes such a batch last.\n * @param batch The batch to check.\n * @returns True if any record in the batch is an action.\n */\nexport function hasAction(batch: LogBatch): boolean {\n // Another script on the origin can write to the database. A throw in a cursor handler would\n // stop the eviction walk, and the walk would never settle.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from an oldest-first walk. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** The oldest items with an audit fact. Only used when there aren't enough plain items. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n */\n constructor(\n private readonly howMany: number,\n private readonly isAudit: (item: T) => boolean,\n ) {}\n\n /**\n * Adds the next item of the walk.\n * @param item The next oldest item.\n * @returns False once the pick has enough items without an audit fact, which stops the walk.\n */\n add(item: T): boolean {\n if (!this.isAudit(item)) {\n this.plain.push(item);\n } else if (this.audit.length < this.howMany) {\n this.audit.push(item);\n }\n\n return this.plain.length < this.howMany;\n }\n\n /**\n * Returns the items to evict, with the ones without an audit fact first.\n * @returns The picked items.\n */\n picked(): T[] {\n return [...this.plain, ...this.audit].slice(0, this.howMany);\n }\n}\n\n/**\n * Picks the items to evict from an oldest-first walk, and stops the walk early.\n * @param items Items, oldest first. A generator reads each item only when the walk needs it.\n * @param howMany Number of items to evict.\n * @param isAudit Checks whether an item holds an audit fact.\n * @returns The picked items, with the ones without an audit fact first.\n */\nexport function pickEvictable<T>(\n items: Iterable<T>,\n howMany: number,\n isAudit: (item: T) => boolean,\n): T[] {\n const pick = new EvictionPick(howMany, isAudit);\n\n for (const item of items) {\n if (!pick.add(item)) {\n break;\n }\n }\n\n return pick.picked();\n}\n","// src/storage/gap.ts\n//\n// Counts and reports the batches a storage adapter drops. Every dropped batch is a loss, and\n// the gap handler passes it on to onDrop.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult } from \"../models/storage\";\n\n/**\n * Adds one rule's drop to the prune result.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts for this rule alone, for the gap report.\n */\nexport function addDrop(\n result: PruneResult,\n reason: PruneResult[\"reason\"],\n batches: number,\n records: number,\n): PruneResult {\n result.batches += batches;\n result.records += records;\n result.reason = reason;\n return { batches, records, reason };\n}\n\n/**\n * Reports dropped batches to diagnostics and to the gap handler. An empty drop reports nothing.\n * @param diagnostics Diagnostics reporter.\n * @param onGap The adapter's gap handler.\n * @param gap The drop's counts and reason.\n * @param dropped The dropped batches that the adapter could read.\n */\nexport function reportEviction(\n diagnostics: Diagnostics,\n onGap: GapReporter | undefined,\n gap: PruneResult,\n dropped: readonly LogBatch[],\n): void {\n if (gap.batches === 0) {\n return;\n }\n\n diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(gap.batches)} stored batches (${String(gap.records)} records).`,\n { ...gap },\n );\n onGap?.(gap, dropped);\n}\n","// src/storage/local-storage.ts\n//\n// Stores batches in localStorage under time-ordered keys. The padding makes keys().sort() a\n// sort by creation time. Without it the sort would compare the decimal times as text, so \"10\"\n// sorts before \"9\", and take() would not return the oldest batch first.\n\nimport {\n BATCH_KEY_TIME_WIDTH,\n BATCH_STORAGE_KEY_PREFIX,\n QUOTA_EVICTION_DIVISOR,\n STORAGE_NAME_LOCAL,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/** A stored entry. A corrupt entry has no batch. */\ninterface Entry {\n key: string;\n batch: LogBatch | null;\n}\n\n/**\n * Reads the creation time from a storage key. prune() runs after every save, and reading the\n * time from the batch would parse the whole store each time.\n * @param key The prefixed storage key.\n * @param prefix The storage key prefix.\n * @returns Creation time in epoch milliseconds, or null for a malformed key.\n */\nfunction createdAtOf(key: string, prefix: string): number | null {\n const start = prefix.length;\n const at = Number(key.slice(start, start + BATCH_KEY_TIME_WIDTH));\n\n return Number.isFinite(at) ? at : null;\n}\n\n/** StorageAdapter that keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_LOCAL;\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n private readonly prefix = BATCH_STORAGE_KEY_PREFIX,\n ) {}\n\n /**\n * Writes a batch to localStorage, removing the oldest entries on a quota error.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n if (this.write(batch, \"localStorage refused a batch, evicting the oldest\")) {\n await this.prune();\n return;\n }\n\n this.evictForQuota();\n\n // The eviction made room for this batch, so write it again. Without the second write,\n // save() resolves, the batch is lost and no counter shows it.\n if (!this.write(batch, \"localStorage refused a batch even after evicting\")) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the valid batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const key of this.keys().slice(0, limit)) {\n const batch = this.read(key);\n // A corrupt entry can't be recovered. Remove it without a gap count, because it has no\n // readable record count.\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n out.push(batch);\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them. Stops\n * at the limit, so later entries are never parsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const out: LogBatch[] = [];\n\n for (const batch of this.batches()) {\n if (out.length >= limit) {\n break;\n }\n if (batch.routingContextId === id) {\n out.push(batch);\n }\n }\n\n return Promise.resolve(out);\n }\n\n /**\n * Counts one context's stored batches. The context id isn't in the key, so every entry is\n * read.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n let count = 0;\n\n for (const batch of this.batches()) {\n if (batch.routingContextId === id) {\n count++;\n }\n }\n\n return Promise.resolve(count);\n }\n\n /**\n * Reads the valid batches one at a time, oldest first, and removes any corrupt entry.\n * @yields Each valid batch.\n */\n private *batches(): Generator<LogBatch> {\n for (const key of this.keys()) {\n const batch = this.read(key);\n if (batch === null) {\n this.removeKey(key);\n continue;\n }\n yield batch;\n }\n }\n\n /**\n * Deletes the batch with the given ID from localStorage.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n const key = this.keyOf(id);\n if (key !== null) {\n this.removeKey(key);\n }\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count. The key doesn't change.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const key = this.keyOf(id);\n if (key === null) {\n return Promise.resolve();\n }\n\n const batch = this.read(key);\n if (batch === null) {\n return Promise.resolve();\n }\n\n batch.attempts = attempts;\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => {\n localStorage.setItem(key, JSON.stringify(batch));\n },\n );\n\n return Promise.resolve();\n }\n\n /**\n * Deletes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n const expired: string[] = [];\n const alive: string[] = [];\n\n for (const key of this.keys()) {\n const createdAt = createdAtOf(key, this.prefix);\n // A key with no readable time has no place in the sort order either.\n if (createdAt === null || createdAt < cutoff) {\n expired.push(key);\n continue;\n }\n alive.push(key);\n }\n\n // The record count is the one field the key doesn't hold, so parse only the deleted batches.\n this.drop(result, \"expired\", [...this.entries(expired)]);\n\n const excess = alive.length - this.limits.maxBatches;\n if (excess > 0) {\n this.drop(result, \"over_capacity\", this.evictable(alive, excess));\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Returns the number of stored batch keys without deserializing the batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** Deletes every batch key from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** Does nothing. localStorage has no connection to close. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Writes a batch to localStorage.\n * @param batch The batch to store.\n * @param context The text diagnostics reports if the write fails.\n * @returns True if the write succeeded.\n */\n private write(batch: LogBatch, context: string): boolean {\n const written = this.diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n localStorage.setItem(batchKey(this.prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n return written === true;\n }\n\n /** Removes a quarter of the store to free quota, and counts the loss. */\n private evictForQuota(): void {\n const keys = this.keys();\n const result: PruneResult = { batches: 0, records: 0, reason: \"quota\" };\n const howMany = Math.ceil(keys.length / QUOTA_EVICTION_DIVISOR);\n\n this.drop(result, \"quota\", this.evictable(keys, howMany));\n }\n\n /**\n * Picks the entries to evict. Entries without an action go first, because an action is an\n * audit fact. A corrupt entry has no action, so it goes first too.\n * @param keys Batch keys, oldest first.\n * @param howMany Number of entries to evict.\n * @returns The picked entries.\n */\n private evictable(keys: string[], howMany: number): Entry[] {\n return pickEvictable(\n this.entries(keys),\n howMany,\n (entry) => entry.batch !== null && hasAction(entry.batch),\n );\n }\n\n /**\n * Reads the entries one at a time. The eviction walk stops early, so later entries are\n * never parsed.\n * @param keys Batch keys.\n * @yields Each key with its batch.\n */\n private *entries(keys: string[]): Generator<Entry> {\n for (const key of keys) {\n yield { key, batch: this.read(key) };\n }\n }\n\n /**\n * Removes entries and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that removes the entries.\n * @param entries The entries to remove.\n */\n private drop(result: PruneResult, reason: PruneResult[\"reason\"], entries: Entry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const dropped: LogBatch[] = [];\n\n for (const { key, batch } of entries) {\n this.removeKey(key);\n if (batch) {\n dropped.push(batch);\n }\n }\n\n // A corrupt entry counts as a batch with no records.\n const gap = addDrop(result, reason, entries.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Reads and validates the stored batch at a key.\n * @param key The storage key to read.\n * @returns The validated LogBatch, or null if it is missing or malformed.\n */\n private read(key: string): LogBatch | null {\n const raw = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read a stored batch.\",\n () => localStorage.getItem(key),\n );\n if (!raw) {\n return null;\n }\n\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"A stored batch is corrupt. The library removed it.\",\n () => JSON.parse(raw) as unknown,\n );\n // The guard above already reported a parse failure. A second report would count one\n // corrupt entry twice.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n this.diagnostics.report(\n \"storage.degraded\",\n \"A stored entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n }\n\n /**\n * Finds the storage key that ends with the batch ID.\n * @param id Batch identifier.\n * @returns The matching storage key, or null.\n */\n private keyOf(id: string): string | null {\n return this.keys().find((key) => key.endsWith(`.${id}`)) ?? null;\n }\n\n /**\n * Deletes a list of storage keys.\n * @param keys Keys to delete.\n */\n private evict(keys: string[]): void {\n for (const key of keys) {\n this.removeKey(key);\n }\n }\n\n /**\n * Deletes one storage key inside a guard.\n * @param key Storage key to remove.\n */\n private removeKey(key: string): void {\n this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not remove a stored batch.\",\n () => {\n localStorage.removeItem(key);\n },\n );\n }\n\n /**\n * Returns every batch storage key, sorted.\n * @returns The sorted storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// Keeps batches in volatile memory during offline periods, so a reload loses all of them.\n// This adapter is the last fallback.\n\nimport { STORAGE_NAME_MEMORY } from \"../constants\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { hasAction, pickEvictable } from \"./eviction\";\nimport { addDrop } from \"./gap\";\n\n/** StorageAdapter that keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** The storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** The batches, in FIFO order. */\n private batches: LogBatch[] = [];\n\n /**\n * @param limits Storage capacity and retention thresholds.\n * @param onGap Optional callback for reporting dropped records.\n */\n constructor(\n private readonly limits: StorageLimits,\n private readonly onGap?: GapReporter,\n ) {}\n\n /**\n * Appends a batch and applies retention pruning.\n * @param batch The batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n // A batch with a known id replaces the old copy in place, as IndexedDB put() does.\n const index = this.batches.findIndex((stored) => stored.id === batch.id);\n if (index >= 0) {\n this.batches[index] = batch;\n } else {\n this.batches.push(batch);\n }\n await this.prune();\n }\n\n /**\n * Returns up to `limit` batches in FIFO order without deleting them.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to the batches.\n */\n take(limit: number): Promise<LogBatch[]> {\n return Promise.resolve(this.batches.slice(0, limit));\n }\n\n /**\n * Returns up to `limit` batches of one context in FIFO order without deleting them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns A promise that resolves to this context's batches.\n */\n takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return Promise.resolve(\n this.batches.filter((batch) => batch.routingContextId === id).slice(0, limit),\n );\n }\n\n /**\n * Counts one context's stored batches.\n * @param id Delivery context id.\n * @returns A promise that resolves to this context's batch count.\n */\n countContext(id: string): Promise<number> {\n return Promise.resolve(this.batches.filter((batch) => batch.routingContextId === id).length);\n }\n\n /**\n * Deletes the batch with the given ID.\n * @param id Batch identifier.\n */\n remove(id: string): Promise<void> {\n this.batches = this.batches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n\n /**\n * Sets a stored batch's delivery attempt count.\n * @param id Batch identifier.\n * @param attempts The new absolute attempt count.\n */\n bumpAttempts(id: string, attempts: number): Promise<void> {\n const found = this.batches.find((batch) => batch.id === id);\n if (found) {\n found.attempts = attempts;\n }\n return Promise.resolve();\n }\n\n /**\n * Removes expired batches, then the oldest batches above the capacity limit.\n * @returns A promise that resolves to the prune summary metrics.\n */\n prune(): Promise<PruneResult> {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n const expired = this.batches.filter((batch) => batch.createdAt < cutoff);\n this.batches = this.batches.filter((batch) => batch.createdAt >= cutoff);\n this.report(result, \"expired\", expired);\n\n const excess = this.batches.length - this.limits.maxBatches;\n if (excess > 0) {\n // An action is an audit fact, so evict the batches without one first.\n const evicted = pickEvictable(this.batches, excess, hasAction);\n this.batches = this.batches.filter((batch) => !evicted.includes(batch));\n this.report(result, \"over_capacity\", evicted);\n }\n\n return Promise.resolve(result);\n }\n\n /**\n * Adds dropped batches to the prune result and reports them under their own reason.\n * @param result The prune result across all rules.\n * @param reason The rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private report(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n if (dropped.length === 0) {\n return;\n }\n\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n this.onGap?.(gap, dropped);\n }\n\n /**\n * Returns the number of stored batches.\n * @returns A promise that resolves to the batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** Deletes every stored batch. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** Deletes every stored batch when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// Picks a storage adapter, falling back from IndexedDB to localStorage to memory instead of\n// throwing. IndexedDB is unavailable in private mode and in sandboxed frames.\n\nimport {\n STORAGE_DB_NAME,\n STORAGE_NAME_INDEXEDDB,\n STORAGE_NAME_MEMORY,\n STORAGE_NAME_NONE,\n STORAGE_PROBE_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { StorageStrategy } from \"../models/config\";\nimport type { GapReporter, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { LocalStorageStorage } from \"./local-storage\";\nimport { MemoryStorage } from \"./memory-storage\";\n\n/**\n * Returns the database name for one application namespace. The sender and the deletion both\n * use this one rule.\n * @param namespace Application namespace. An empty value keeps the name used before namespaces.\n * @returns The IndexedDB database name.\n */\nexport function storageName(namespace: string): string {\n return namespace ? `${STORAGE_DB_NAME}:${namespace}` : STORAGE_DB_NAME;\n}\n\n/**\n * Builds the adapter that keeps nothing, returned for the \"none\" strategy. Every method\n * resolves, so a sender that calls close() on shutdown doesn't crash.\n * @param onGap Receives every batch the adapter doesn't keep. Each one is a loss.\n * @returns The adapter.\n */\nconst noop = (onGap?: GapReporter): StorageAdapter => ({\n name: STORAGE_NAME_NONE,\n save: (batch) => {\n onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n return Promise.resolve();\n },\n take: () => Promise.resolve([]),\n remove: () => Promise.resolve(),\n bumpAttempts: () => Promise.resolve(),\n prune: () => Promise.resolve({ batches: 0, records: 0, reason: \"expired\" as const }),\n count: () => Promise.resolve(0),\n clear: () => Promise.resolve(),\n close: () => Promise.resolve(),\n});\n\n/**\n * Checks whether IndexedDB is available in the current context.\n * @param diagnostics Diagnostics reporter.\n * @returns True if IDBFactory is available.\n */\nfunction hasIndexedDb(diagnostics: Diagnostics): boolean {\n const available = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read indexedDB.\",\n () => {\n const factory = (globalThis as { indexedDB?: IDBFactory | null }).indexedDB;\n return factory !== undefined && factory !== null;\n },\n );\n\n return available === true;\n}\n\n/**\n * Checks whether localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if a probe write to localStorage succeeds.\n */\nfunction hasLocalStorage(diagnostics: Diagnostics): boolean {\n const usable = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not write a test key to localStorage.\",\n () => {\n localStorage.setItem(STORAGE_PROBE_KEY, \"1\");\n localStorage.removeItem(STORAGE_PROBE_KEY);\n return true;\n },\n );\n\n return usable === true;\n}\n\n/**\n * Creates the requested storage adapter, falling back to the next one when a dependency is\n * unavailable.\n * @param strategy The configured persistence strategy.\n * @param dbName IndexedDB database name.\n * @param limits Storage retention and capacity thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for telemetry gap reporting.\n * @returns A promise that resolves to the selected StorageAdapter.\n */\nexport async function createStorage(\n strategy: StorageStrategy,\n dbName: string,\n limits: StorageLimits,\n diagnostics: Diagnostics,\n onGap?: GapReporter,\n namespace = \"\",\n): Promise<StorageAdapter> {\n if (strategy === STORAGE_NAME_NONE) {\n return noop(onGap);\n }\n if (strategy === STORAGE_NAME_MEMORY) {\n return new MemoryStorage(limits, onGap);\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB || strategy === \"auto\") {\n if (hasIndexedDb(diagnostics)) {\n // The dynamic import keeps the driver out of the main bundle. If the chunk fails to\n // load, we fall back to the next adapter.\n const adapter = await diagnostics.guardAsync(\n \"storage.unavailable\",\n \"The library could not open IndexedDB.\",\n async () => {\n const { IndexedDbStorage } = await import(\"./indexeddb-storage\");\n const storage = new IndexedDbStorage(dbName, limits, diagnostics, onGap);\n // Open the database here rather than on first use. Private mode, a corrupt profile\n // and some WebViews define indexedDB but reject open(), and only a rejection in\n // this block selects the next adapter.\n await storage.open();\n return storage;\n },\n );\n if (adapter) {\n return adapter;\n }\n }\n\n if (strategy === STORAGE_NAME_INDEXEDDB) {\n diagnostics.report(\n \"storage.degraded\",\n \"IndexedDB is not available. The library uses memory storage instead.\",\n );\n return new MemoryStorage(limits, onGap);\n }\n }\n\n if (hasLocalStorage(diagnostics)) {\n return new LocalStorageStorage(\n limits,\n diagnostics,\n onGap,\n namespace ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:batch:` : undefined,\n );\n }\n\n diagnostics.report(\n \"storage.degraded\",\n \"No persistent storage is available. The library keeps undelivered records in memory only.\",\n );\n return new MemoryStorage(limits, onGap);\n}\n"],"mappings":";;;;AAYA,SAAgBW,EAAU,GAA0B;CAGlD,OAAO,MAAM,QAAQC,EAAM,OAAO,KAAKA,EAAM,QAAQ,KAAKJ,CAAc;AAC1E;AAGA,IAAaK,IAAb,MAA6B;CAYR;CACA;CAXnB,QAA8B,CAAC;CAG/B,QAA8B,CAAC;CAM/B,YACE,GACA,GACA;EADiB,AADA,KAAA,UAAAC,GACA,KAAA,UAAAC;CAChB;CAOH,IAAI,GAAkB;EAOpB,OANK,KAAK,QAAQC,CAAI,IAEX,KAAK,MAAM,SAAS,KAAK,WAClC,KAAK,MAAM,KAAKA,CAAI,IAFpB,KAAK,MAAM,KAAKA,CAAI,GAKf,KAAK,MAAM,SAAS,KAAK;CAClC;CAMA,SAAc;EACZ,OAAO,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,KAAK,OAAO;CAC7D;AACF;AASA,SAAgBC,EACd,GACA,GACA,GACK;CACL,IAAMC,IAAO,IAAIL,EAA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CAAC;CAC9B,aAAa,QAAQ,QAAQ;CAC7B,aAAa,QAAQ,QAAQ;AAC/B;AAOA,SAASiD,EAAa,GAAmC;CAUvD,OATkBnC,EAAY,MAC5B,uBACA,+CAEmB,WAAiD,aACtB,IAIzC,MAAc;AACvB;AAOA,SAASoC,EAAgB,GAAmC;CAW1D,OAVepC,EAAY,MACzB,uBACA,kEAEE,aAAa,QAAQtB,GAAmB,GAAG,GAC3C,aAAa,WAAWA,CAAiB,GAClC,GAIJ,MAAW;AACpB;AAYA,eAAsB2D,EACpB,GACA,GACA,GACA,GACA,GACA,IAAY,IACa;CACzB,IAAIC,MAAA,QACF,OAAOJ,EAAKjC,CAAK;CAEnB,IAAIqC,MAAA,UACF,OAAO,IAAIX,EAAclB,GAAQR,CAAK;CAGxC,IAAIqC,MAAA,eAAuCA,MAAa,QAAQ;EAC9D,IAAIH,EAAanC,CAAW,GAAG;GAG7B,IAAMuC,IAAU,MAAMvC,EAAY,WAChC,uBACA,yCACA,YAAY;IACV,IAAM,EAAE,wBAAqB,MAAM,OAAO,oCACpCwC,IAAU,IAAIC,EAAiBC,GAAQjC,GAAQT,GAAaC,CAAK;IAKvE,OADA,MAAMuC,EAAQ,KAAK,GACZA;GACT,CACF;GACA,IAAID,GACF,OAAOA;EAEX;EAEA,IAAID,MAAA,aAKF,OAJAtC,EAAY,OACV,oBACA,sEACF,GACO,IAAI2B,EAAclB,GAAQR,CAAK;CAE1C;CAeA,OAbImC,EAAgBpC,CAAW,IACtB,IAAIQ,EACTC,GACAT,GACAC,GACAgC,IAAY,+BAA+B,mBAAmBA,CAAS,EAAE,WAAW,KAAA,CACtF,KAGFjC,EAAY,OACV,oBACA,2FACF,GACO,IAAI2B,EAAclB,GAAQR,CAAK;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixed-window-CvESpFYV.cjs","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period
|
|
1
|
+
{"version":3,"file":"fixed-window-CvESpFYV.cjs","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period earns no extra allowance. The capture\n// modules and the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window The window state to update.\n * @param limit Maximum events per window.\n * @param windowMs Window length in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Checks whether a fixed window has ended. The bus uses the same rule to expire its source\n * entries.\n * @param window Window state.\n * @param windowMs Window length in milliseconds.\n * @param now Current epoch time in milliseconds.\n * @returns True once the window length has passed, or when the clock moved back. Without the\n * second check, a clock that moves back would keep the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":"AAoBA,SAAgBA,EAAc,EAAqB,EAAe,EAA2B,CAC3F,IAAMC,EAAM,KAAK,IAAI,EASrB,OAPIC,EAAYC,EAAQC,EAAUH,CAAG,IACnC,EAAO,MAAQA,EACf,EAAO,MAAQ,GAGjB,EAAO,QAEAE,EAAO,OAASE,CACzB,CAWA,SAAgBH,EAAY,EAAqB,EAAkB,EAAsB,CACvF,OAAOD,EAAME,EAAO,OAASF,EAAME,EAAO,MAAQC,CACpD,C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/fixed-window.ts
|
|
2
2
|
function e(e, n, r) {
|
|
3
3
|
let i = Date.now();
|
|
4
4
|
return t(e, r, i) && (e.start = i, e.count = 0), e.count++, e.count <= n;
|
|
@@ -6,7 +6,6 @@ function e(e, n, r) {
|
|
|
6
6
|
function t(e, t, n) {
|
|
7
7
|
return n < e.start || n - e.start > t;
|
|
8
8
|
}
|
|
9
|
-
//#endregion
|
|
10
9
|
export { t as n, e as t };
|
|
11
10
|
|
|
12
|
-
//# sourceMappingURL=fixed-window-
|
|
11
|
+
//# sourceMappingURL=fixed-window-Dq3MLUUv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fixed-window-Dq3MLUUv.js","names":["countInWindow","now","windowEnded","window","windowMs","limit"],"sources":["../src/utils/fixed-window.ts"],"sourcesContent":["// src/utils/fixed-window.ts\n//\n// Counts events in a fixed time window. A quiet period earns no extra allowance. The capture\n// modules and the error ceiling use it to stop a storm of records.\n\n/** State of one fixed window. Counters that share a limit share one object. */\nexport interface StormWindow {\n /** Start of the current window, in epoch milliseconds. */\n start: number;\n /** Events counted in the current window. */\n count: number;\n}\n\n/**\n * Counts one event in a fixed window.\n * @param window The window state to update.\n * @param limit Maximum events per window.\n * @param windowMs Window length in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the event.\n */\nexport function countInWindow(window: StormWindow, limit: number, windowMs: number): boolean {\n const now = Date.now();\n\n if (windowEnded(window, windowMs, now)) {\n window.start = now;\n window.count = 0;\n }\n\n window.count++;\n\n return window.count <= limit;\n}\n\n/**\n * Checks whether a fixed window has ended. The bus uses the same rule to expire its source\n * entries.\n * @param window Window state.\n * @param windowMs Window length in milliseconds.\n * @param now Current epoch time in milliseconds.\n * @returns True once the window length has passed, or when the clock moved back. Without the\n * second check, a clock that moves back would keep the window open.\n */\nexport function windowEnded(window: StormWindow, windowMs: number, now: number): boolean {\n return now < window.start || now - window.start > windowMs;\n}\n"],"mappings":";AAoBA,SAAgBA,EAAc,GAAqB,GAAe,GAA2B;CAC3F,IAAMC,IAAM,KAAK,IAAI;CASrB,OAPIC,EAAYC,GAAQC,GAAUH,CAAG,MACnC,EAAO,QAAQA,GACf,EAAO,QAAQ,IAGjB,EAAO,SAEAE,EAAO,SAASE;AACzB;AAWA,SAAgBH,EAAY,GAAqB,GAAkB,GAAsB;CACvF,OAAOD,IAAME,EAAO,SAASF,IAAME,EAAO,QAAQC;AACpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol
|
|
1
|
+
{"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol, so two copies of the library on one page share the\n// count. Otherwise one copy would capture the other copy's requests and console lines.\n\n/** A scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. Only the synchronous part of the function is covered.\n * @param fn The function to run.\n * @returns The function's return value.\n */\n run<T>(fn: () => T): T;\n /**\n * Checks whether a scope is open.\n * @returns True while a function is running inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Creates a scope whose count lives on a global symbol.\n * @param key The global symbol's key.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // Counting keeps this correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF,C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/global-scope.ts
|
|
2
2
|
function e(e) {
|
|
3
3
|
let t = Symbol.for(e), n = globalThis, r = () => n[t] ?? 0;
|
|
4
4
|
return {
|
|
@@ -13,7 +13,6 @@ function e(e) {
|
|
|
13
13
|
open: () => r() > 0
|
|
14
14
|
};
|
|
15
15
|
}
|
|
16
|
-
//#endregion
|
|
17
16
|
export { e as t };
|
|
18
17
|
|
|
19
|
-
//# sourceMappingURL=global-scope-
|
|
18
|
+
//# sourceMappingURL=global-scope-D9I8s-oN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global-scope-D9I8s-oN.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol, so two copies of the library on one page share the\n// count. Otherwise one copy would capture the other copy's requests and console lines.\n\n/** A scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. Only the synchronous part of the function is covered.\n * @param fn The function to run.\n * @returns The function's return value.\n */\n run<T>(fn: () => T): T;\n /**\n * Checks whether a scope is open.\n * @returns True while a function is running inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Creates a scope whose count lives on a global symbol.\n * @param key The global symbol's key.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // Counting keeps this correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/guards.ts
|
|
2
2
|
function e(e) {
|
|
3
3
|
return typeof e == "object" && !!e && !Array.isArray(e);
|
|
4
4
|
}
|
|
5
|
-
//#endregion
|
|
6
5
|
export { e as t };
|
|
7
6
|
|
|
8
|
-
//# sourceMappingURL=guards-
|
|
7
|
+
//# sourceMappingURL=guards-Cidk71ME.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards-Cidk71ME.js","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values that come from outside the library, such as config input, a server\n// answer or a call's payload.\n\n/**\n * Checks whether a value is a non-null object that isn't an array.\n * @param value The value to check.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAUA,SAAgBA,EAAS,GAAkD;CACzE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guards-nJ70syPt.cjs","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library,
|
|
1
|
+
{"version":3,"file":"guards-nJ70syPt.cjs","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values that come from outside the library, such as config input, a server\n// answer or a call's payload.\n\n/**\n * Checks whether a value is a non-null object that isn't an array.\n * @param value The value to check.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":"AAUA,SAAgBA,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=identity-
|
|
1
|
+
const e=require("./constants-DakMxVB2.cjs");var t={local:()=>localStorage,session:()=>sessionStorage};function n(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function r(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return r(16)}function a(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function o(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function s(t,n,r,i){let o=a(t,`local`,e.An,n);if(o)try{let e=JSON.parse(o);return e.id&&(i===0||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function c(n,r=t,c=e.kn){let l=i(n),u=Date.now(),d=i(n),f=s(r,n,u,c)??d,p=JSON.stringify({id:f,lastSeenAt:u});o(r,`local`,e.An,p,n);let m=a(r,`session`,`ui-observability.tab`,n)??``;return m||(m=i(n),o(r,`session`,e.Hn,m,n)),{sessionId:f,tabId:m,contextId:l}}function l(t,n,r){o(r,`session`,e.Hn,t,n)}var u=class{diagnostics;stores;touchMs;idleMs;lastTouchAt=0;constructor(n,r=t,i=e.jn,a=e.kn){this.diagnostics=n,this.stores=r,this.touchMs=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<this.touchMs)return;let n=s(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return s(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.An,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
|
|
2
|
+
//# sourceMappingURL=identity-BlvlgjrU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity-BlvlgjrU.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","SESSION_TOUCH_MS","require_constants","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","touchMs","stored"],"sources":["../src/utils/identity.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Creates and keeps the session, tab, and context correlation identifiers. In a sandboxed\n// iframe and in private mode, Storage throws instead of returning null, so an unguarded read\n// would break the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. Used by the `identity: \"storage\"` option. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. Used by the `identity: \"memory\"` option.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the given byte length. Uses\n * crypto.getRandomValues when it is available, and Math.random otherwise.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier with crypto.randomUUID, falling back to randomHex.\n * @param diagnostics Diagnostics reporter. Counts a blocked crypto.randomUUID call.\n * @returns A UUID or a random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError: the method exists but the\n // call throws. Count the fault, because a report for every id would be noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store, reporting any storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns The stored string, or null if it is unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store, reporting any storage error to\n * diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value The string value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Reads the session id from the local store. Reports a record that isn't valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @param idleMs Idle time after which the session expires, in milliseconds. 0 means never.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === 0 || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\n }\n}\n\n/**\n * Resolves or initializes the session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns The populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n idleMs = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`. The throttle\n * state lives on the instance, not the module, so two runtimes in one document don't block\n * each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n private readonly touchMs = SESSION_TOUCH_MS,\n private readonly idleMs = SESSION_IDLE_MS,\n ) {}\n\n /**\n * Writes the session activity time to the local store, at most once per throttle window.\n * @param sessionId The active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < this.touchMs) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Don't write the old\n // id back, or a reload would resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id from the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store right away, bypassing the throttle.\n * @param sessionId The new session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n"],"mappings":"A,4CAwDA,IAAaK,EAAiC,CAC5C,UAAa,aAC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AAc,KAAK,QAChC,OAKF,IAAMU,EAASd,EAAY,KAAK,OAAQ,KAAK,YAAaI,EAAK,KAAK,MAAM,EACtEU,IAAW,IAAA,IAAaA,IAAWN,EACrC,KAAK,YAAcJ,EAIrB,KAAK,MAAMI,EAAWJ,CAAG,CAC3B,CAMA,QAA6B,CAC3B,OAAOJ,EAAY,KAAK,OAAQ,KAAK,YAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAC3E,CAMA,QAAQ,EAAyB,CAC/B,KAAK,MAAMQ,EAAW,KAAK,IAAI,CAAC,CAClC,CAOA,MAAc,EAAmB,EAAmB,CAClD,KAAK,YAAcJ,EACnB,IAAMK,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYJ,CAAI,CAAC,EACjEL,EAAU,KAAK,OAAQ,QAASvB,EAAAA,GAAgBiC,EAAS,KAAK,WAAW,CAC3E,CACF,E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { An as e,
|
|
2
|
-
|
|
1
|
+
import { An as e, Hn as t, jn as n, kn as r } from "./constants-Bwl_YtQi.js";
|
|
2
|
+
// src/utils/identity.ts
|
|
3
3
|
var i = {
|
|
4
4
|
local: () => localStorage,
|
|
5
5
|
session: () => sessionStorage
|
|
@@ -41,31 +41,31 @@ function l(e, t, n, r, i) {
|
|
|
41
41
|
e[t]().setItem(n, r);
|
|
42
42
|
});
|
|
43
43
|
}
|
|
44
|
-
function u(
|
|
45
|
-
let a = c(
|
|
44
|
+
function u(t, n, r, i) {
|
|
45
|
+
let a = c(t, "local", e, n);
|
|
46
46
|
if (a) try {
|
|
47
47
|
let e = JSON.parse(a);
|
|
48
48
|
return e.id && (i === 0 || r - (e.lastSeenAt ?? 0) < i) ? e.id : void 0;
|
|
49
49
|
} catch {
|
|
50
|
-
|
|
50
|
+
n.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
|
|
51
51
|
return;
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
function d(
|
|
55
|
-
let d = s(
|
|
54
|
+
function d(n, a = i, o = r) {
|
|
55
|
+
let d = s(n), f = Date.now(), p = s(n), m = u(a, n, f, o) ?? p, h = JSON.stringify({
|
|
56
56
|
id: m,
|
|
57
57
|
lastSeenAt: f
|
|
58
58
|
});
|
|
59
|
-
l(a, "local",
|
|
60
|
-
let g = c(a, "session", "ui-observability.tab",
|
|
61
|
-
return g || (g = s(
|
|
59
|
+
l(a, "local", e, h, n);
|
|
60
|
+
let g = c(a, "session", "ui-observability.tab", n) ?? "";
|
|
61
|
+
return g || (g = s(n), l(a, "session", t, g, n)), {
|
|
62
62
|
sessionId: m,
|
|
63
63
|
tabId: g,
|
|
64
64
|
contextId: d
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
|
-
function f(
|
|
68
|
-
l(r, "session",
|
|
67
|
+
function f(e, n, r) {
|
|
68
|
+
l(r, "session", t, e, n);
|
|
69
69
|
}
|
|
70
70
|
var p = class {
|
|
71
71
|
diagnostics;
|
|
@@ -73,8 +73,8 @@ var p = class {
|
|
|
73
73
|
touchMs;
|
|
74
74
|
idleMs;
|
|
75
75
|
lastTouchAt = 0;
|
|
76
|
-
constructor(e,
|
|
77
|
-
this.diagnostics = e, this.stores =
|
|
76
|
+
constructor(e, t = i, a = n, o = r) {
|
|
77
|
+
this.diagnostics = e, this.stores = t, this.touchMs = a, this.idleMs = o;
|
|
78
78
|
}
|
|
79
79
|
touch(e) {
|
|
80
80
|
let t = Date.now();
|
|
@@ -88,16 +88,15 @@ var p = class {
|
|
|
88
88
|
restart(e) {
|
|
89
89
|
this.write(e, Date.now());
|
|
90
90
|
}
|
|
91
|
-
write(
|
|
92
|
-
this.lastTouchAt =
|
|
91
|
+
write(t, n) {
|
|
92
|
+
this.lastTouchAt = n;
|
|
93
93
|
let r = JSON.stringify({
|
|
94
|
-
id:
|
|
95
|
-
lastSeenAt:
|
|
94
|
+
id: t,
|
|
95
|
+
lastSeenAt: n
|
|
96
96
|
});
|
|
97
|
-
l(this.stores, "local",
|
|
97
|
+
l(this.stores, "local", e, r, this.diagnostics);
|
|
98
98
|
}
|
|
99
99
|
};
|
|
100
|
-
//#endregion
|
|
101
100
|
export { f as a, s as i, p as n, o, a as r, d as s, i as t };
|
|
102
101
|
|
|
103
|
-
//# sourceMappingURL=identity-
|
|
102
|
+
//# sourceMappingURL=identity-BrQp_5J5.js.map
|