@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deadline-5_PecIl5.js","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":";AAYA,SAAgBA,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB;;;ACRA,IAAaC,IAAb,cAAmC,MAAM;CAIvC,YAAY,GAAY;EAEtB,AADA,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,GACxD,KAAK,OAAO;CACd;AACF;AAQA,SAAgBC,EAAgB,GAAkB,GAAwB;CACxE,IAAIC,GAEEC,IAAW,IAAI,SAAgB,GAAU,MAAW;EACxD,IAAML,IAAQ,iBAAiB;GAC7B,EAAO,IAAIC,EAAcC,CAAE,CAAC;EAC9B,GAAGA,CAAE;EAGL,AADA,IAASF,GACTD,EAAWC,CAAK;CAClB,CAAC;CAGD,OAAO,QAAQ,KAAK,CAACM,GAAMD,CAAQ,CAAC,CAAC,CAAC,cAAc;EAClD,aAAaD,CAAM;CACrB,CAAC;AACH"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){typeof e!=`number`&&e.unref?.()}var t=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function n(n,r){let i,a=new Promise((n,a)=>{let o=setTimeout(()=>{a(new t(r))},r);i=o,e(o)});return Promise.race([n,a]).finally(()=>{clearTimeout(i)})}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
|
|
2
|
-
//# sourceMappingURL=deadline-XSnm95pg.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deadline-XSnm95pg.cjs","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"AAYA,SAAgBA,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAAkB,EAAwB,CACxE,IAAIC,EAEEC,EAAW,IAAI,SAAgB,EAAU,IAAW,CACxD,IAAML,EAAQ,eAAiB,CAC7BM,EAAO,IAAIL,EAAcC,CAAE,CAAC,CAC9B,EAAGA,CAAE,EAEL,EAASF,EACTD,EAAWC,CAAK,CAClB,CAAC,EAGD,OAAO,QAAQ,KAAK,CAACO,EAAMF,CAAQ,CAAC,CAAC,CAAC,YAAc,CAClD,aAAaD,CAAM,CACrB,CAAC,CACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"debug-bundle-CZZ6SQQh.js","names":["isObject","recordedUrl","stripUrls","value","key","entry","configSummary","cut","config","copy","serializer","capture","plugin","sanitize","limits","diagnostics"],"sources":["../src/core/debug-bundle.ts"],"sourcesContent":["// src/core/debug-bundle.ts\n//\n// Makes the config summary of a debug bundle. The runtime loads this module only when the app\n// asks for a bundle.\n\nimport type { ResolvedConfig } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { sanitize, type SanitizeLimits } from \"../utils/sanitize\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Removes the user info, query and fragment of each absolute URL in a JSON-safe value. The\n * library also puts the endpoints into `capture.ignoreUrls`.\n * @param value JSON-safe value.\n * @returns The value with each URL cut.\n */\nfunction stripUrls(value: unknown): unknown {\n if (typeof value === \"string\") {\n return /^[a-z][a-z\\d+.-]*:\\/\\//i.test(value) ? recordedUrl(value, false) : value;\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUrls);\n }\n\n if (isObject(value)) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, stripUrls(entry)]));\n }\n\n return value;\n}\n\n/**\n * Copies the config for a support ticket. It leaves out the headers and cuts each URL. A function\n * becomes its name, and a RegExp its text.\n * @param config Active configuration.\n * @param limits Limits of the copy, as for record attributes.\n * @param diagnostics Diagnostics reporter.\n * @returns JSON-safe copy of the config.\n */\nexport function configSummary(\n config: ResolvedConfig,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n // A relative endpoint has no scheme. stripUrls() does not see it as a URL.\n const cut = (value: unknown): unknown =>\n typeof value === \"string\" ? recordedUrl(value, false) : value;\n const { capture, serializer } = config;\n const copy: Record<string, unknown> = {\n ...config,\n endpoint: cut(config.endpoint),\n metricsEndpoint: cut(config.metricsEndpoint),\n tracesEndpoint: cut(config.tracesEndpoint),\n // An object of the app can hold a key in any field. Only its name goes out.\n serializer: typeof serializer === \"string\" ? serializer : serializer.name,\n capture: {\n ...capture,\n ignoreUrls: capture.ignoreUrls.map(cut),\n plugins: capture.plugins.map((plugin) => plugin.name),\n },\n };\n // Static headers can hold a token.\n Reflect.deleteProperty(copy, \"headers\");\n\n return stripUrls(sanitize(copy, limits, diagnostics)) as Record<string, unknown>;\n}\n"],"mappings":";;;;AAiBA,SAASE,EAAU,GAAyB;CAa1C,OAZI,OAAOC,KAAU,WACZ,0BAA0B,KAAKA,CAAK,IAAIF,EAAYE,GAAO,EAAK,IAAIA,IAGzE,MAAM,QAAQA,CAAK,IACdA,EAAM,IAAID,CAAS,IAGxBF,EAASG,CAAK,IACT,OAAO,YAAY,OAAO,QAAQA,CAAK,CAAC,CAAC,KAAK,CAACC,GAAKC,OAAW,CAACD,GAAKF,EAAUG,CAAK,CAAC,CAAC,CAAC,IAGzFF;AACT;AAUA,SAAgBG,EACd,GACA,GACA,GACyB;CAEzB,IAAMC,KAAO,MACX,OAAOJ,KAAU,WAAWF,EAAYE,GAAO,EAAK,IAAIA,GACpD,EAAE,YAAS,kBAAeK,GAC1BC,IAAgC;EACpC,GAAGD;EACH,UAAUD,EAAIC,EAAO,QAAQ;EAC7B,iBAAiBD,EAAIC,EAAO,eAAe;EAC3C,gBAAgBD,EAAIC,EAAO,cAAc;EAEzC,YAAY,OAAOE,KAAe,WAAWA,IAAaA,EAAW;EACrE,SAAS;GACP,GAAGC;GACH,YAAYA,EAAQ,WAAW,IAAIJ,CAAG;GACtC,SAASI,EAAQ,QAAQ,KAAK,MAAWC,EAAO,IAAI;EACtD;CACF;CAIA,OAFA,QAAQ,eAAeH,GAAM,SAAS,GAE/BP,EAAUW,EAASJ,GAAMK,GAAQC,CAAW,CAAC;AACtD"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./guards-nJ70syPt.cjs"),t=require("./platform-KMWkoI-v.cjs"),n=require("./sanitize-Bsn8HQWC.cjs");function r(n){return typeof n==`string`?/^[a-z][a-z\d+.-]*:\/\//i.test(n)?t.i(n,!1):n:Array.isArray(n)?n.map(r):e.t(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,r(t)])):n}function i(e,i,a){let o=e=>typeof e==`string`?t.i(e,!1):e,{capture:s,serializer:c}=e,l={...e,endpoint:o(e.endpoint),metricsEndpoint:o(e.metricsEndpoint),tracesEndpoint:o(e.tracesEndpoint),serializer:typeof c==`string`?c:c.name,capture:{...s,ignoreUrls:s.ignoreUrls.map(o),plugins:s.plugins.map(e=>e.name)}};return Reflect.deleteProperty(l,`headers`),r(n.n(l,i,a))}exports.configSummary=i;
|
|
2
|
-
//# sourceMappingURL=debug-bundle-yRkrU1ny.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"debug-bundle-yRkrU1ny.cjs","names":["recordedUrl","isObject","sanitize","require_guards","require_platform","require_sanitize","stripUrls","value","key","entry","configSummary","cut","config","copy","serializer","capture","plugin","limits","diagnostics"],"sources":["../src/core/debug-bundle.ts"],"sourcesContent":["// src/core/debug-bundle.ts\n//\n// Makes the config summary of a debug bundle. The runtime loads this module only when the app\n// asks for a bundle.\n\nimport type { ResolvedConfig } from \"../models/config\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { sanitize, type SanitizeLimits } from \"../utils/sanitize\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Removes the user info, query and fragment of each absolute URL in a JSON-safe value. The\n * library also puts the endpoints into `capture.ignoreUrls`.\n * @param value JSON-safe value.\n * @returns The value with each URL cut.\n */\nfunction stripUrls(value: unknown): unknown {\n if (typeof value === \"string\") {\n return /^[a-z][a-z\\d+.-]*:\\/\\//i.test(value) ? recordedUrl(value, false) : value;\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUrls);\n }\n\n if (isObject(value)) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, stripUrls(entry)]));\n }\n\n return value;\n}\n\n/**\n * Copies the config for a support ticket. It leaves out the headers and cuts each URL. A function\n * becomes its name, and a RegExp its text.\n * @param config Active configuration.\n * @param limits Limits of the copy, as for record attributes.\n * @param diagnostics Diagnostics reporter.\n * @returns JSON-safe copy of the config.\n */\nexport function configSummary(\n config: ResolvedConfig,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n // A relative endpoint has no scheme. stripUrls() does not see it as a URL.\n const cut = (value: unknown): unknown =>\n typeof value === \"string\" ? recordedUrl(value, false) : value;\n const { capture, serializer } = config;\n const copy: Record<string, unknown> = {\n ...config,\n endpoint: cut(config.endpoint),\n metricsEndpoint: cut(config.metricsEndpoint),\n tracesEndpoint: cut(config.tracesEndpoint),\n // An object of the app can hold a key in any field. Only its name goes out.\n serializer: typeof serializer === \"string\" ? serializer : serializer.name,\n capture: {\n ...capture,\n ignoreUrls: capture.ignoreUrls.map(cut),\n plugins: capture.plugins.map((plugin) => plugin.name),\n },\n };\n // Static headers can hold a token.\n Reflect.deleteProperty(copy, \"headers\");\n\n return stripUrls(sanitize(copy, limits, diagnostics)) as Record<string, unknown>;\n}\n"],"mappings":"mHAiBA,SAASM,EAAU,EAAyB,CAa1C,OAZI,OAAOC,GAAU,SACZ,0BAA0B,KAAKA,CAAK,EAAIP,EAAAA,EAAYO,EAAO,EAAK,EAAIA,EAGzE,MAAM,QAAQA,CAAK,EACdA,EAAM,IAAID,CAAS,EAGxBL,EAAAA,EAASM,CAAK,EACT,OAAO,YAAY,OAAO,QAAQA,CAAK,CAAC,CAAC,KAAK,CAACC,EAAKC,KAAW,CAACD,EAAKF,EAAUG,CAAK,CAAC,CAAC,CAAC,EAGzFF,CACT,CAUA,SAAgBG,EACd,EACA,EACA,EACyB,CAEzB,IAAMC,EAAO,GACX,OAAOJ,GAAU,SAAWP,EAAAA,EAAYO,EAAO,EAAK,EAAIA,EACpD,CAAE,UAAS,cAAeK,EAC1BC,EAAgC,CACpC,GAAGD,EACH,SAAUD,EAAIC,EAAO,QAAQ,EAC7B,gBAAiBD,EAAIC,EAAO,eAAe,EAC3C,eAAgBD,EAAIC,EAAO,cAAc,EAEzC,WAAY,OAAOE,GAAe,SAAWA,EAAaA,EAAW,KACrE,QAAS,CACP,GAAGC,EACH,WAAYA,EAAQ,WAAW,IAAIJ,CAAG,EACtC,QAASI,EAAQ,QAAQ,IAAK,GAAWC,EAAO,IAAI,CACtD,CACF,EAIA,OAFA,QAAQ,eAAeH,EAAM,SAAS,EAE/BP,EAAUJ,EAAAA,EAASW,EAAMI,EAAQC,CAAW,CAAC,CACtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"emergency-queue-CQ-9acZf.cjs","names":["isLogBatch","keysWithPrefix","withDeadline","STORAGE_DEADLINE_MS","batchKey","EMERGENCY_STORAGE_KEY_PREFIX","require_constants","require_deadline","require_batch","require_keys","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, every window on the origin drains and sends the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock is not available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * It runs the task directly when the Web Locks API is not available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Gives the lock name of one application namespace. Two namespaces on one origin then do not wait for each other.\n * Without it, the retry pass of one application skips while the other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns Lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch. Parse each entry one time.\n // A batch of another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. Each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of the old entries that the queue drops, and of a\n * batch that the store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window removed gives null. readBatch then rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this function. A throw here skips the shutdown of the sender.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes emergency entries of one context, or all entries in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace Application storage namespace.\n * @param all True to remove entries of all contexts in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Gives the emergency storage prefix of one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns Prefix for this application emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":"oJAoCA,SAAgBU,EACd,EACA,EACA,EACA,CAAE,aAAa,IAAmC,CAAC,EAC3B,CACxB,IAAMC,EAAS,WAA2D,WAAW,MAOrF,OAJKA,GAAO,QAILC,EAAY,WACjB,mBACA,sCAAsCC,EAAK,OAEzCF,EAAM,QAAQE,EAAM,CAAE,YAAaC,CAAW,EAAI,GAChDC,EAAOC,EAAG,EAAI,QAAQ,QAAQ,IAAA,EAAS,CACzC,CACJ,EAVSA,EAAG,CAWd,CASA,SAAgBC,EAAS,EAAc,EAA2B,CAChE,OAAOC,EAAY,GAAGL,EAAK,GAAG,mBAAmBK,CAAS,IAAML,CAClE,CC1CA,SAASM,EAAU,EAAa,EAA2C,CACzE,IAAMC,EAASR,EAAY,MACzB,mBACA,oEACM,KAAK,MAAMS,CAAG,CACtB,EAeA,OAZID,IAAW,IAAA,GACN,KAGJpB,EAAAA,EAAWoB,CAAM,EAQfA,GAPLR,EAAY,OACV,mBACA,4DACF,EACO,KAIX,CAQA,eAAeU,EACb,EACA,EACA,EACA,EACiB,CACjB,IAAIC,EAAQ,EAEZ,IAAK,IAAMC,KAAOvB,EAAAA,EAAewB,EAAQb,CAAW,EAAG,CAIrD,IAAMc,EAAQd,EAAY,MACxB,sBACA,sDACuB,CACrB,IAAMe,EAAQ,aAAa,QAAQH,CAAG,EAChCJ,EA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EACpB,EACA,EACA,MAA8C,GAC9C,EAAY,GACK,CAQjB,OAAO,MAPahC,EAClBO,EAAA,6BAA8BC,CAAS,EACvCN,MACMU,EAAUO,EAASjB,EAAagB,EAASI,EAAgBd,CAAS,CAAC,EACzE,CAAE,WAAY,EAAM,CACtB,GAEgB,CAClB,CASA,SAAgByB,EACd,EACA,EACA,EAAY,GACZ,EAAM,GACA,CACN,IAAMlB,EAASO,EAAgBd,CAAS,EACxCN,EAAY,MACV,sBACA,+DACM,CACJ,IAAK,IAAMY,KAAOvB,EAAAA,EAAewB,EAAQb,CAAW,EAAG,CACrD,IAAMS,EAAM,aAAa,QAAQG,CAAG,EAChCH,IAAQuB,GAAOzB,EAAUE,EAAKT,CAAW,CAAC,EAAE,mBAAqBiC,IACnE,aAAa,WAAWrB,CAAG,CAC/B,CACF,CACF,CACF,CAOA,SAASQ,EAAgB,EAAY,GAAY,CAC/C,OAAOd,EACH,+BAA+B,mBAAmBA,CAAS,EAAE,aAC7Db,EAAAA,EACN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"emergency-queue-Cs8-i2xw.js","names":["STORAGE_DEADLINE_MS","EMERGENCY_STORAGE_KEY_PREFIX","isLogBatch","keysWithPrefix","batchKey","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","withDeadline","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, every window on the origin drains and sends the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock is not available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * It runs the task directly when the Web Locks API is not available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Gives the lock name of one application namespace. Two namespaces on one origin then do not wait for each other.\n * Without it, the retry pass of one application skips while the other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns Lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch. Parse each entry one time.\n // A batch of another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. Each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of the old entries that the queue drops, and of a\n * batch that the store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window removed gives null. readBatch then rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this function. A throw here skips the shutdown of the sender.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes emergency entries of one context, or all entries in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace Application storage namespace.\n * @param all True to remove entries of all contexts in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Gives the emergency storage prefix of one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns Prefix for this application emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":";;;;;AAoCA,SAAgBK,EACd,GACA,GACA,GACA,EAAE,gBAAa,OAAmC,CAAC,GAC3B;CACxB,IAAMC,IAAS,WAA2D,WAAW;CAOrF,OAJKA,GAAO,UAILC,EAAY,WACjB,oBACA,sCAAsCC,EAAK,UAEzCF,EAAM,QAAQE,GAAM,EAAE,aAAaC,EAAW,IAAI,MAChDC,IAAOC,EAAG,IAAI,QAAQ,QAAQ,KAAA,CAAS,CACzC,CACJ,IAVSA,EAAG;AAWd;AASA,SAAgBC,EAAS,GAAc,GAA2B;CAChE,OAAOC,IAAY,GA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KAAKI,CAAO,GAEtB,aAAa,WAAWD,CAAG;EAC7B;EAGA,OADA,aAAa,QAAQ7B,EAASgB,GAAQC,CAAK,GAAG,KAAK,UAAUA,CAAK,CAAC,GAC5D;CACT,CAAC;CAGD,EAAY,MAAM,oBAAoB,wDAAwD;EAC5F,IAAIS,EAAQ,SAAS,GAAG;GACtB,IAAMK,IAAUL,EAAQ,SAAS,MAAQM,EAAI,OAAO;GACpD,IACE,mBACAD,GACAL,EAAQ,KAAK,MAAQM,EAAI,EAAE,CAC7B;EACF;EAEA,AAAIL,MAAU,MACZM,IAAS,SAAShB,EAAM,SAAS,CAACA,EAAM,EAAE,CAAC;CAE/C,CAAC;AACH;AAQA,eAAsBiB,EACpB,GACA,GACA,UAA8C,IAC9C,IAAY,IACK;CAQjB,OAAO,MAPajC,EAClBO,EAAA,8BAA8BC,CAAS,GACvCN,SACMU,EAAUQ,GAASlB,GAAagB,GAASK,EAAgBf,CAAS,CAAC,GACzE,EAAE,YAAY,GAAM,CACtB,KAEgB;AAClB;AASA,SAAgB0B,EACd,GACA,GACA,IAAY,IACZ,IAAM,IACA;CACN,IAAMnB,IAASQ,EAAgBf,CAAS;CACxC,EAAY,MACV,uBACA,kEACM;EACJ,KAAK,IAAMM,KAAOhB,EAAeiB,GAAQb,CAAW,GAAG;GACrD,IAAMS,IAAM,aAAa,QAAQG,CAAG;GACpC,AAAIH,MAAQwB,KAAO1B,EAAUE,GAAKT,CAAW,CAAC,EAAE,qBAAqBkC,MACnE,aAAa,WAAWtB,CAAG;EAC/B;CACF,CACF;AACF;AAOA,SAASS,EAAgB,IAAY,IAAY;CAC/C,OAAOf,IACH,+BAA+B,mBAAmBA,CAAS,EAAE,eAC7DZ;AACN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-like-Ywo5uRHo.js","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/** Standard fields of an error. The library writes the other own fields as error data. */\nexport const ERROR_OWN_KEYS: ReadonlySet<string> = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * Tests if a value is a field that error data keeps. An object field, for example the\n * config of an AxiosError, holds credentials and request bodies.\n * @param value Field value.\n * @returns True for a string, a number or a boolean.\n */\nexport function isDataField(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\n/** The fields of an error that the library reads. */\nexport interface ErrorLike {\n /** Error class name, for example \"TypeError\". */\n name: string;\n /** Error message. */\n message: string;\n /** Stack trace text. */\n stack?: string;\n}\n\n/**\n * Tests if a value has the shape of an error.\n * A getter on a hostile value can throw. Call this function inside a diagnostics guard.\n * @param value Value to test.\n * @returns True for an object with a string name, a string message and a string or no stack.\n */\nexport function isErrorLike(value: unknown): value is ErrorLike {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n return (\n typeof candidate.name === \"string\" &&\n typeof candidate.message === \"string\" &&\n (candidate.stack === undefined || typeof candidate.stack === \"string\")\n );\n}\n"],"mappings":";AAMA,IAAaA,oBAAsC,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAS;AAAO,CAAC;AAQhG,SAAgBC,EAAY,GAAyB;CACnD,OAAO,OAAOC,KAAU,YAAY,OAAOA,KAAU,YAAY,OAAOA,KAAU;AACpF;AAkBA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAME,IAAYF;CAClB,OACE,OAAOE,EAAU,QAAS,YAC1B,OAAOA,EAAU,WAAY,aAC5BA,EAAU,UAAU,KAAA,KAAa,OAAOA,EAAU,SAAU;AAEjE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-CigX45pL.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 /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value 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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing 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 // Uses capture phase to observe non-bubbling resource load errors.\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 // Filters element-level resource load failures from script errors.\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. A signed URL is a credential.\n // The record keeps neither 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 captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\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 // 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 // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each 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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, 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":"oHAgCA,SAASM,EAAY,EAA2B,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,IAAI,OAAO,cAAc,mBAAqB,GACnD,KAAK,KAAK,KAAO,KAAK,IAAI,OAAO,cAAc,mBAC/C,CACA,GAAM,CAACI,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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-oyxrpHjY.js","names":["isErrorLike","recordedUrl","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value 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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing 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 // Uses capture phase to observe non-bubbling resource load errors.\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 // Filters element-level resource load failures from script errors.\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. A signed URL is a credential.\n // The record keeps neither 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 captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\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 // 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 // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each 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 // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;AAgCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgBd;CAd7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK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AGf,EAAE,YAAS,WAAQ,KAAK,IAAI,YAAY,MAC5C,yBACA,gGACMb,EAAYY,CAAK,CACzB,KAAK;GAAE,SAAS;GAAI,KAAK,GAAG,OAAOA,EAAM;EAAI,GACvCE,IAAW,KAAK,KAAK,IAAIC,CAAG;EAElC,IAAID,KAAYD,IAAMC,EAAS,KAAK,KAAK,IAAI,OAAO,cAAc,eAAe;GAE/E,AADA,EAAS,SACT,EAAS,KAAKD;GACd;EACF;EAIA,IAAMG,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAKtC,KAAK,IAAI,OAAO,cAAc,qBAAqB,KACnD,KAAK,KAAK,OAAO,KAAK,IAAI,OAAO,cAAc,oBAC/C;GACA,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMT,CAAO,IAAIS;EAC1D,KAAK,IAAI,OAAO,MAAMT,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"factory-Bgsky_e0.js","names":["STORAGE_NAME_MEMORY","BATCH_STORAGE_KEY_PREFIX","STORAGE_NAME_LOCAL","STORAGE_NAME_NONE","STORAGE_DB_NAME","STORAGE_PROBE_KEY","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// This module selects the stored batches to evict. An action is an audit fact. The batches without\n// an action go first. The walk stops early. A read of the full store at each save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Tests if a batch holds an action. An eviction removes such a batch last.\n * @param batch Batch to test.\n * @returns True if one record of 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 stops\n // the eviction walk. The walk then never settles.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from a walk in age order, oldest first. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** Oldest items with an audit fact. The pick uses them only when too few plain items exist. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Tests if 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 Next oldest item.\n * @returns False when the pick has enough items without an audit fact. The walk then stops.\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 * Gives the items to evict. The items without an audit fact come 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 a walk in age order. It 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 Tests if an item holds an audit fact.\n * @returns The picked items. The items without an audit fact come 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// This module counts and reports the batches that a storage adapter drops. Each dropped batch is a\n// loss. The gap handler gives it 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 the drop of one rule to the prune result.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts of 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 Gap handler of the adapter.\n * @param gap Counts and reason of the drop.\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// This module stores batches in localStorage with time-ordered keys. The padding makes\n// keys().sort() a sort by creation time. Without padding, the sort uses hex order. take()\n// then does 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 each save. A\n * read from the batch parses the full store for each save.\n * @param key Prefixed storage key.\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/** This StorageAdapter keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** This field holds 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 dropped record reporting.\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. It removes the oldest entries on a quota error.\n * @param batch 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 makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\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. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to an array of 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 // The entry is corrupt. The library cannot recover it. Remove it without a gap count. It has\n // no 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. It does not delete them.\n * It stops at the limit. The later entries then stay unparsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to the batches of this context.\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 the stored batches of one context. The context id is not in the key. Each entry is read.\n * @param id Delivery context id.\n * @returns Promise that resolves to the batch count of this context.\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. It removes a 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 the delivery attempt count of a stored batch. It does not change the key.\n * @param id Batch identifier.\n * @param attempts 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. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves to 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 also has no position in the sort order.\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 that the key does not contain. Parse only the\n // 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. It does not deserialize the batches.\n * @returns Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** This method deletes all batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** This method 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 Batch to store.\n * @param context Text that diagnostics reports when 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 /** This method removes a quarter of the store to free quota. It 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. An action is an audit fact.\n * A corrupt entry has no action. It goes first.\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. The later entries then stay\n * unparsed.\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. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that removes the entries.\n * @param entries 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 Storage key to read.\n * @returns Validated LogBatch or null if 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 counts one corrupt\n // 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 Matching storage key string 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 all batch storage keys in sorted order.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// This module keeps batches in volatile memory during offline periods. A reload loses all of\n// them. 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/** This StorageAdapter keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** This array holds 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 dropped record reporting.\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 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. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to an array of 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. It does not delete them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to the batches of this context.\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 the stored batches of one context.\n * @param id Delivery context id.\n * @returns Promise that resolves to the batch count of this context.\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 the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts 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. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves to 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. Evict each batch without an action 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. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason 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 Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** This method deletes all stored batches. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** This method deletes all stored batches when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// This module selects a storage adapter. It falls back from IndexedDB to localStorage to memory.\n// It falls back and does not throw. IndexedDB is unavailable in private mode and sandboxed\n// 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 * Gives the database name of one application namespace. The sender and the deletion use one rule.\n * @param namespace Application namespace. An empty value keeps the name before namespaces.\n * @returns Name of the IndexedDB database.\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. The factory returns it for the \"none\" strategy. Each\n * method resolves. A sender that calls close() on shutdown must not crash.\n * @param onGap Receives each batch that the adapter does not keep. That batch 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 if 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 if localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write 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. It falls back to the next adapter when\n * a dependency is unavailable.\n * @param strategy 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 Promise that resolves to the selected StorageAdapter instance.\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 // Import IndexedDbStorage dynamically. This keeps the driver out of the main bundle. A\n // chunk that does not load falls 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, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB but reject open(). Only a rejection in this\n // 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;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,GACO,IAAI2B,EAAclB,GAAQR,CAAK;AACxC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"factory-BkjNzPYL.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// This module selects the stored batches to evict. An action is an audit fact. The batches without\n// an action go first. The walk stops early. A read of the full store at each save blocks the page.\n\nimport { isActionRecord, type LogBatch } from \"../models/batch\";\n\n/**\n * Tests if a batch holds an action. An eviction removes such a batch last.\n * @param batch Batch to test.\n * @returns True if one record of 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 stops\n // the eviction walk. The walk then never settles.\n return Array.isArray(batch.records) && batch.records.some(isActionRecord);\n}\n\n/** Collects the items to evict from a walk in age order, oldest first. */\nexport class EvictionPick<T> {\n /** Items without an audit fact. */\n private readonly plain: T[] = [];\n\n /** Oldest items with an audit fact. The pick uses them only when too few plain items exist. */\n private readonly audit: T[] = [];\n\n /**\n * @param howMany Number of items to evict.\n * @param isAudit Tests if 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 Next oldest item.\n * @returns False when the pick has enough items without an audit fact. The walk then stops.\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 * Gives the items to evict. The items without an audit fact come 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 a walk in age order. It 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 Tests if an item holds an audit fact.\n * @returns The picked items. The items without an audit fact come 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// This module counts and reports the batches that a storage adapter drops. Each dropped batch is a\n// loss. The gap handler gives it 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 the drop of one rule to the prune result.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param batches Number of dropped batches.\n * @param records Number of dropped records.\n * @returns The counts of 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 Gap handler of the adapter.\n * @param gap Counts and reason of the drop.\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// This module stores batches in localStorage with time-ordered keys. The padding makes\n// keys().sort() a sort by creation time. Without padding, the sort uses hex order. take()\n// then does 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 each save. A\n * read from the batch parses the full store for each save.\n * @param key Prefixed storage key.\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/** This StorageAdapter keeps batches in localStorage. */\nexport class LocalStorageStorage implements StorageAdapter {\n /** This field holds 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 dropped record reporting.\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. It removes the oldest entries on a quota error.\n * @param batch 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 makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\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. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to an array of 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 // The entry is corrupt. The library cannot recover it. Remove it without a gap count. It has\n // no 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. It does not delete them.\n * It stops at the limit. The later entries then stay unparsed.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to the batches of this context.\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 the stored batches of one context. The context id is not in the key. Each entry is read.\n * @param id Delivery context id.\n * @returns Promise that resolves to the batch count of this context.\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. It removes a 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 the delivery attempt count of a stored batch. It does not change the key.\n * @param id Batch identifier.\n * @param attempts 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. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves to 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 also has no position in the sort order.\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 that the key does not contain. Parse only the\n // 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. It does not deserialize the batches.\n * @returns Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.keys().length);\n }\n\n /** This method deletes all batch keys from localStorage. */\n clear(): Promise<void> {\n this.evict(this.keys());\n return Promise.resolve();\n }\n\n /** This method 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 Batch to store.\n * @param context Text that diagnostics reports when 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 /** This method removes a quarter of the store to free quota. It 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. An action is an audit fact.\n * A corrupt entry has no action. It goes first.\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. The later entries then stay\n * unparsed.\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. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that removes the entries.\n * @param entries 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 Storage key to read.\n * @returns Validated LogBatch or null if 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 counts one corrupt\n // 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 Matching storage key string 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 all batch storage keys in sorted order.\n * @returns Sorted array of storage keys.\n */\n private keys(): string[] {\n return keysWithPrefix(this.prefix, this.diagnostics);\n }\n}\n","// src/storage/memory-storage.ts\n//\n// This module keeps batches in volatile memory during offline periods. A reload loses all of\n// them. 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/** This StorageAdapter keeps batches in volatile memory. */\nexport class MemoryStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_MEMORY;\n\n /** This array holds 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 dropped record reporting.\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 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. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to an array of 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. It does not delete them.\n * @param id Delivery context id.\n * @param limit Maximum number of batches to retrieve.\n * @returns Promise that resolves to the batches of this context.\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 the stored batches of one context.\n * @param id Delivery context id.\n * @returns Promise that resolves to the batch count of this context.\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 the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts 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. It then removes the oldest batches above the\n * capacity limit.\n * @returns Promise that resolves to 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. Evict each batch without an action 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. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason 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 Promise that resolves to batch count.\n */\n count(): Promise<number> {\n return Promise.resolve(this.batches.length);\n }\n\n /** This method deletes all stored batches. */\n clear(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n\n /** This method deletes all stored batches when the storage closes. */\n close(): Promise<void> {\n this.batches = [];\n return Promise.resolve();\n }\n}\n","// src/storage/factory.ts\n//\n// This module selects a storage adapter. It falls back from IndexedDB to localStorage to memory.\n// It falls back and does not throw. IndexedDB is unavailable in private mode and sandboxed\n// 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 * Gives the database name of one application namespace. The sender and the deletion use one rule.\n * @param namespace Application namespace. An empty value keeps the name before namespaces.\n * @returns Name of the IndexedDB database.\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. The factory returns it for the \"none\" strategy. Each\n * method resolves. A sender that calls close() on shutdown must not crash.\n * @param onGap Receives each batch that the adapter does not keep. That batch 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 if 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 if localStorage is available and accepts writes.\n * @param diagnostics Diagnostics reporter.\n * @returns True if localStorage probe write 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. It falls back to the next adapter when\n * a dependency is unavailable.\n * @param strategy 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 Promise that resolves to the selected StorageAdapter instance.\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 // Import IndexedDbStorage dynamically. This keeps the driver out of the main bundle. A\n // chunk that does not load falls 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, not on first use. Private mode, a corrupt profile and\n // some WebViews define indexedDB but reject open(). Only a rejection in this\n // 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 und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H,EAAanC,CAAW,EAAG,CAG7B,IAAMuC,EAAU,MAAMvC,EAAY,WAChC,sBACA,wCACA,SAAY,CACV,GAAM,CAAE,oBAAqB,MAAA,QAAA,QAAA,CAAA,CAAA,SAAA,QAAM,kCAAA,CAAA,EAC7BwC,EAAU,IAAIC,EAAiBC,EAAQjC,EAAQT,EAAaC,CAAK,EAKvE,OADA,MAAMuC,EAAQ,KAAK,EACZA,CACT,CACF,EACA,GAAID,EACF,OAAOA,CAEX,CAEA,GAAID,IAAA,YAKF,OAJAtC,EAAY,OACV,mBACA,sEACF,EACO,IAAI2B,EAAclB,EAAQR,CAAK,CAE1C,CAeA,OAbImC,EAAgBpC,CAAW,EACtB,IAAIQ,EACTC,EACAT,EACAC,EACAgC,EAAY,+BAA+B,mBAAmBA,CAAS,EAAE,SAAW,IAAA,EACtF,GAGFjC,EAAY,OACV,mBACA,2FACF,EACO,IAAI2B,EAAclB,EAAQR,CAAK,EACxC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fixed-window-CtaFHanJ.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 adds no allowance. The capture modules and\n// 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 Window state to change.\n * @param limit Maximum events in each window.\n * @param windowMs Length of the window, 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 * Tells if a fixed window has ended. The bus uses the same rule to expire its source entries.\n * @param window Window state.\n * @param windowMs Length of the window, in milliseconds.\n * @param now Current epoch time, in milliseconds.\n * @returns True after the window length, or when the clock moved back. Without the second\n * check, a clock that moves back keeps 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;AAUA,SAAgBH,EAAY,GAAqB,GAAkB,GAAsB;CACvF,OAAOD,IAAME,EAAO,SAASF,IAAME,EAAO,QAAQC;AACpD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"global-scope-dp2jADRl.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. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests if a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\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 // A count stays 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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"guards-CpvOpJL6.js","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identity-BMlKGHUM.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// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks 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. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\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 specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\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 string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or 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,\n // but the call throws. Count the fault. A report on each id is 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. Reports a 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 Stored string value or null if 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. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value 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 in the local store. It reports a record that is not valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\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 session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns 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 last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\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. It writes one time in each throttle window.\n * @param sessionId 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(). Do not write the old\n // id back. A reload would then 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 in 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 now. The throttle does not apply.\n * @param sessionId 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":"4CAwDA,IAAaK,EAAiC,CAC5C,UAAa,aACb,YAAe,cACjB,EAMA,SAAgBC,GAA+B,CAC7C,IAAMC,EAAQ,IAA6C,CACzD,QAAU,GAAQC,EAAI,IAAIC,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvBD,EAAI,IAAIC,EAAKC,CAAK,CACpB,EACA,WAAa,GAAQ,CACnBF,EAAI,OAAOC,CAAG,CAChB,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AAQ,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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identity-DOaHdfhT.js","names":["TAB_ID_KEY","SESSION_IDLE_MS","SESSION_ID_KEY","SESSION_TOUCH_MS","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","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// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks 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. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\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 specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\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 string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or 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,\n // but the call throws. Count the fault. A report on each id is 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. Reports a 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 Stored string value or null if 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. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value 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 in the local store. It reports a record that is not valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\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 session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns 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 last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\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. It writes one time in each throttle window.\n * @param sessionId 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(). Do not write the old\n // id back. A reload would then 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 in 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 now. The throttle does not apply.\n * @param sessionId 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":";;AAwDA,IAAaI,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKC,CAAK;EACpB;EACA,aAAa,MAAQ;GACnB,EAAI,OAAOD,CAAG;EAChB;CACF,IAEME,IAAaJ,kBAAK,IAAI,IAAI,CAAC,GAC3BK,IAAeL,kBAAK,IAAI,IAAI,CAAC;CAEnC,OAAO;EAAE,aAAaI;EAAY,eAAeC;CAAa;AAChE;AAQA,SAAgBC,EAAU,GAA4B;CACpD,IAAMC,IAAQ,IAAI,WAAWC,CAAU;CACvC,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,mBAAoB,YACrE,OAAO,gBAAgBD,CAAK;MAE5B,KAAK,IAAIE,IAAI,GAAGA,IAAID,GAAY,KAC9B,EAAMC,KAAK,KAAK,MAAM,KAAK,OAAO,IAAA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ATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","store","range","id","limit","cursor","visit","cutoff","ids","connection","mode","existing","opening","abandoned","db","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","records","gap","attempts","result","expired","total","reason","dropped","pick","howMany","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first. It does not remove them. A cursor reads one\n * batch at a time. The walk can then stop before it reads the full store.\n * @param visit Receives each batch. It returns false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that the library delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\"))\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report counts it two times.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n }\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. A larger count throws. Then the read gives nothing.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n }\n },\n );\n\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first. An action is an audit fact. It has no guard. Both callers guard it. A guard here\n * hides the failure and reports an eviction that did not occur.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records tell if a batch holds an action. The walk stops at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":"kHAqBA,SAASU,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAAC,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIK,CAAK,CAAC,CAClC,CAQA,MAAM,YAAY,EAAY,EAAoC,CAChE,IAAMC,EAAQ,MAAM,KAAK,MAAM,UAAU,EACnCC,EAAQ,YAAY,MAAM,CAACC,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,EACtE,OAAOR,EAAsBM,EAAM,MAAM,gBAAgB,CAAC,CAAC,OAAOC,EAAOE,CAAK,CAAC,CACjF,CAOA,MAAM,aAAa,EAA6B,CAE9C,OAAOT,GACL,MAFkB,KAAK,MAAM,UAAU,EAAA,CAGpC,MAAM,gBAAgB,CAA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