@utk09/ui-observability 0.9.5 → 0.11.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 +52 -0
- package/README.md +315 -99
- package/bin/uiobs.mjs +8 -0
- package/dist/{batch-BQFtb3i5.cjs → batch-C8OcWR2L.cjs} +2 -2
- package/dist/{batch-BQFtb3i5.cjs.map → batch-C8OcWR2L.cjs.map} +1 -1
- package/dist/{batch-BUJh-1jZ.js → batch-CL9uWYY3.js} +5 -6
- package/dist/{batch-BUJh-1jZ.js.map → batch-CL9uWYY3.js.map} +1 -1
- package/dist/bus/bus.d.ts +15 -0
- package/dist/{bus-DeOPHWaD.js → bus-BZ0GldpT.js} +125 -112
- package/dist/bus-BZ0GldpT.js.map +1 -0
- package/dist/bus-VWlmM5xs.cjs +2 -0
- package/dist/bus-VWlmM5xs.cjs.map +1 -0
- package/dist/capture/interactions.d.ts +18 -0
- package/dist/capture/lifecycle.d.ts +20 -0
- package/dist/capture/reports.d.ts +17 -0
- package/dist/capture/resource-timing.d.ts +14 -0
- package/dist/capture/server-timing.d.ts +19 -0
- package/dist/capture/types.d.ts +13 -0
- package/dist/capture/unclean-exit.d.ts +31 -0
- package/dist/capture/user-timing.d.ts +22 -0
- package/dist/console-BPZCuSLc.cjs +2 -0
- package/dist/console-BPZCuSLc.cjs.map +1 -0
- package/dist/{console-DbAZYJuy.js → console-BeCF7n59.js} +20 -20
- package/dist/{console-DbAZYJuy.js.map → console-BeCF7n59.js.map} +1 -1
- package/dist/constants-DqKJH_MP.cjs +2 -0
- package/dist/constants-DqKJH_MP.cjs.map +1 -0
- package/dist/constants-zyrqveN4.js +304 -0
- package/dist/constants-zyrqveN4.js.map +1 -0
- package/dist/constants.d.ts +58 -2
- 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-DxZf4Gfh.js.map → context-storage-BzkoHzkQ.js.map} +1 -1
- package/dist/core/debug-buffer.d.ts +34 -0
- package/dist/core/debug-bundle.d.ts +12 -0
- package/dist/core/deferred.d.ts +7 -0
- package/dist/core/logger.d.ts +7 -2
- package/dist/core/measure.d.ts +19 -0
- package/dist/core/pipeline.d.ts +6 -1
- package/dist/core/record.d.ts +20 -1
- package/dist/core/remote-sampling.d.ts +5 -1
- package/dist/core/runtime.d.ts +45 -2
- package/dist/core/sampling.d.ts +5 -4
- package/dist/core/sender.d.ts +3 -1
- package/dist/core/spans.d.ts +5 -0
- package/dist/{deadline-5_PecIl5.js → deadline-BOjOxNHj.js} +3 -5
- package/dist/{deadline-5_PecIl5.js.map → deadline-BOjOxNHj.js.map} +1 -1
- package/dist/deadline-XSnm95pg.cjs.map +1 -1
- package/dist/debug-bundle-BzJNpbF0.cjs +2 -0
- package/dist/debug-bundle-BzJNpbF0.cjs.map +1 -0
- package/dist/debug-bundle-C7UkHZ-q.js +25 -0
- package/dist/debug-bundle-C7UkHZ-q.js.map +1 -0
- package/dist/doctor.cjs +2 -0
- package/dist/doctor.cjs.map +1 -0
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +98 -0
- package/dist/doctor.js.map +1 -0
- package/dist/{emergency-queue-Cs1hrjsC.cjs → emergency-queue-CNTRui5t.cjs} +2 -2
- package/dist/{emergency-queue-Cs1hrjsC.cjs.map → emergency-queue-CNTRui5t.cjs.map} +1 -1
- package/dist/{emergency-queue-BYUyDHGD.js → emergency-queue-Zy6lNafo.js} +17 -19
- package/dist/{emergency-queue-BYUyDHGD.js.map → emergency-queue-Zy6lNafo.js.map} +1 -1
- package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
- package/dist/{error-like-Ywo5uRHo.js.map → error-like-B11pB4aL.js.map} +1 -1
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-BhC7HTSt.js → errors-Dh7kef0i.js} +5 -6
- package/dist/{errors-BhC7HTSt.js.map → errors-Dh7kef0i.js.map} +1 -1
- package/dist/{errors-CgY633cG.cjs → errors-tfEr48bS.cjs} +2 -2
- package/dist/{errors-CgY633cG.cjs.map → errors-tfEr48bS.cjs.map} +1 -1
- package/dist/{factory-C5TujXlU.js → factory-BonqI3NL.js} +16 -20
- package/dist/{factory-C5TujXlU.js.map → factory-BonqI3NL.js.map} +1 -1
- package/dist/{factory-CNj4DH3n.cjs → factory-CJXVYp0R.cjs} +2 -2
- package/dist/{factory-CNj4DH3n.cjs.map → factory-CJXVYp0R.cjs.map} +1 -1
- 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-CtaFHanJ.js.map → fixed-window-Dq3MLUUv.js.map} +1 -1
- 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-dp2jADRl.js.map → global-scope-D9I8s-oN.js.map} +1 -1
- package/dist/guards-Cidk71ME.js +7 -0
- package/dist/guards-Cidk71ME.js.map +1 -0
- package/dist/guards-nJ70syPt.cjs +2 -0
- package/dist/guards-nJ70syPt.cjs.map +1 -0
- package/dist/{identity-Da9TkuKd.cjs → identity-Cxgj6pZX.cjs} +2 -2
- package/dist/{identity-Da9TkuKd.cjs.map → identity-Cxgj6pZX.cjs.map} +1 -1
- package/dist/{identity-8vKkyAWm.js → identity-DT5VmvXy.js} +15 -16
- package/dist/{identity-8vKkyAWm.js.map → identity-DT5VmvXy.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +27 -7
- package/dist/index.js +980 -604
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CCA1LvtO.js → indexeddb-storage-BJVtiQKm.js} +29 -30
- package/dist/{indexeddb-storage-CCA1LvtO.js.map → indexeddb-storage-BJVtiQKm.js.map} +1 -1
- package/dist/{indexeddb-storage-BTfIFRHF.cjs → indexeddb-storage-CIoW21Xd.cjs} +2 -2
- package/dist/{indexeddb-storage-BTfIFRHF.cjs.map → indexeddb-storage-CIoW21Xd.cjs.map} +1 -1
- package/dist/interactions-DTgKy_6K.js +119 -0
- package/dist/interactions-DTgKy_6K.js.map +1 -0
- package/dist/interactions-fEN6FbVo.cjs +2 -0
- package/dist/interactions-fEN6FbVo.cjs.map +1 -0
- package/dist/{journey-BUJ4WJxP.js → journey-CuJrHzEg.js} +18 -19
- package/dist/{journey-BUJ4WJxP.js.map → journey-CuJrHzEg.js.map} +1 -1
- package/dist/{journey-B_tTnvac.cjs → journey-pffMVMfa.cjs} +2 -2
- package/dist/{journey-B_tTnvac.cjs.map → journey-pffMVMfa.cjs.map} +1 -1
- package/dist/keys-BHhw_0Wh.cjs.map +1 -1
- package/dist/{keys-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
- package/dist/{keys-D5r_GH9q.js.map → keys-BU9j5YqW.js.map} +1 -1
- package/dist/library-console-C1m6g1BR.js +13 -0
- package/dist/library-console-C1m6g1BR.js.map +1 -0
- package/dist/library-console-D2GY9Or6.cjs +2 -0
- package/dist/library-console-D2GY9Or6.cjs.map +1 -0
- package/dist/{library-request-BaZOi4eg.cjs → library-request-1BX_UlaX.cjs} +2 -2
- package/dist/{library-request-BaZOi4eg.cjs.map → library-request-1BX_UlaX.cjs.map} +1 -1
- package/dist/library-request-BQBT9N9Q.js +24 -0
- package/dist/{library-request-BKOcaKtQ.js.map → library-request-BQBT9N9Q.js.map} +1 -1
- package/dist/lifecycle-2EtUaRpo.cjs +2 -0
- package/dist/lifecycle-2EtUaRpo.cjs.map +1 -0
- package/dist/lifecycle-BaKx_-32.js +55 -0
- package/dist/lifecycle-BaKx_-32.js.map +1 -0
- package/dist/log-record-CAoGBBf3.js +16 -0
- package/dist/log-record-CAoGBBf3.js.map +1 -0
- package/dist/log-record-i9zOTkpQ.cjs +2 -0
- package/dist/log-record-i9zOTkpQ.cjs.map +1 -0
- package/dist/{long-frames-CF3qiSAX.cjs → long-frames-BVg4i5SC.cjs} +2 -2
- package/dist/{long-frames-CF3qiSAX.cjs.map → long-frames-BVg4i5SC.cjs.map} +1 -1
- package/dist/{long-frames-DI5ypfAF.js → long-frames-Czk7IupC.js} +4 -5
- package/dist/{long-frames-DI5ypfAF.js.map → long-frames-Czk7IupC.js.map} +1 -1
- package/dist/models/config.d.ts +168 -4
- package/dist/models/health.d.ts +25 -0
- package/dist/models/metric.d.ts +13 -0
- package/dist/models/storage.d.ts +5 -0
- package/dist/{network-DdzXDI3J.js → network-DBNwApoF.js} +117 -70
- package/dist/network-DBNwApoF.js.map +1 -0
- package/dist/network-xbbuvG_6.cjs +2 -0
- package/dist/network-xbbuvG_6.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js +7 -0
- package/dist/{openfin-BwEN0uj4.js.map → openfin-Bxelt0yg.js.map} +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/otlp-BDvFrLnc.cjs +2 -0
- package/dist/otlp-BDvFrLnc.cjs.map +1 -0
- package/dist/otlp-BTJdIa6F.js +81 -0
- package/dist/otlp-BTJdIa6F.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-CCWfuEY7.js.map → patch-UdPz1ea8.js.map} +1 -1
- package/dist/{platform-DBSKTvFn.cjs → platform-C2Ez5kDc.cjs} +2 -2
- package/dist/{platform-DBSKTvFn.cjs.map → platform-C2Ez5kDc.cjs.map} +1 -1
- package/dist/{platform-Bw1btWCT.js → platform-DkcuXwe-.js} +5 -6
- package/dist/{platform-Bw1btWCT.js.map → platform-DkcuXwe-.js.map} +1 -1
- package/dist/remote-rules-Cfb4K-Nl.js +98 -0
- package/dist/remote-rules-Cfb4K-Nl.js.map +1 -0
- package/dist/remote-rules-vzvk7aKf.cjs +2 -0
- package/dist/remote-rules-vzvk7aKf.cjs.map +1 -0
- package/dist/reports-Dk2YhKIh.cjs +2 -0
- package/dist/reports-Dk2YhKIh.cjs.map +1 -0
- package/dist/reports-TA-zInnq.js +70 -0
- package/dist/reports-TA-zInnq.js.map +1 -0
- package/dist/resource-timing-BLv3EA2A.js +76 -0
- package/dist/resource-timing-BLv3EA2A.js.map +1 -0
- package/dist/resource-timing-Cysw1S1f.cjs +2 -0
- package/dist/resource-timing-Cysw1S1f.cjs.map +1 -0
- package/dist/sampling-C4VV-1MS.js +60 -0
- package/dist/sampling-C4VV-1MS.js.map +1 -0
- package/dist/sampling-Ckh2yW9k.cjs +2 -0
- package/dist/sampling-Ckh2yW9k.cjs.map +1 -0
- package/dist/sanitize-6ymPlVvP.js +112 -0
- package/dist/sanitize-6ymPlVvP.js.map +1 -0
- package/dist/sanitize-BAWzkZt0.cjs +2 -0
- package/dist/sanitize-BAWzkZt0.cjs.map +1 -0
- package/dist/select-ZF4by-lF.cjs +3 -0
- package/dist/select-ZF4by-lF.cjs.map +1 -0
- package/dist/select-xtQaenIi.js +270 -0
- package/dist/select-xtQaenIi.js.map +1 -0
- package/dist/{sender-DUUmSglb.js → sender-CiMHC9YG.js} +202 -509
- package/dist/sender-CiMHC9YG.js.map +1 -0
- package/dist/sender-D5wBoXA8.cjs +2 -0
- package/dist/sender-D5wBoXA8.cjs.map +1 -0
- package/dist/storage/persistence.d.ts +8 -0
- 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-CYi9Swpx.cjs +2 -0
- package/dist/{storm-CNZjsw4T.cjs.map → storm-CYi9Swpx.cjs.map} +1 -1
- package/dist/{storm-Daq2jGHU.js → storm-VR024_QN.js} +4 -5
- package/dist/{storm-Daq2jGHU.js.map → storm-VR024_QN.js.map} +1 -1
- package/dist/transport/headers.d.ts +8 -0
- package/dist/transport/http-transport.d.ts +2 -6
- package/dist/transport/serializers/otlp.d.ts +14 -0
- package/dist/transport/status-transport.d.ts +5 -2
- package/dist/transport/worker-client.d.ts +14 -0
- package/dist/transport/worker-entry.d.ts +5 -0
- package/dist/transport/worker-protocol.d.ts +36 -0
- package/dist/transport/worker-server.d.ts +3 -0
- package/dist/transport/worker-transport.d.ts +9 -0
- 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-CwcUhFOn.js +62 -0
- package/dist/unclean-exit-CwcUhFOn.js.map +1 -0
- package/dist/unclean-exit-DFUN57wY.cjs +2 -0
- package/dist/unclean-exit-DFUN57wY.cjs.map +1 -0
- package/dist/user-timing-C9kfRq3J.cjs +2 -0
- package/dist/user-timing-C9kfRq3J.cjs.map +1 -0
- package/dist/user-timing-_jZIhDKI.js +63 -0
- package/dist/user-timing-_jZIhDKI.js.map +1 -0
- package/dist/{web-socket-BacvKOvD.cjs → web-socket-BWUoqBh8.cjs} +2 -2
- package/dist/{web-socket-BacvKOvD.cjs.map → web-socket-BWUoqBh8.cjs.map} +1 -1
- package/dist/{web-socket-CpsD8WAa.js → web-socket-CV7yIMnm.js} +7 -8
- package/dist/{web-socket-CpsD8WAa.js.map → web-socket-CV7yIMnm.js.map} +1 -1
- package/dist/{web-vitals-Bflr5jSA.js → web-vitals-Bq4WFHQo.js} +2 -3
- package/dist/{web-vitals-Bflr5jSA.js.map → web-vitals-Bq4WFHQo.js.map} +1 -1
- package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -1
- package/dist/worker-protocol-Bai7GAIA.cjs +2 -0
- package/dist/worker-protocol-Bai7GAIA.cjs.map +1 -0
- package/dist/worker-protocol-CrsdSDLn.js +49 -0
- package/dist/worker-protocol-CrsdSDLn.js.map +1 -0
- package/dist/worker-server-BrIYkfoa.cjs +2 -0
- package/dist/worker-server-BrIYkfoa.cjs.map +1 -0
- package/dist/worker-server-Dp5HYm4b.js +83 -0
- package/dist/worker-server-Dp5HYm4b.js.map +1 -0
- package/dist/worker-transport-Bwej4N2e.cjs +2 -0
- package/dist/worker-transport-Bwej4N2e.cjs.map +1 -0
- package/dist/worker-transport-D6jtgpqN.js +199 -0
- package/dist/worker-transport-D6jtgpqN.js.map +1 -0
- package/package.json +31 -41
- package/dist/bus-BW6N-pY8.cjs +0 -2
- package/dist/bus-BW6N-pY8.cjs.map +0 -1
- package/dist/bus-DeOPHWaD.js.map +0 -1
- package/dist/console-Ce6heqZZ.cjs +0 -2
- package/dist/console-Ce6heqZZ.cjs.map +0 -1
- package/dist/constants-CN7GE1Lt.js +0 -246
- package/dist/constants-CN7GE1Lt.js.map +0 -1
- package/dist/constants-CW-MlHdY.cjs +0 -2
- package/dist/constants-CW-MlHdY.cjs.map +0 -1
- package/dist/interactions-BUDLxbv1.js +0 -74
- package/dist/interactions-BUDLxbv1.js.map +0 -1
- package/dist/interactions-NHbLKrqe.cjs +0 -2
- package/dist/interactions-NHbLKrqe.cjs.map +0 -1
- package/dist/library-request-BKOcaKtQ.js +0 -25
- package/dist/network-CF8UO5PK.cjs +0 -2
- package/dist/network-CF8UO5PK.cjs.map +0 -1
- package/dist/network-DdzXDI3J.js.map +0 -1
- package/dist/openfin-BwEN0uj4.js +0 -8
- package/dist/remote-rules-DIcC5vVC.js +0 -91
- package/dist/remote-rules-DIcC5vVC.js.map +0 -1
- package/dist/remote-rules-DpFmOef2.cjs +0 -2
- package/dist/remote-rules-DpFmOef2.cjs.map +0 -1
- package/dist/sampling-BVjspJWu.cjs +0 -2
- package/dist/sampling-BVjspJWu.cjs.map +0 -1
- package/dist/sampling-Cm3WhI0a.js +0 -76
- package/dist/sampling-Cm3WhI0a.js.map +0 -1
- package/dist/sanitize-C-ahCFsG.js +0 -123
- package/dist/sanitize-C-ahCFsG.js.map +0 -1
- package/dist/sanitize-DHucKGdi.cjs +0 -2
- package/dist/sanitize-DHucKGdi.cjs.map +0 -1
- package/dist/sender-D3fRCR8d.cjs +0 -3
- package/dist/sender-D3fRCR8d.cjs.map +0 -1
- package/dist/sender-DUUmSglb.js.map +0 -1
- package/dist/storage-w7Tslvlq.js.map +0 -1
- package/dist/storm-CNZjsw4T.cjs +0 -2
- package/dist/types-BR9t_w28.js.map +0 -1
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import { ht as e } from "./constants-CN7GE1Lt.js";
|
|
2
|
-
import { n as t, t as n } from "./error-like-Ywo5uRHo.js";
|
|
3
|
-
import { t as r } from "./global-scope-dp2jADRl.js";
|
|
4
|
-
//#region src/utils/library-console.ts
|
|
5
|
-
var i = r(e);
|
|
6
|
-
function a(e) {
|
|
7
|
-
return i.run(e);
|
|
8
|
-
}
|
|
9
|
-
function o() {
|
|
10
|
-
return i.open();
|
|
11
|
-
}
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/utils/sanitize.ts
|
|
14
|
-
function s(e, t) {
|
|
15
|
-
if (e.length <= t) return e;
|
|
16
|
-
let n = c(e.charCodeAt(t - 1)) ? t - 1 : t;
|
|
17
|
-
return `${e.slice(0, n)}… [truncated ${String(e.length - n)} chars]`;
|
|
18
|
-
}
|
|
19
|
-
function c(e) {
|
|
20
|
-
return e >= 55296 && e <= 56319;
|
|
21
|
-
}
|
|
22
|
-
function l(e) {
|
|
23
|
-
return `[Element ${(e.nodeName ?? "NODE").toLowerCase()}${e.id ? `#${e.id}` : ""}${typeof e.className == "string" && e.className ? `.${e.className.trim().split(/\s+/).slice(0, 3).join(".")}` : ""}]`;
|
|
24
|
-
}
|
|
25
|
-
function u(e, t, n) {
|
|
26
|
-
return d(e, t, n).value;
|
|
27
|
-
}
|
|
28
|
-
function d(e, t, n) {
|
|
29
|
-
let r = {
|
|
30
|
-
bytes: 0,
|
|
31
|
-
nodes: 0,
|
|
32
|
-
diagnostics: n
|
|
33
|
-
};
|
|
34
|
-
return {
|
|
35
|
-
value: p(e, t, /* @__PURE__ */ new WeakSet(), 0, r),
|
|
36
|
-
bytes: r.bytes
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
function f(e, t) {
|
|
40
|
-
return t.bytes += m(e) + 2, e;
|
|
41
|
-
}
|
|
42
|
-
function p(e, r, i, a, o) {
|
|
43
|
-
if (o.nodes++, o.nodes > r.maxNodes) return f("[MaxNodes]", o);
|
|
44
|
-
if (e == null) return o.bytes += 4, e;
|
|
45
|
-
if (typeof e == "string") return f(s(e, r.maxAttributeChars), o);
|
|
46
|
-
if (typeof e == "number") return o.bytes += 8, Number.isFinite(e) ? e : String(e);
|
|
47
|
-
if (typeof e == "boolean") return o.bytes += 5, e;
|
|
48
|
-
if (typeof e == "bigint") return f(`${e.toString()}n`, o);
|
|
49
|
-
if (typeof e == "symbol") return f(e.toString(), o);
|
|
50
|
-
if (typeof e == "function") return f(`[Function ${e.name === "" ? "anonymous" : e.name}]`, o);
|
|
51
|
-
if (a >= r.maxDepth) return f("[MaxDepth]", o);
|
|
52
|
-
if (i.has(e)) return f("[Circular]", o);
|
|
53
|
-
i.add(e), o.bytes += 2;
|
|
54
|
-
try {
|
|
55
|
-
if (e instanceof Error || Object.prototype.toString.call(e) === "[object Error]") {
|
|
56
|
-
let c = e, l = {}, u = 0;
|
|
57
|
-
for (let e of Object.keys(c)) {
|
|
58
|
-
let r = c[e];
|
|
59
|
-
!n.has(e) && t(r) && (l[e] = r, u++);
|
|
60
|
-
}
|
|
61
|
-
return {
|
|
62
|
-
name: f(c.name, o),
|
|
63
|
-
message: f(s(c.message, r.maxAttributeChars), o),
|
|
64
|
-
stack: c.stack ? f(s(c.stack, r.maxStackChars), o) : void 0,
|
|
65
|
-
cause: c.cause ? p(c.cause, r, i, a + 1, o) : void 0,
|
|
66
|
-
data: u > 0 ? p(l, r, i, a + 1, o) : void 0
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
if (e instanceof Date) return f(e.toISOString(), o);
|
|
70
|
-
if (e instanceof RegExp) return f(e.toString(), o);
|
|
71
|
-
if (e instanceof Map) {
|
|
72
|
-
let t = e, n = {}, s = 0;
|
|
73
|
-
for (let [e, c] of t) {
|
|
74
|
-
if (s >= r.maxArrayLength) {
|
|
75
|
-
n["…"] = f(`[${String(t.size - r.maxArrayLength)} more entries]`, o);
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
s++;
|
|
79
|
-
let l = String(e);
|
|
80
|
-
o.bytes += m(l) + 4, n[l] = p(c, r, i, a + 1, o);
|
|
81
|
-
}
|
|
82
|
-
return n;
|
|
83
|
-
}
|
|
84
|
-
if (e instanceof Set) return p([...e].slice(0, r.maxArrayLength), r, i, a, o);
|
|
85
|
-
if (ArrayBuffer.isView(e)) {
|
|
86
|
-
let t = e.length ?? 0;
|
|
87
|
-
return f(`[${e.constructor.name}(${String(t)})]`, o);
|
|
88
|
-
}
|
|
89
|
-
if (e instanceof Promise) return f("[Promise]", o);
|
|
90
|
-
if (typeof Node < "u" && e instanceof Node) return f(l(e), o);
|
|
91
|
-
if (Array.isArray(e)) {
|
|
92
|
-
let t = e, n = t.slice(0, r.maxArrayLength).map((e) => p(e, r, i, a + 1, o));
|
|
93
|
-
return t.length > r.maxArrayLength && n.push(f(`[${String(t.length - r.maxArrayLength)} more items]`, o)), n;
|
|
94
|
-
}
|
|
95
|
-
let c = e.toJSON;
|
|
96
|
-
if (typeof c == "function") return p(c.call(e), r, i, a + 1, o);
|
|
97
|
-
let u = e, d = Object.keys(u), h = {}, g = 0;
|
|
98
|
-
for (let e of d) {
|
|
99
|
-
if (g >= r.maxAttributeCount) {
|
|
100
|
-
h["…"] = f(`[${String(d.length - g)} more keys]`, o);
|
|
101
|
-
break;
|
|
102
|
-
}
|
|
103
|
-
g++, o.bytes += m(e) + 4, h[e] = p(u[e], r, i, a + 1, o);
|
|
104
|
-
}
|
|
105
|
-
return h;
|
|
106
|
-
} catch (e) {
|
|
107
|
-
return o.diagnostics.count("record.sanitize_failed"), f(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, o);
|
|
108
|
-
} finally {
|
|
109
|
-
i.delete(e);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
function m(e) {
|
|
113
|
-
let t = 0;
|
|
114
|
-
for (let n = 0; n < e.length; n++) {
|
|
115
|
-
let r = e.charCodeAt(n);
|
|
116
|
-
r < 128 ? t += 1 : r < 2048 ? t += 2 : r >= 55296 && r <= 56319 ? (t += 4, n++) : t += 3;
|
|
117
|
-
}
|
|
118
|
-
return t;
|
|
119
|
-
}
|
|
120
|
-
//#endregion
|
|
121
|
-
export { o as a, s as i, u as n, a as o, d as r, m as t };
|
|
122
|
-
|
|
123
|
-
//# sourceMappingURL=sanitize-C-ahCFsG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-C-ahCFsG.js","names":["set","toJson","LIBRARY_CONSOLE_KEY","isDataField","ERROR_OWN_KEYS","globalScope","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/library-console.ts","../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/library-console.ts\n//\n// Marks the console calls that the library makes itself. The console capture skips a call inside\n// this scope. Without the scope, the capture records each mirrored line again, and the loop does\n// not stop.\n\nimport { LIBRARY_CONSOLE_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library console calls. */\nconst scope = globalScope(LIBRARY_CONSOLE_KEY);\n\n/**\n * Runs a function inside the library console scope.\n * @param fn Function that writes to the console.\n * @returns The return value of the function.\n */\nexport function runAsLibraryConsole<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library console scope is open.\n * @returns True while the library writes to the console.\n */\nexport function isLibraryConsole(): boolean {\n return scope.open();\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Tests if a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. If not, a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":";;;;AAUA,IAAMM,IAAQD,EAAYH,CAAmB;AAO7C,SAAgBK,EAAuB,GAAgB;CACrD,OAAOD,EAAM,IAAIE,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOH,EAAM,KAAK;AACpB;;;ACgBA,SAAgBI,EAAS,GAAe,GAAqB;CAC3D,IAAIC,EAAM,UAAUC,GAClB,OAAOD;CAKT,IAAME,IAAMC,EAAgBH,EAAM,WAAWC,IAAM,CAAC,CAAC,IAAIA,IAAM,IAAIA;CACnE,OAAO,GAAGD,EAAM,MAAM,GAAGE,CAAG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AAK,CAAC,GAElFa;EACT;EAEA,IAAMO,IAAwB/B,EAA+B;EAC7D,IAAI,OAAO+B,KAAgB,YAEzB,OAAOnB,EAAKtB,EAAO,KAAKU,CAAK,GAAGS,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAGhE,IAAMqB,IAAShC,GACTiC,IAAO,OAAO,KAAKD,CAAM,GACzBR,IAA+B,CAAC,GAClCU,IAAQ;EACZ,KAAK,IAAMb,KAAOY,GAAM;GACtB,IAAIC,KAASzB,EAAO,mBAAmB;IACrC,EAAI,OAAOI,EAAQ,IAAI,OAAOoB,EAAK,SAASC,CAAK,EAAE,cAAcvB,CAAK;IACtE;GACF;GAGA,AAFA,KACA,EAAM,SAASG,EAAcO,CAAG,IAAA,GAChC,EAAIA,KAAOT,EAAKoB,EAAOX,IAAMZ,GAAQQ,GAAMD,IAAQ,GAAGL,CAAK;EAC7D;EACA,OAAOa;CACT,SAASN,GAAO;EAKd,OAFAP,EAAM,YAAY,MAAM,wBAAwB,GAEzCE,EAAQ,oBADFK,aAAiB,QAAQA,EAAM,OAAO,QACX,IAAIP,CAAK;CACnD,UAAU;EAGR,EAAK,OAAOX,CAAK;CACnB;AACF;AAOA,SAAgBc,EAAc,GAAuB;CACnD,IAAIqB,IAAQ;CACZ,KAAK,IAAIC,IAAI,GAAGA,IAAIpC,EAAM,QAAQ,KAAK;EACrC,IAAMI,IAAOJ,EAAM,WAAWoC,CAAC;EAC/B,AAAIhC,IAAA,MACF,KAAS,IACAA,IAAA,OACT,KAAS,IACAA,KAAA,SAA8BA,KAAA,SACvC,KAAS,GACT,OAEA,KAAS;CAEb;CACA,OAAO+B;AACT"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CW-MlHdY.cjs"),t=require("./error-like-gGRx2s36.cjs");var n=require("./global-scope-BN-Io_yv.cjs").t(e.ht);function r(e){return n.run(e)}function i(){return n.open()}function a(e,t){if(e.length<=t)return e;let n=o(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function o(e){return e>=55296&&e<=56319}function s(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function c(e,t,n){return l(e,t,n).value}function l(e,t,n){let r={bytes:0,nodes:0,diagnostics:n};return{value:d(e,t,new WeakSet,0,r),bytes:r.bytes}}function u(e,t){return t.bytes+=f(e)+2,e}function d(e,n,r,i,o){if(o.nodes++,o.nodes>n.maxNodes)return u(`[MaxNodes]`,o);if(e==null)return o.bytes+=4,e;if(typeof e==`string`)return u(a(e,n.maxAttributeChars),o);if(typeof e==`number`)return o.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return o.bytes+=5,e;if(typeof e==`bigint`)return u(`${e.toString()}n`,o);if(typeof e==`symbol`)return u(e.toString(),o);if(typeof e==`function`)return u(`[Function ${e.name===``?`anonymous`:e.name}]`,o);if(i>=n.maxDepth)return u(`[MaxDepth]`,o);if(r.has(e))return u(`[Circular]`,o);r.add(e),o.bytes+=2;try{if(e instanceof Error||Object.prototype.toString.call(e)===`[object Error]`){let s=e,c={},l=0;for(let e of Object.keys(s)){let n=s[e];!t.t.has(e)&&t.n(n)&&(c[e]=n,l++)}return{name:u(s.name,o),message:u(a(s.message,n.maxAttributeChars),o),stack:s.stack?u(a(s.stack,n.maxStackChars),o):void 0,cause:s.cause?d(s.cause,n,r,i+1,o):void 0,data:l>0?d(c,n,r,i+1,o):void 0}}if(e instanceof Date)return u(e.toISOString(),o);if(e instanceof RegExp)return u(e.toString(),o);if(e instanceof Map){let t=e,a={},s=0;for(let[e,c]of t){if(s>=n.maxArrayLength){a[`…`]=u(`[${String(t.size-n.maxArrayLength)} more entries]`,o);break}s++;let l=String(e);o.bytes+=f(l)+4,a[l]=d(c,n,r,i+1,o)}return a}if(e instanceof Set)return d([...e].slice(0,n.maxArrayLength),n,r,i,o);if(ArrayBuffer.isView(e)){let t=e.length??0;return u(`[${e.constructor.name}(${String(t)})]`,o)}if(e instanceof Promise)return u(`[Promise]`,o);if(typeof Node<`u`&&e instanceof Node)return u(s(e),o);if(Array.isArray(e)){let t=e,a=t.slice(0,n.maxArrayLength).map(e=>d(e,n,r,i+1,o));return t.length>n.maxArrayLength&&a.push(u(`[${String(t.length-n.maxArrayLength)} more items]`,o)),a}let c=e.toJSON;if(typeof c==`function`)return d(c.call(e),n,r,i+1,o);let l=e,p=Object.keys(l),m={},h=0;for(let e of p){if(h>=n.maxAttributeCount){m[`…`]=u(`[${String(p.length-h)} more keys]`,o);break}h++,o.bytes+=f(e)+4,m[e]=d(l[e],n,r,i+1,o)}return m}catch(e){return o.diagnostics.count(`record.sanitize_failed`),u(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,o)}finally{r.delete(e)}}function f(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return f}});
|
|
2
|
-
//# sourceMappingURL=sanitize-DHucKGdi.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-DHucKGdi.cjs","names":["globalScope","LIBRARY_CONSOLE_KEY","ERROR_OWN_KEYS","isDataField","set","toJson","require_constants","require_error_like","scope","runAsLibraryConsole","fn","isLibraryConsole","truncate","value","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","diagnostics","state","walk","counted","estimateBytes","text","depth","seen","error","extra","extraCount","key","field","map","out","shown","entry","name","length","items","item","maybeToJson","record","keys","count","bytes","i"],"sources":["../src/utils/library-console.ts","../src/utils/sanitize.ts"],"sourcesContent":["// src/utils/library-console.ts\n//\n// Marks the console calls that the library makes itself. The console capture skips a call inside\n// this scope. Without the scope, the capture records each mirrored line again, and the loop does\n// not stop.\n\nimport { LIBRARY_CONSOLE_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library console calls. */\nconst scope = globalScope(LIBRARY_CONSOLE_KEY);\n\n/**\n * Runs a function inside the library console scope.\n * @param fn Function that writes to the console.\n * @returns The return value of the function.\n */\nexport function runAsLibraryConsole<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library console scope is open.\n * @returns True while the library writes to the console.\n */\nexport function isLibraryConsole(): boolean {\n return scope.open();\n}\n","// src/utils/sanitize.ts\n//\n// Converts arbitrary data into JSON-safe structures. It detects cycles and estimates\n// the byte size. It never throws. It never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { ERROR_OWN_KEYS, isDataField } from \"./error-like\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Tests if a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n /** Diagnostics reporter. It counts a value that throws during the walk. */\n diagnostics: Diagnostics;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): unknown {\n return sanitizeWithSize(value, limits, diagnostics).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @param diagnostics Diagnostics reporter. It counts a value that throws during the walk.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(\n value: unknown,\n limits: SanitizeLimits,\n diagnostics: Diagnostics,\n): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0, diagnostics };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Walks an object tree recursively. It replaces cyclic references, hostile getters, and\n * invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits do not bound a wide tree. 128 keys over 6 levels give 128^6\n // values. The walk visits all of them synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n // An Error from another realm fails instanceof. Its built-in tag still names an Error.\n if (value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\") {\n const error = value as Error;\n // Keep the own fields of the error, for example a code or an HTTP status.\n const extra: Record<string, unknown> = {};\n let extraCount = 0;\n for (const key of Object.keys(error)) {\n const field = (error as unknown as Record<string, unknown>)[key];\n if (!ERROR_OWN_KEYS.has(key) && isDataField(field)) {\n extra[key] = field;\n extraCount++;\n }\n }\n\n return {\n name: counted(error.name, state),\n message: counted(truncate(error.message, limits.maxAttributeChars), state),\n stack: error.stack\n ? counted(truncate(error.stack, limits.maxStackChars), state)\n : undefined,\n cause: error.cause ? walk(error.cause, limits, seen, depth + 1, state) : undefined,\n data: extraCount > 0 ? walk(extra, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catch hostile getters and throwing proxies. A failure replaces one attribute,\n // not the full record. Count the fault. A report on each attribute is noise.\n state.diagnostics.count(\"record.sanitize_failed\");\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Remove the object from the ancestor set on unwind. If not, a repeated sibling\n // shows as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n"],"mappings":"mFAUA,IAAMQ,uCAAQR,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAO7C,SAAgBQ,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB,CCgBA,SAAgBI,EAAS,EAAe,EAAqB,CAC3D,GAAIC,EAAM,QAAUC,EAClB,OAAOD,EAKT,IAAME,EAAMC,EAAgBH,EAAM,WAAWC,EAAM,CAAC,CAAC,EAAIA,EAAM,EAAIA,EACnE,MAAO,GAAGD,EAAM,MAAM,EAAGE,CAAG,EAAE,eAAe,OAAOF,EAAM,OAASE,CAAG,EAAE,QAC1E,CAOA,SAASC,EAAgB,EAAuB,CAC9C,OAAOC,GAAA,OAA8BA,GAAA,KACvC,CAcA,SAASC,EAAa,EAAwB,CAO5C,MAAO,aANMC,EAAK,UAAY,OAAA,CAAQ,YAMnB,IALRA,EAAK,GAAK,IAAIA,EAAK,KAAO,KAEnC,OAAOA,EAAK,WAAc,UAAYA,EAAK,UACvC,IAAIA,EAAK,UAAU,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAAG,IAC9E,GAC4B,EACpC,CA2BA,SAAgBC,EACd,EACA,EACA,EACS,CACT,OAAOC,EAAiBR,EAAOS,EAAQC,CAAW,CAAC,CAAC,KACtD,CASA,SAAgBF,EACd,EACA,EACA,EACgB,CAChB,IAAMG,EAAmB,CAAE,MAAO,EAAG,MAAO,EAAG,aAAY,EAE3D,MAAO,CAAE,MADMC,EAAKZ,EAAOS,EAAQ,IAAI,QAAW,EAAGE,CACrC,EAAQ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,CACnD,QAAU,CAGRM,EAAK,OAAOjB,CAAK,CACnB,CACF,CAOA,SAAgBc,EAAc,EAAuB,CACnD,IAAIqB,EAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIpC,EAAM,OAAQ,IAAK,CACrC,IAAMI,EAAOJ,EAAM,WAAWoC,CAAC,EAC3BhC,EAAA,IACF,GAAS,EACAA,EAAA,KACT,GAAS,EACAA,GAAA,OAA8BA,GAAA,OACvC,GAAS,EACT,KAEA,GAAS,CAEb,CACA,OAAO+B,CACT"}
|
package/dist/sender-D3fRCR8d.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CW-MlHdY.cjs"),t=require("./sampling-BVjspJWu.cjs"),n=require("./deadline-XSnm95pg.cjs"),r=require("./sanitize-DHucKGdi.cjs"),i=require("./identity-Da9TkuKd.cjs"),a=require("./library-request-BaZOi4eg.cjs"),o=require("./openfin-DtH2f7zX.cjs"),s=require("./platform-DBSKTvFn.cjs"),c=require("./batch-BQFtb3i5.cjs"),l=require("./remote-rules-DpFmOef2.cjs"),u=require("./storage-BA9RqRO-.cjs"),d=require("./emergency-queue-Cs1hrjsC.cjs"),f=require("./factory-CNj4DH3n.cjs"),ee=require("./context-storage-BjzeBSxH.cjs");var p=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i,a){super(t,a===void 0?void 0:{cause:a}),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function m(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.Tt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var h={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},g=new Set([e.r,...Object.keys(h)]);function _(t){return e.Dt.test(t)?Number(BigInt(t)/e.Ot):Date.now()}function v(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function y(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function b(e,t,n,r){let i=v(n);if(i!==null)y(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)b(e,t,i,r);else for(let[i,a]of Object.entries(n))b(e,`${t}.${i}`,a,r);r.delete(n)}}function x(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))b(t,r,i,n);return t}function S(e){let t=[];for(let[n,r]of Object.entries(h)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function C(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(g.has(e)&&typeof t==`string`)))}var te={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=_(t.timeUnixNano),{attributes:r}=t,i=r[e.r];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.U},log:{level:e.H[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:S(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Gt],version:t.resource[e.Kt],environment:t.resource[e.Vt]},user_agent:{original:t.resource[e.zt]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...x(t.resource),...x(C(r))}})}).join(`
|
|
2
|
-
`)}\n`,contentType:e.F}}};function w(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isSafeInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(w).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:T(e)}}:null}function T(e){let t=[];for(let[n,r]of Object.entries(e)){let e=w(r);e&&t.push({key:n,value:e})}return t}var E=new WeakMap;function D(e){let t=E.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return E.set(e,n),n}function O(e){let t=new Map;for(let n of e){let e=D(n.resource),r=t.get(e);r?r.records.push(n):t.set(e,{resource:n.resource,records:[n]})}return[...t.values()]}var k={name:e.tn,serialize(t){let n=O(t).map(t=>({resource:{attributes:T(t.resource)},scopeLogs:[{scope:{name:e._n,version:e.vn},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:T(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:n}),contentType:e.P}}},A=1;function j(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function M(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function N(t){let n=t.attributes[e.Ct.attributeKeys],r={};if(!Array.isArray(n))return r;for(let e of n){let n=typeof e==`string`&&!e.startsWith(`metric.`)?t.attributes[e]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[e]=n)}return r}function ne(t){let n=j(t,e.Ct.count);if(n===void 0){let e=j(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.Ct.bounds],i=t.attributes[e.Ct.buckets];if(!M(r)||!M(i)||i.length!==r.length+1)return null;let a=j(t,e.Ct.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:j(t,e.Ct.sum),min:a,max:j(t,e.Ct.max),bucketCounts:i.map(String),explicitBounds:r}}function re(e){let t=j(e,`metric.value`);return t===void 0?null:{asDouble:t}}function ie(t,n){let r=t.attributes[e.Ct.start],i=n===`histogram`?ne(t):re(t);return i===null?null:{attributes:T(N(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function P({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:A,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var F={name:e.tn,serialize(t){let n=O(t).map(t=>{let n=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],r=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=ie(e,r);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:r,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=n.get(c)??s;l.points.push(i),n.set(c,l)}return{resource:{attributes:T(t.resource)},scopeMetrics:[{scope:{name:e._n,version:e.vn},metrics:[...n.values()].map(P)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.P}}},I={internal:1,client:3},L=2,R=0,z=new Set([e.f,...Object.values(e.on)]);function B(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function V(t){let n=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!z.has(e))),r=B(t,e.on.parentId);return{traceId:t.traceId,spanId:t.spanId,...r?{parentSpanId:r}:{},name:t.body,kind:B(t,e.on.kind)===`client`?I.client:I.internal,startTimeUnixNano:B(t,e.on.start)??t.timeUnixNano,endTimeUnixNano:B(t,e.on.end)??t.timeUnixNano,attributes:T(n),status:{code:B(t,e.on.status)===`error`?L:R}}}var H={name:e.tn,serialize(t){let n=O(t).map(t=>({resource:{attributes:T(t.resource)},scopeSpans:[{scope:{name:e._n,version:e.vn},spans:t.records.map(V)}]}));return{body:JSON.stringify({resourceSpans:n}),contentType:e.P}}};function U(e){return e===`otlp`?k:e===`ecs`?te:e}function W(e,t){let n=t=>e.records.length>0&&e.records.every(e=>c.t(e,`log.type`)===t);return t.metricsEndpoint!==``&&n(`metric`)?`metrics`:n(`span`)?`traces`:`logs`}function G(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var K={metrics:F,traces:H};function q(e,t,n,r){try{return(K[W(t,e)]??U(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var J=class{config;diagnostics;onSampling;onLoss;cancellation=new AbortController;stop(){this.cancellation.abort()}assertContext(e){if(this.cancellation.signal.aborted||this.config.securityContext.isolation&&this.config.securityContext.id&&e.routingContextId!==this.config.securityContext.id)throw this.diagnostics.count(`security.context_mismatch`),new p(`permanent`,`The delivery context is inactive or does not match the batch.`)}async untilCancelled(e){if(this.cancellation.signal.aborted)throw new p(`permanent`,`The delivery context retired.`);let t,n=new Promise((e,n)=>{t=()=>{n(new p(`permanent`,`The delivery context retired.`))},this.cancellation.signal.addEventListener(`abort`,t,{once:!0})});try{return await Promise.race([e,n])}finally{this.cancellation.signal.removeEventListener(`abort`,t)}}throttledUntil={logs:0,metrics:0,traces:0};acceptedAt=null;constructor(e,t,n=()=>void 0,r=()=>void 0){this.config=e,this.diagnostics=t,this.onSampling=n,this.onLoss=r}throttledForMs(e){return Math.max(0,this.throttledUntil[W(e,this.config)]-Date.now())}lastSendAt(){return this.acceptedAt}serialize(e){let t=q(this.config,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`);return t||this.onLoss(`unserializable`,e.records,[e.id]),t}accept(e,t){this.throttledUntil[e]=0,this.acceptedAt=Date.now(),this.config.sampling.remote&&t!=null&&this.onSampling(t)}reject(e,t,n,r){let i=String(e);if(e===401||e===403){let t=r.advice===void 0?``:` ${r.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${i}.${t}`,{status:e,endpoint:G(n,this.config)}),new p(`permanent`,`The server rejected the batch with ${i}.`,e)}if(e===413)return new p(`too_large`,`The payload is too large.`,e,void 0,r.maxBytes);if(e===429||e===503){let t=e===429,i=r.retryAfterMs===void 0?void 0:Math.min(r.retryAfterMs,this.config.delivery.retryMaxDelayMs);return this.throttledUntil[n]=Date.now()+(i??this.config.delivery.retryBaseDelayMs),t&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:i}),new p(`throttled`,t?`The server throttles the requests.`:`The service is not available.`,e,i)}return e===408||e>=500?new p(`transient`,`The server returned the error ${i}.`,e):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${i}. The library dropped it.`,{batchId:t,status:e}),new p(`permanent`,`The server rejected the batch with ${i}.`,e))}};function Y(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records,routingContextId:e.routingContextId}}function ae(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isInteger(t)&&t>=100&&t<=599}function X(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var oe=class extends J{async send(e){this.assertContext(e);let{transport:t}=this.config;if(!t||e.records.length===0)return;let i=this.serialize(e);if(!i)return;let o=W(e,this.config),s=Y(e,i,o);s.signal=this.cancellation.signal;let c;try{c=await n.n(this.untilCancelled(a.i(()=>a.r(()=>r.o(()=>t(s))))),this.config.delivery.requestTimeoutMs)}catch(e){let t=e instanceof n.t?e:void 0;throw new p(t?`timeout`:`transient`,t?.message??`The custom transport failed.`,void 0,void 0,void 0,e)}if(this.assertContext(e),!ae(c))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:e.id}),new p(`transient`,`The custom transport returned no valid status.`);let{status:l}=c;if(l>=200&&l<300)this.accept(o,c.sampling);else throw this.reject(l,e.id,o,{retryAfterMs:X(c.retryAfterMs),maxBytes:X(c.maxBytes)})}},se=class{deps;installed=!1;keepaliveBytes=0;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(e){let{config:t,diagnostics:n}=this.deps;if(n.guard(`pipeline.crashed`,`The metric points before the exit flush failed.`,()=>{this.deps.beforeExit?.()}),e===`hidden`){this.flushAlive();return}if(t.transport){this.flushCustom(e,t.transportOnExit);return}let r=this.endpointUrl();if(r!==null){this.keepaliveBytes=0;for(let i of this.deps.drainForExit()){let a=W(i,t),o=a===`logs`?r.href:G(a,t);o?this.flushBatch(i,e,new URL(o)):n.count(`record.dropped_no_destination`)}}}flushBatch(t,n,i){let{config:a}=this.deps;if(t.records.length===0)return;let o=this.serialize(t,n);if(!o)return;if(r.t(o.body)>6e4){this.park(t);return}i.searchParams.set(e.Mt,t.id),i.searchParams.set(e.Nt,n);let s=i.toString(),c=this.deps.exitHeaders();if(c){this.keepaliveFetch(s,t,o.body,n,()=>{let n=new Headers(c);return n.set(e.et,o.contentType),n.set(e.Q,t.id),n});return}if(a.headers){this.park(t);return}let l=this.beacon(s,o.body);l!==`sent`&&(l===`refused`?this.park(t):this.keepaliveFetch(s,t,o.body,n,()=>new Headers({[e.et]:e.I})))}flushAlive(){let{diagnostics:e}=this.deps,t=`The flush of the hidden document failed.`;e.guard(`pipeline.crashed`,t,()=>{Promise.resolve(this.deps.flushAlive()).catch(n=>{e.report(`pipeline.crashed`,t,void 0,n)})})}flushCustom(e,t){let{config:n,diagnostics:r}=this.deps;for(let i of this.deps.drainForExit()){let o=this.serialize(i,e);if(!o)continue;let s=Y(i,o,W(i,n));(t===void 0||r.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>a.r(()=>t(s)))!==!0)&&this.park(i)}}park(e){let{config:t,diagnostics:n,onLoss:r}=this.deps;t.storage===`memory`||t.storage===`none`?r?.(`not_stored`,e.records,[e.id]):d.saveToEmergencyQueue(e,n,r)}serialize(e,t){let n=q(this.deps.config,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`);return n||this.deps.onLoss?.(`unserializable`,e.records,[e.id]),n}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`The sendBeacon call failed.`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(e,t,n,i,a){let{config:o,diagnostics:s}=this.deps,c=()=>{this.park(t)},l=r.t(n);this.keepaliveBytes+l>6e4?c():(this.keepaliveBytes+=l,s.guard(`transport.http_error`,`The keepalive fetch failed.`,()=>(fetch(e,{method:`POST`,body:n,headers:a(),credentials:o.credentials,keepalive:!0}).catch(e=>{s.report(`transport.http_error`,`The exit flush failed.`,{reason:i},e),c()}),!0))!==!0&&c())}};async function ce(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.K)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var le=`In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,ue=class extends J{cachedHeaders;async send(e,t){this.assertContext(e);let{config:n}=this,r=W(e,n),i=G(r,n);i?e.records.length!==0&&await this.post(e,r,i,t):this.diagnostics.count(`record.dropped_no_destination`)}lastHeaders(){let{headers:e}=this.config;if(!e)return;if(typeof e!=`function`)return e;let t=this.cachedHeaders;return t?.source===e&&t.endpoint===this.config.endpoint&&t.metricsEndpoint===this.config.metricsEndpoint&&t.tracesEndpoint===this.config.tracesEndpoint?t.headers:void 0}async post(t,n,r,i){let a=this.serialize(t);if(!a)return;let o=await this.attempt(t,r,a,i);if(this.assertContext(t),this.rejectsCredentials(o.status)&&typeof this.config.headers==`function`&&(this.cachedHeaders=void 0,o=await this.attempt(t,r,a,i),this.assertContext(t)),o.ok){this.accept(n,o.headers.get(e.nt));return}let s=o.status,c=m(o.headers.get(e.tt)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,n,{retryAfterMs:c,maxBytes:l,advice:le})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i){let a=Date.now()+this.config.delivery.requestTimeoutMs,o=new Headers(await this.before(this.resolveHeaders(),a,n));o.set(e.et,r.contentType),o.set(e.Q,t.id),o.set(e.Z,String(t.attempts));let s=await this.before(this.encodeBody(r.body),a,n);this.assertContext(t),typeof s!=`string`&&o.set(e.$,e.K);let c=this.keepalive(s);return c&&i?.(),this.dispatch(n,o,s,a,c)}async before(e,t,r){try{return await n.n(this.untilCancelled(e),Math.max(0,t-Date.now()))}catch{throw this.cancellation.signal.aborted?new p(`permanent`,`The delivery context retired.`):this.timeout(r)}}timeout(e){let t=`The request took longer than ${String(this.config.delivery.requestTimeoutMs)} ms.`;return this.diagnostics.report(`transport.timeout`,t,{endpoint:e}),new p(`timeout`,t)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||r.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>ce(e))??e}async dispatch(e,t,r,i,o){let{config:c}=this,l=new AbortController,u=()=>{l.abort()};this.cancellation.signal.addEventListener(`abort`,u,{once:!0}),this.cancellation.signal.aborted&&l.abort();let d=setTimeout(()=>{l.abort()},Math.max(0,i-Date.now()));n.r(d);try{return await a.r(()=>fetch(e,{method:`POST`,headers:t,body:r,credentials:c.credentials,signal:l.signal,cache:`no-store`,keepalive:o}))}catch{throw this.cancellation.signal.aborted?new p(`permanent`,`The delivery context retired.`):l.signal.aborted?this.timeout(e):new p(s.r()?`transient`:`offline`,`A network error occurred.`)}finally{this.cancellation.signal.removeEventListener(`abort`,u),clearTimeout(d)}}keepalive(e){let t=globalThis.document?.visibilityState===`hidden`,n=typeof e==`string`?r.t(e):e.byteLength;return t&&n<=6e4}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`The library could not read the body of the 413 response.`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;if(!e)return{};if(typeof e!=`function`)return e;let{endpoint:t,metricsEndpoint:n,tracesEndpoint:r}=this.config,i=await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()));return i&&(this.cachedHeaders={source:e,endpoint:t,metricsEndpoint:n,tracesEndpoint:r,headers:i}),i??{}}},de=class{storage;transport;diagnostics;config;batchesPerDrain;onLoss;timer=null;attempt=0;draining=!1;stopped=!1;maxAttempts;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i,a=()=>void 0){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i,this.onLoss=a,this.maxAttempts=u.storageLimits(r.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(this.config.delivery.retryIdleDelayMs)}nudge(){this.draining||this.schedule(this.config.delivery.retryBaseDelayMs)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}async flush(){this.stopped=!1;try{await this.drain()}finally{this.stop()}}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,n.r(t)}bounded(t){return n.n(t,e.cn)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let e=Math.min(this.config.delivery.retryBaseDelayMs*2**this.attempt,this.config.delivery.retryMaxDelayMs);return Math.random()*e}async drain(){if(!this.draining){this.draining=!0;try{let t=d.t(e.B,this.config.persistence.namespace);await d.n(t,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(this.config.delivery.retryIdleDelayMs)}finally{this.draining=!1}}}async drainLocked(){try{if(!s.r())return this.schedule(this.config.delivery.retryIdleDelayMs),!0;let e=await this.bounded(this.storage.take(this.batchesPerDrain??this.config.delivery.batchesPerDrain));if(e.length===0)return this.schedule(this.config.delivery.retryIdleDelayMs),!0;let t=new Set,n=0;for(let r of e){if(this.stopped)return!0;let e=W(r,this.config);if(t.has(e))continue;let i=await this.deliver(r);if(i===`stop`)return!0;i!==`next`&&(t.add(e),n=Math.max(n,i))}return t.size>0?this.schedule(n):this.schedule(e.length===(this.batchesPerDrain??this.config.delivery.batchesPerDrain)?0:this.config.delivery.retryIdleDelayMs),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(e){if(e.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${e.attempts.toString()} attempts.`,{batchId:e.id,records:e.records.length}),this.onLoss(`max_attempts`,e.records,[e.id]),await this.bounded(this.storage.remove(e.id)),`next`;try{return await this.transport.send(e),await this.bounded(this.storage.remove(e.id)),this.attempt=0,`next`}catch(t){if(this.stopped)return`stop`;let n=t instanceof p?t:void 0;return n?.kind===`permanent`||n?.kind===`too_large`?(await this.replaceStored(e,t),`next`):n?.kind===`offline`?(this.schedule(this.config.delivery.retryIdleDelayMs),`stop`):n?.kind===`throttled`?(this.attempt++,n.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(e.id,e.attempts+1)),this.attempt++,n?.retryAfterMs??this.backoffMs())}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof p?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=c.a(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),this.onLoss(`rejected`,e.records,[e.id]),[])}},Z=[`metrics`,`logs`,`traces`];function Q(t){let n=t.attributes[e.f];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}var $=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}get size(){return this.pending.length}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,n.r(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},fe=class{transport;storage;retry;diagnostics;routingContextId;policy;onLoss;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;held=new Map;heldBytes=0;persisting=!1;release(e){for(let t of e)this.heldBytes-=this.held.get(t)??0,this.held.delete(t)}evict(){let e=this.queue.shift();if(e)return this.open.delete(e),this.unconfirmed.delete(e.batch.id),this.release(e.batch.records),e.resolve(),this.onLoss(`buffer_full`,e.batch.records,[e.batch.id]),!0;for(let e of Object.values(this.streams)){let t=e.take();if(t.length)return this.release(t),this.onLoss(`buffer_full`,t),!0}return!1}admit(e){if(!this.policy)return!0;let{maxPendingRecords:t,maxPendingBytes:n,overflow:i}=this.policy.buffering,a;try{a=r.t(JSON.stringify(e))}catch{return this.onLoss(`unserializable`,[e]),!1}let o=()=>!!(t&&this.held.size>=t||n&&this.heldBytes+a>n),s=!n||a<=n;for(;s&&o()&&i===`drop-oldest`&&this.evict(););if(o()){if(i===`persist`&&!this.persisting){this.persisting=!0;let t=this.toBatch([e]);this.diagnostics.guardAsync(`storage.degraded`,`Could not persist an overflow record.`,async()=>{try{await this.storage.save(t),this.retry.nudge()}finally{this.persisting=!1}})}else this.onLoss(`buffer_full`,[e]);return!1}return this.held.set(e,a),this.heldBytes+=a,!0}constructor(e,t,n,r,i,a,o,s=()=>void 0){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r,this.routingContextId=a,this.policy=o,this.onLoss=s;let c=e=>{this.claim(e)};this.streams={logs:new $(i.logs,c),metrics:new $(i.metrics,c),traces:new $(i.traces,c)}}push(e){if(this.stopped)return;e.observedTimeUnixNano=t.l();let n={...e};this.admit(n)&&this.route(n)}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.held.clear(),this.heldBytes=0,Z.map(t=>this.toBatch([...e.filter(e=>Q(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(){if(!this.stopped)for(let e of Z)this.claim(this.streams[e]);await Promise.all([...this.open].map(e=>e.done))}counts(){let e=e=>{let t=0;for(let n of e)t+=n.batch.records.length;return t},t=e(this.queue);return{pending:Z.reduce((e,t)=>e+this.streams[t].size,0)+t,inFlight:e(this.open)-t}}destroy(){this.stopped=!0,this.held.clear(),this.heldBytes=0;for(let e of Z)this.streams[e].stop();this.queue.length=0;for(let e of this.open)e.resolve();this.open.clear()}toBatch(e){return e.length===0?null:{id:i.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0,routingContextId:this.routingContextId?.(),persistenceNamespace:this.policy?.persistence.namespace}}route(e){try{let t=this.streams[Q(e)];if(!this.ceiling.allow(e,this.policy?.capturePolicy.errorCeiling,this.policy?.capturePolicy.windowMs)){this.release([e]),this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){this.enqueue(this.toBatch(e.take()))}enqueue(e){if(!e)return;let t,n={batch:e,done:new Promise(e=>{t=e}),resolve:t};this.unconfirmed.set(e.id,e),this.open.add(n),this.queue.push(n),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){if(!this.stopped)for(;this.inFlight<(this.policy?.delivery.maxConcurrentRequests??2);){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){let{batch:t}=e;try{await this.dispatch(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:t.id},e)}finally{this.release(t.records),this.inFlight--,this.open.delete(e),e.resolve(),this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs(e);if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`The server throttles requests. The pipeline stored the batch and did not send it.`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e,()=>{this.unconfirmed.delete(e.id)})}catch(t){if(this.stopped)return;await this.storeFailed({...e,attempts:e.attempts+1},t),this.diagnostics.report(`transport.http_error`,`The send failed. The pipeline stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await this.retry.storeFailed(e,t)})}async store(t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await n.n(this.storage.save(t),e.cn),this.retry.nudge()})}},pe=class e{storage;retry;pipeline;exitFlush;diagnostics;transport;retired=!1;emergencyImport=Promise.resolve();constructor(e,t,n,r,i,a){this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i,this.transport=a}static async create(t){let{config:n,diagnostics:r}=t,i=t.storage??await f.createStorage(n.storage,f.storageName(n.persistence.namespace),u.storageLimits(n.retention),r,t.onGap,n.persistence.namespace);t.onStorage?.(i);let a=new ee.ContextStorage(i,n.securityContext,n.persistence.namespace),o=e=>{let i=l.n(e,r);i&&l.t(t.remote,n,i)},{onLoss:s}=t,c=n.transport?void 0:new ue(n,r,o,s),d=c??new oe(n,r,o,s),p=new de(a,d,r,n,void 0,s),{batching:m}=n,h=new fe(d,a,p,r,{logs:{flushIntervalMs:m.logFlushIntervalMs,batchSize:m.logBatchSize},metrics:{flushIntervalMs:m.metricFlushIntervalMs,batchSize:m.metricBatchSize},traces:{flushIntervalMs:m.logFlushIntervalMs,batchSize:m.logBatchSize}},()=>n.securityContext.id||void 0,n,s),g=new se({config:n,diagnostics:r,drainForExit:()=>h.drainForExit(),flushAlive:()=>h.flushPending(),exitHeaders:()=>c?.lastHeaders(),onLoss:s,beforeExit:t.beforeExit}),_=!1;try{g.install(),p.start(),_=!0}finally{_||(g.uninstall(),p.stop())}let v=new e(a,p,h,g,r,d);return v.emergencyImport=v.importEmergency(),v}push(e){this.pipeline.push(e)}async flush(){await this.pipeline.flushPending()}async clearPersisted(e,t){e===`namespace`?await this.storage.clearNamespace():await this.storage.clear(),d.clearEmergencyContext(t,this.diagnostics,this.storage.namespace,e===`namespace`)}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}stats(){return{...this.pipeline.counts(),lastSendAt:this.transport.lastSendAt()}}async destroy(){await this.diagnostics.guardAsync(`pipeline.crashed`,`The flush before shutdown failed.`,()=>this.flush()),this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}async retire(e,t,r){if(this.retired=!0,this.exitFlush.uninstall(),this.retry.stop(),e===`flush`)try{await n.n(Promise.all([this.flush(),this.retry.flush()]),t)}catch(e){this.diagnostics.report(`transport.timeout`,`The flush of the old security context did not complete before its time limit.`,void 0,e)}this.retry.stop(),this.transport.stop();let i=this.pipeline.drainForExit(),a=i.flatMap(e=>e.records);this.pipeline.destroy(),await this.emergencyImport;let o=await this.storage.take(2**53-1);if(e===`retain`)for(let e of i)await this.storage.save({...e,routingContextId:r,persistenceNamespace:this.storage.namespace});let s=e===`discard`||e===`flush`;return await this.storage.retire(s),s&&d.clearEmergencyContext(r,this.diagnostics,this.storage.namespace),{buffered:a,stored:o}}async adopt(e,t){for(let n of e)await this.storage.save({...n,attempts:0,routingContextId:t,persistenceNamespace:this.storage.namespace});e.length>0&&this.retry.nudge()}async importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>d.drainEmergencyQueue(this.storage,this.diagnostics,e=>this.storage.accepts(e),this.storage.namespace));!this.retired&&e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=pe;
|
|
3
|
-
//# sourceMappingURL=sender-D3fRCR8d.cjs.map
|