@utk09/ui-observability 0.9.3 → 0.9.5
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 +90 -0
- package/README.md +199 -96
- package/dist/batch-BQFtb3i5.cjs +2 -0
- package/dist/batch-BQFtb3i5.cjs.map +1 -0
- package/dist/{batch-DDgxg16_.js → batch-BUJh-1jZ.js} +6 -4
- package/dist/batch-BUJh-1jZ.js.map +1 -0
- package/dist/bus/bus.d.ts +76 -2
- package/dist/bus/links.d.ts +9 -2
- package/dist/bus/validation.d.ts +7 -0
- package/dist/bus-BW6N-pY8.cjs +2 -0
- package/dist/bus-BW6N-pY8.cjs.map +1 -0
- package/dist/bus-DeOPHWaD.js +647 -0
- package/dist/bus-DeOPHWaD.js.map +1 -0
- package/dist/capture/network.d.ts +1 -0
- package/dist/capture/storm.d.ts +2 -1
- package/dist/capture/types.d.ts +5 -0
- package/dist/capture/web-socket.d.ts +40 -0
- package/dist/{console-BSusX_M-.cjs → console-Ce6heqZZ.cjs} +2 -2
- package/dist/console-Ce6heqZZ.cjs.map +1 -0
- package/dist/{console-Dv5GfaNn.js → console-DbAZYJuy.js} +4 -4
- package/dist/console-DbAZYJuy.js.map +1 -0
- package/dist/constants-CN7GE1Lt.js +246 -0
- package/dist/constants-CN7GE1Lt.js.map +1 -0
- package/dist/constants-CW-MlHdY.cjs +2 -0
- package/dist/constants-CW-MlHdY.cjs.map +1 -0
- package/dist/constants.d.ts +63 -11
- package/dist/context-storage-BjzeBSxH.cjs +2 -0
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
- package/dist/context-storage-DxZf4Gfh.js +52 -0
- package/dist/context-storage-DxZf4Gfh.js.map +1 -0
- package/dist/core/breadcrumbs.d.ts +10 -3
- package/dist/core/context.d.ts +2 -0
- package/dist/core/diagnostics.d.ts +11 -3
- package/dist/core/journey.d.ts +7 -0
- package/dist/core/meter.d.ts +25 -2
- package/dist/core/pipeline.d.ts +41 -6
- package/dist/core/record.d.ts +42 -9
- package/dist/core/remote-sampling.d.ts +7 -3
- package/dist/core/runtime.d.ts +153 -6
- package/dist/core/sampling.d.ts +35 -2
- package/dist/core/sender.d.ts +43 -1
- package/dist/core/spans.d.ts +34 -0
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/emergency-queue-BYUyDHGD.js +69 -0
- package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
- package/dist/{errors-DCZWcHkd.js → errors-BhC7HTSt.js} +8 -9
- package/dist/errors-BhC7HTSt.js.map +1 -0
- package/dist/errors-CgY633cG.cjs +3 -0
- package/dist/errors-CgY633cG.cjs.map +1 -0
- package/dist/factory-C5TujXlU.js +280 -0
- package/dist/factory-C5TujXlU.js.map +1 -0
- package/dist/factory-CNj4DH3n.cjs +2 -0
- package/dist/factory-CNj4DH3n.cjs.map +1 -0
- package/dist/fixed-window-CtaFHanJ.js +12 -0
- package/dist/fixed-window-CtaFHanJ.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs +2 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
- package/dist/identity-8vKkyAWm.js +103 -0
- package/dist/identity-8vKkyAWm.js.map +1 -0
- package/dist/identity-Da9TkuKd.cjs +2 -0
- package/dist/identity-Da9TkuKd.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +66 -6
- package/dist/index.js +1253 -595
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
- package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
- package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-CCA1LvtO.js} +45 -30
- package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
- package/dist/{interactions-BLH_tX87.js → interactions-BUDLxbv1.js} +16 -12
- package/dist/interactions-BUDLxbv1.js.map +1 -0
- package/dist/interactions-NHbLKrqe.cjs +2 -0
- package/dist/interactions-NHbLKrqe.cjs.map +1 -0
- package/dist/{journey-yALMEWF7.js → journey-BUJ4WJxP.js} +37 -34
- package/dist/journey-BUJ4WJxP.js.map +1 -0
- package/dist/journey-B_tTnvac.cjs +2 -0
- package/dist/journey-B_tTnvac.cjs.map +1 -0
- package/dist/keys-BHhw_0Wh.cjs +2 -0
- package/dist/keys-BHhw_0Wh.cjs.map +1 -0
- package/dist/keys-D5r_GH9q.js +17 -0
- package/dist/keys-D5r_GH9q.js.map +1 -0
- package/dist/{library-request-CQD4HUiP.js → library-request-BKOcaKtQ.js} +3 -3
- package/dist/{library-request-CQD4HUiP.js.map → library-request-BKOcaKtQ.js.map} +1 -1
- package/dist/{library-request-BcAxuwsf.cjs → library-request-BaZOi4eg.cjs} +2 -2
- package/dist/{library-request-BcAxuwsf.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
- package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-CF3qiSAX.cjs} +2 -2
- package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
- package/dist/{long-frames-DD_Um9_4.js → long-frames-DI5ypfAF.js} +5 -5
- package/dist/long-frames-DI5ypfAF.js.map +1 -0
- package/dist/models/batch.d.ts +4 -0
- package/dist/models/bus.d.ts +32 -9
- package/dist/models/config.d.ts +401 -12
- package/dist/models/drop.d.ts +1 -1
- package/dist/models/health.d.ts +27 -0
- package/dist/models/log-record.d.ts +1 -1
- package/dist/models/plugin.d.ts +47 -0
- package/dist/models/stats.d.ts +11 -0
- package/dist/models/storage.d.ts +13 -0
- package/dist/network-CF8UO5PK.cjs +2 -0
- package/dist/network-CF8UO5PK.cjs.map +1 -0
- package/dist/{network--GoE7_Or.js → network-DdzXDI3J.js} +47 -31
- package/dist/network-DdzXDI3J.js.map +1 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{platform-GaM6h7XM.js → platform-Bw1btWCT.js} +21 -10
- package/dist/platform-Bw1btWCT.js.map +1 -0
- package/dist/platform-DBSKTvFn.cjs +2 -0
- package/dist/platform-DBSKTvFn.cjs.map +1 -0
- package/dist/remote-rules-DIcC5vVC.js +91 -0
- package/dist/remote-rules-DIcC5vVC.js.map +1 -0
- package/dist/remote-rules-DpFmOef2.cjs +2 -0
- package/dist/remote-rules-DpFmOef2.cjs.map +1 -0
- package/dist/sampling-BVjspJWu.cjs +2 -0
- package/dist/sampling-BVjspJWu.cjs.map +1 -0
- package/dist/sampling-Cm3WhI0a.js +76 -0
- package/dist/sampling-Cm3WhI0a.js.map +1 -0
- package/dist/{sanitize-DP0xDPrt.js → sanitize-C-ahCFsG.js} +2 -2
- package/dist/{sanitize-DP0xDPrt.js.map → sanitize-C-ahCFsG.js.map} +1 -1
- package/dist/{sanitize--_e4oOPX.cjs → sanitize-DHucKGdi.cjs} +2 -2
- package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
- package/dist/sender-D3fRCR8d.cjs +3 -0
- package/dist/sender-D3fRCR8d.cjs.map +1 -0
- package/dist/sender-DUUmSglb.js +1163 -0
- package/dist/sender-DUUmSglb.js.map +1 -0
- package/dist/storage/context-storage.d.ts +89 -0
- package/dist/storage/emergency-queue.d.ts +9 -1
- package/dist/storage/factory.d.ts +7 -1
- package/dist/storage/idb-driver.d.ts +13 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -0
- package/dist/storage/local-storage.d.ts +21 -1
- package/dist/storage/memory-storage.d.ts +13 -0
- package/dist/storage-BA9RqRO-.cjs +2 -0
- package/dist/storage-BA9RqRO-.cjs.map +1 -0
- package/dist/storage-w7Tslvlq.js +17 -0
- package/dist/storage-w7Tslvlq.js.map +1 -0
- package/dist/storm-CNZjsw4T.cjs +2 -0
- package/dist/storm-CNZjsw4T.cjs.map +1 -0
- package/dist/storm-Daq2jGHU.js +10 -0
- package/dist/storm-Daq2jGHU.js.map +1 -0
- package/dist/transport/exit-flush.d.ts +6 -0
- package/dist/transport/http-transport.d.ts +2 -1
- package/dist/transport/retry-engine.d.ts +7 -2
- package/dist/transport/serializers/otlp-traces.d.ts +3 -0
- package/dist/transport/serializers/select.d.ts +8 -5
- package/dist/transport/status-transport.d.ts +24 -0
- package/dist/types-BR9t_w28.js +8 -0
- package/dist/types-BR9t_w28.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs +2 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -0
- package/dist/utils/fixed-window.d.ts +9 -0
- package/dist/utils/identity.d.ts +20 -2
- package/dist/utils/lock.d.ts +8 -0
- package/dist/utils/openfin.d.ts +1 -1
- package/dist/utils/platform.d.ts +10 -0
- package/dist/utils/tracing.d.ts +82 -4
- package/dist/web-socket-BacvKOvD.cjs +2 -0
- package/dist/web-socket-BacvKOvD.cjs.map +1 -0
- package/dist/web-socket-CpsD8WAa.js +105 -0
- package/dist/web-socket-CpsD8WAa.js.map +1 -0
- package/package.json +1 -1
- package/dist/batch-D5qvsMQ_.cjs +0 -2
- package/dist/batch-D5qvsMQ_.cjs.map +0 -1
- package/dist/batch-DDgxg16_.js.map +0 -1
- package/dist/bus-C6RwKzPW.js +0 -478
- package/dist/bus-C6RwKzPW.js.map +0 -1
- package/dist/bus-WPVDFw2y.cjs +0 -2
- package/dist/bus-WPVDFw2y.cjs.map +0 -1
- package/dist/console-BSusX_M-.cjs.map +0 -1
- package/dist/console-Dv5GfaNn.js.map +0 -1
- package/dist/constants-Cb92egPS.cjs +0 -2
- package/dist/constants-Cb92egPS.cjs.map +0 -1
- package/dist/constants-DhH6VI5a.js +0 -144
- package/dist/constants-DhH6VI5a.js.map +0 -1
- package/dist/deadline-CUrH0Hd8.cjs +0 -2
- package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
- package/dist/deadline-DeqXEliN.js +0 -31
- package/dist/deadline-DeqXEliN.js.map +0 -1
- package/dist/errors-DCZWcHkd.js.map +0 -1
- package/dist/errors-ERu-su8m.cjs +0 -3
- package/dist/errors-ERu-su8m.cjs.map +0 -1
- package/dist/fixed-window-BR0bu32Y.cjs +0 -2
- package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
- package/dist/fixed-window-Re7jIRJH.js +0 -9
- package/dist/fixed-window-Re7jIRJH.js.map +0 -1
- package/dist/identity-C1WLItSl.cjs +0 -2
- package/dist/identity-C1WLItSl.cjs.map +0 -1
- package/dist/identity-Di-QXGCC.js +0 -88
- package/dist/identity-Di-QXGCC.js.map +0 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +0 -2
- package/dist/indexeddb-storage-DX18p39D.cjs.map +0 -1
- package/dist/indexeddb-storage-T9YIYVYC.js.map +0 -1
- package/dist/interactions-BLH_tX87.js.map +0 -1
- package/dist/interactions-_hfOerfC.cjs +0 -2
- package/dist/interactions-_hfOerfC.cjs.map +0 -1
- package/dist/journey-BRUj0hqD.cjs +0 -2
- package/dist/journey-BRUj0hqD.cjs.map +0 -1
- package/dist/journey-yALMEWF7.js.map +0 -1
- package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
- package/dist/long-frames-DD_Um9_4.js.map +0 -1
- package/dist/network--GoE7_Or.js.map +0 -1
- package/dist/network-DcuS2H1P.cjs +0 -2
- package/dist/network-DcuS2H1P.cjs.map +0 -1
- package/dist/platform-GaM6h7XM.js.map +0 -1
- package/dist/platform-kIL5AZB7.cjs +0 -2
- package/dist/platform-kIL5AZB7.cjs.map +0 -1
- package/dist/remote-rules-6ePq8CrI.js +0 -84
- package/dist/remote-rules-6ePq8CrI.js.map +0 -1
- package/dist/remote-rules-CI3gbRCL.cjs +0 -2
- package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
- package/dist/sampling-C-M8p3FK.cjs +0 -2
- package/dist/sampling-C-M8p3FK.cjs.map +0 -1
- package/dist/sampling-Ud_WiuU9.js +0 -65
- package/dist/sampling-Ud_WiuU9.js.map +0 -1
- package/dist/sender-BESHz6my.cjs +0 -3
- package/dist/sender-BESHz6my.cjs.map +0 -1
- package/dist/sender-BUBWLn5i.js +0 -1244
- package/dist/sender-BUBWLn5i.js.map +0 -1
- package/dist/storm-DhHGHhOc.cjs +0 -2
- package/dist/storm-DhHGHhOc.cjs.map +0 -1
- package/dist/storm-OD5J6Ylm.js +0 -10
- package/dist/storm-OD5J6Ylm.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"platform-kIL5AZB7.cjs","names":["getFin","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","require_openfin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url","isOnline"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { getFin } from \"./openfin\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = getFin()?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"gFAkDA,IAAIQ,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAOA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAOA,EAET,IAAMG,EAAI,WAEJG,EAAMH,EAAE,WAAqC,WAAa,GAC5DI,EAAyB,UACzBC,EACAC,EACAC,EAAW,GAETC,EAAQnB,EAAAA,EAAO,CAAC,EAAE,GAkCxB,OAhCIS,EAAcE,EAAG,0BAA0B,GAC7C,EAAW,iBACX,EAAW,IACFF,EAAcE,EAAG,yBAAyB,GACnD,EAAW,gBACX,EAAW,IACFF,EAAcE,EAAG,mBAAmB,GAC7C,EAAW,aACX,EAAW,IACFQ,IAAU,IAAA,GAOVR,EAAE,YAAc,IAAA,IAAaA,EAAE,QAAU,IAAA,GAClD,EAAW,QACFA,EAAE,UAAY,IAAA,IAAaS,EAAUN,CAAE,EAChD,EAAW,iBACF,OAAO,SAAa,KAAe,OAAO,QAAY,MAC/D,EAAW,SAXX,EAAWb,EAAAA,GAAmB,KAAKa,CAAE,EAAI,UAAY,cACrDO,EAAY,MAAM,sBAAuB,kDAAqD,CAC5F,IAAMC,EAAWH,EAAM,SACvB,EAAcG,GAAU,KACxB,EAAcA,GAAU,IAC1B,CAAC,GASH,EAAS,CACP,WACA,cACA,cACA,UAAWR,EACX,WACA,mBAAoBS,EAAWF,CAAW,CAC5C,EACOb,CACT,CAOA,SAASY,EAAU,EAAqB,CAMtC,OALIlB,EAAAA,EAA2B,KAAKY,CAAE,EAC7B,IAGPX,EAAAA,GAAsB,KAAKW,CAAE,GAAMV,EAAAA,GAAqB,KAAKU,CAAE,GAAKT,EAAAA,GAAkB,KAAKS,CAAE,IACjFA,EAAG,SAAA,aAAwB,GAAK,CAACA,EAAG,SAAA,SAAwB,CAC5E,CAOA,SAAgBS,EAAW,EAAmC,CAC5D,GAAI,OAAO,OAAW,IACpB,MAAO,GAET,GAAI,CACF,OAAO,OAAO,OAAS,OAAO,GAChC,MAAQ,CAGN,OADAF,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C,CAMA,SAAgBE,GAAoB,CAClC,OAAQ,WAAoD,WAAW,SAAW,EACpF"}
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { Mt as e, jt as t, ut as n } from "./constants-DhH6VI5a.js";
|
|
2
|
-
import { i as r } from "./deadline-DeqXEliN.js";
|
|
3
|
-
//#region src/core/remote-sampling.ts
|
|
4
|
-
var i = class {
|
|
5
|
-
config;
|
|
6
|
-
rules = null;
|
|
7
|
-
receivedAt = 0;
|
|
8
|
-
until = 0;
|
|
9
|
-
constructor(e) {
|
|
10
|
-
this.config = e;
|
|
11
|
-
}
|
|
12
|
-
apply(e) {
|
|
13
|
-
if (!e) {
|
|
14
|
-
this.rules = null;
|
|
15
|
-
return;
|
|
16
|
-
}
|
|
17
|
-
let t = Date.now();
|
|
18
|
-
this.rules = e.rules, this.receivedAt = t, this.until = t + e.ttlMs;
|
|
19
|
-
}
|
|
20
|
-
current() {
|
|
21
|
-
if (!this.rules) return null;
|
|
22
|
-
let e = Date.now();
|
|
23
|
-
return !this.config.sampling.remote || e < this.receivedAt || e >= this.until ? (this.rules = null, null) : this.rules;
|
|
24
|
-
}
|
|
25
|
-
minLevel() {
|
|
26
|
-
let { minLevel: e } = this.config, t = this.current()?.minLevel;
|
|
27
|
-
return t !== void 0 && n[t] < n[e] ? t : e;
|
|
28
|
-
}
|
|
29
|
-
wire() {
|
|
30
|
-
let e = this.current();
|
|
31
|
-
return e ? {
|
|
32
|
-
...e,
|
|
33
|
-
v: 1,
|
|
34
|
-
ttlMs: this.until - Date.now()
|
|
35
|
-
} : null;
|
|
36
|
-
}
|
|
37
|
-
}, a = class extends Error {};
|
|
38
|
-
function o(e) {
|
|
39
|
-
return typeof e == "number" && e >= 0 && e <= 1;
|
|
40
|
-
}
|
|
41
|
-
function s(e) {
|
|
42
|
-
if (e.length > 4096) throw new a(`The header is longer than ${String(t)} characters.`);
|
|
43
|
-
try {
|
|
44
|
-
return JSON.parse(e);
|
|
45
|
-
} catch {
|
|
46
|
-
throw new a("The header is not valid JSON.");
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
function c(e) {
|
|
50
|
-
if (e === void 0) return {};
|
|
51
|
-
let t = "rates must be an object with at most 100 rates from 0 to 1.";
|
|
52
|
-
if (!r(e)) throw new a(t);
|
|
53
|
-
let n = Object.entries(e);
|
|
54
|
-
if (n.length > 100 || !n.every(([, e]) => o(e))) throw new a(t);
|
|
55
|
-
return Object.fromEntries(n);
|
|
56
|
-
}
|
|
57
|
-
function l(t) {
|
|
58
|
-
if (!r(t)) throw new a("The rules must be an object.");
|
|
59
|
-
if (t.v !== 1) throw new a("The version must be 1.");
|
|
60
|
-
let { ttlMs: i, defaultRate: s, minLevel: l } = t;
|
|
61
|
-
if (typeof i != "number" || !(i > 0 && i <= 36e5)) throw new a(`ttlMs must be a number more than 0 and at most ${String(e)}.`);
|
|
62
|
-
if (s !== void 0 && !o(s)) throw new a("defaultRate must be a number from 0 to 1.");
|
|
63
|
-
if (l !== void 0 && !(typeof l == "string" && Object.hasOwn(n, l))) throw new a("minLevel must be a level name, for example DEBUG.");
|
|
64
|
-
let u = { rates: c(t.rates) };
|
|
65
|
-
return s !== void 0 && (u.defaultRate = s), l !== void 0 && (u.minLevel = l), {
|
|
66
|
-
rules: u,
|
|
67
|
-
ttlMs: i
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
function u(e, t) {
|
|
71
|
-
try {
|
|
72
|
-
return l(typeof e == "string" ? s(e) : e);
|
|
73
|
-
} catch (e) {
|
|
74
|
-
let n = e instanceof a ? ` ${e.message}` : "";
|
|
75
|
-
return t.report("config.invalid", `The library ignores the sampling rules from the server.${n}`, void 0, e), null;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
function d(e, t, n) {
|
|
79
|
-
n && (e.sampling ??= new i(t)), e.sampling?.apply(n);
|
|
80
|
-
}
|
|
81
|
-
//#endregion
|
|
82
|
-
export { u as n, d as t };
|
|
83
|
-
|
|
84
|
-
//# sourceMappingURL=remote-rules-6ePq8CrI.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-6ePq8CrI.js","names":["REMOTE_SAMPLING_MAX_TTL_MS","REMOTE_SAMPLING_MAX_CHARS","LEVEL_ORDER","isObject","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":";;;AA2CA,IAAaI,IAAb,MAA4B;CAaG;CAX7B,QAAoC;CAGpC,aAAqB;CAGrB,QAAgB;CAKhB,YAAY,GAAyC;EAAxB,KAAA,SAAAC;CAAyB;CAMtD,MAAM,GAAmC;EACvC,IAAI,CAACC,GAAQ;GACX,KAAK,QAAQ;GACb;EACF;EAEA,IAAMC,IAAM,KAAK,IAAI;EAIrB,AAFA,KAAK,QAAQD,EAAO,OACpB,KAAK,aAAaC,GAClB,KAAK,QAAQA,IAAMD,EAAO;CAC5B;CAMA,UAA8B;EAC5B,IAAI,CAAC,KAAK,OACR,OAAO;EAGT,IAAM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EAAM,MAAA,GACR,MAAM,IAAIF,EAAU,wBAAyD;CAG/E,IAAM,EAAE,UAAO,gBAAa,gBAAaE;CAEzC,IAAI,OAAOQ,KAAU,YAAY,EAAEA,IAAQ,KAAKA,KAAA,OAC9C,MAAM,IAAIV,EACR,kDAAkD,OAAOX,CAA0B,EAAE,EACvF;CAGF,IAAIsB,MAAgB,KAAA,KAAa,CAACV,EAAOU,CAAW,GAClD,MAAM,IAAIX,EAAU,2CAA2C;CAGjE,IACEF,MAAa,KAAA,KACb,EAAE,OAAOA,KAAa,YAAY,OAAO,OAAOP,GAAaO,CAAQ,IAErE,MAAM,IAAIE,EAAU,mDAAmD;CAGzE,IAAMD,IAAqB,EAAE,OAAOM,EAAUH,EAAM,KAAK,EAAE;CAU3D,OARIS,MAAgB,KAAA,MAClB,EAAM,cAAcA,IAGlBb,MAAa,KAAA,MACf,EAAM,WAAWA,IAGZ;EAAE;EAAO;CAAM;AACxB;AAQA,SAAgBc,EAAiB,GAAc,GAA+C;CAC5F,IAAI;EACF,OAAOH,EAAU,OAAOI,KAAQ,WAAWV,EAAUU,CAAG,IAAIA,CAAG;CACjE,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiBd,IAAY,IAAIc,EAAM,YAAY;EAQlE,OANAE,EAAY,OACV,kBACA,0DAA0DD,KAC1D,KAAA,GACAD,CACF,GACO;CACT;AACF;AAQA,SAAgBG,EACd,GACA,GACA,GACM;CAKN,AAJItB,MACF,EAAK,aAAa,IAAIF,EAAeC,CAAM,IAG7CwB,EAAK,UAAU,MAAMvB,CAAM;AAC7B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-Cb92egPS.cjs"),t=require("./deadline-CUrH0Hd8.cjs");var n=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevel(){let{minLevel:t}=this.config,n=this.current()?.minLevel;return n!==void 0&&e.ut[n]<e.ut[t]?n:t}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},r=class extends Error{};function i(e){return typeof e==`number`&&e>=0&&e<=1}function a(t){if(t.length>4096)throw new r(`The header is longer than ${String(e.jt)} characters.`);try{return JSON.parse(t)}catch{throw new r(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let n=`rates must be an object with at most 100 rates from 0 to 1.`;if(!t.i(e))throw new r(n);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>i(e)))throw new r(n);return Object.fromEntries(a)}function s(n){if(!t.i(n))throw new r(`The rules must be an object.`);if(n.v!==1)throw new r(`The version must be 1.`);let{ttlMs:a,defaultRate:s,minLevel:c}=n;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new r(`ttlMs must be a number more than 0 and at most ${String(e.Mt)}.`);if(s!==void 0&&!i(s))throw new r(`defaultRate must be a number from 0 to 1.`);if(c!==void 0&&!(typeof c==`string`&&Object.hasOwn(e.ut,c)))throw new r(`minLevel must be a level name, for example DEBUG.`);let l={rates:o(n.rates)};return s!==void 0&&(l.defaultRate=s),c!==void 0&&(l.minLevel=c),{rules:l,ttlMs:a}}function c(e,t){try{return s(typeof e==`string`?a(e):e)}catch(e){let n=e instanceof r?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${n}`,void 0,e),null}}function l(e,t,r){r&&(e.sampling??=new n(t)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
|
|
2
|
-
//# sourceMappingURL=remote-rules-CI3gbRCL.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-CI3gbRCL.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","isObject","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","require_deadline","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\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iBACA,0DAA0DD,IAC1D,IAAA,GACAD,CACF,EACO,IACT,CACF,CAQA,SAAgBG,EACd,EACA,EACA,EACM,CACFtB,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7CwB,EAAK,UAAU,MAAMvB,CAAM,CAC7B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-Cb92egPS.cjs"),t=require("./fixed-window-BR0bu32Y.cjs");function n(){return`${String(Date.now())}000000`}function r(t){return typeof t==`string`&&Object.hasOwn(e.ut,t)}function i(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function a(t){let n=e.K;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.q);return n>>>0}function o(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function s(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={rate:i,length:r.length});return n}function c(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,o=s(e,r),c=n?s(e,n.rates):void 0;return c&&c.length>=(o?.length??-1)?Math.min(c.rate,a):o?o.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function l(t,n,r){if(t.aggregated===!0||t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=c(t.namespace,n,r),o=e.ut[t.level]<e.ut[n.minLevel];return r&&o&&!e.lt.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),i>=1?!0:i<=0?!1:a(t.journeyId||t.traceId)/e.bn<i}function u(t,n,r=null){return l({level:t.severityText,type:o(t,e.d),namespace:o(t,e.n),journeyId:o(t,e.s),traceId:t.traceId,aggregated:o(t,`log.type`)===`metric`&&o(t,e.vt.start)!==``},n,r)}var d=class{window={start:0,count:0};allow(n){return n.severityText!==`ERROR`&&n.severityText!==`FATAL`||t.t(this.window,500,e.G)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return d}});
|
|
2
|
-
//# sourceMappingURL=sampling-C-M8p3FK.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-C-M8p3FK.cjs","names":["LEVEL_ORDER","FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","LEVEL_BYPASS_TYPES","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","countInWindow","ERROR_STORM_WINDOW_MS","require_constants","require_fixed_window","nowUnixNano","isLogLevel","value","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","belowMinLevel","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters.\n if (input.aggregated === true || input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n // minLevel does not apply to an action or a metric. Do not cap them.\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW, ERROR_STORM_WINDOW_MS);\n }\n}\n"],"mappings":"qFA0DA,SAAgBc,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOhB,EAAAA,GAAagB,CAAK,CACtE,CAUA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAME,EAASF,EACf,OACE,OAAOE,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA,EAAO,aAAe,MACtB,OAAOA,EAAO,UAAa,UAC3BA,EAAO,WAAa,IAExB,CChEA,SAASC,EAAK,EAAuB,CACnC,IAAIC,EAAInB,EAAAA,EAER,IAAK,IAAIoB,EAAI,EAAGA,EAAIL,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWK,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGlB,EAAAA,CAAS,EAG5B,OAAOkB,IAAM,CACf,CASA,SAASE,EAAS,EAAmB,EAAqB,CACxD,IAAMN,EAAiBE,EAAO,WAAWK,GACzC,OAAO,OAAOP,GAAU,SAAWA,EAAQ,EAC7C,CAiBA,SAASQ,EAAc,EAAmB,EAAwD,CAChG,IAAIC,EAEJ,IAAK,GAAM,CAACC,EAAQC,KAAS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J,EAAQV,EAAAA,CAAe,EAC3C,QAASU,EAAO,QAChB,WACEI,EAASJ,EAAA,UAAqB,IAAM,UAAYI,EAASJ,EAAQT,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAsB,EACAG,CACF,CACF,CAQA,IAAaO,EAAb,KAA0B,CAExB,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAO5D,MAAM,EAA4B,CAMhC,OALIvB,EAAO,eAAiB,SAAWA,EAAO,eAAiB,SAKxDR,EAAAA,EAAc,KAAK,OAAA,IAAsCC,EAAAA,CAAqB,CACvF,CACF"}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import { G as e, K as t, bn as n, d as r, lt as i, n as a, q as o, s, ut as c, vt as l } from "./constants-DhH6VI5a.js";
|
|
2
|
-
import { t as u } from "./fixed-window-Re7jIRJH.js";
|
|
3
|
-
//#region src/models/log-record.ts
|
|
4
|
-
function d() {
|
|
5
|
-
return `${String(Date.now())}000000`;
|
|
6
|
-
}
|
|
7
|
-
function f(e) {
|
|
8
|
-
return typeof e == "string" && Object.hasOwn(c, e);
|
|
9
|
-
}
|
|
10
|
-
function p(e) {
|
|
11
|
-
if (typeof e != "object" || !e) return !1;
|
|
12
|
-
let t = e;
|
|
13
|
-
return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
|
|
14
|
-
}
|
|
15
|
-
//#endregion
|
|
16
|
-
//#region src/core/sampling.ts
|
|
17
|
-
function m(e) {
|
|
18
|
-
let n = t;
|
|
19
|
-
for (let t = 0; t < e.length; t++) n ^= e.charCodeAt(t), n = Math.imul(n, o);
|
|
20
|
-
return n >>> 0;
|
|
21
|
-
}
|
|
22
|
-
function h(e, t) {
|
|
23
|
-
let n = e.attributes[t];
|
|
24
|
-
return typeof n == "string" ? n : "";
|
|
25
|
-
}
|
|
26
|
-
function g(e, t) {
|
|
27
|
-
let n;
|
|
28
|
-
for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
|
|
29
|
-
rate: i,
|
|
30
|
-
length: r.length
|
|
31
|
-
});
|
|
32
|
-
return n;
|
|
33
|
-
}
|
|
34
|
-
function _(e, t, n) {
|
|
35
|
-
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = g(e, r), s = n ? g(e, n.rates) : void 0;
|
|
36
|
-
return s && s.length >= (o?.length ?? -1) ? Math.min(s.rate, a) : o ? o.rate : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
|
|
37
|
-
}
|
|
38
|
-
function v(e, t, r) {
|
|
39
|
-
if (e.aggregated === !0 || e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
40
|
-
let a = _(e.namespace, t, r), o = c[e.level] < c[t.minLevel];
|
|
41
|
-
return r && o && !i.includes(e.type) && (a = Math.min(a, t.sampling.remoteMaxRate)), a >= 1 ? !0 : a <= 0 ? !1 : m(e.journeyId || e.traceId) / n < a;
|
|
42
|
-
}
|
|
43
|
-
function y(e, t, n = null) {
|
|
44
|
-
return v({
|
|
45
|
-
level: e.severityText,
|
|
46
|
-
type: h(e, r),
|
|
47
|
-
namespace: h(e, a),
|
|
48
|
-
journeyId: h(e, s),
|
|
49
|
-
traceId: e.traceId,
|
|
50
|
-
aggregated: h(e, "log.type") === "metric" && h(e, l.start) !== ""
|
|
51
|
-
}, t, n);
|
|
52
|
-
}
|
|
53
|
-
var b = class {
|
|
54
|
-
window = {
|
|
55
|
-
start: 0,
|
|
56
|
-
count: 0
|
|
57
|
-
};
|
|
58
|
-
allow(t) {
|
|
59
|
-
return t.severityText !== "ERROR" && t.severityText !== "FATAL" || u(this.window, 500, e);
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
//#endregion
|
|
63
|
-
export { p as a, f as i, y as n, d as o, v as r, b as t };
|
|
64
|
-
|
|
65
|
-
//# sourceMappingURL=sampling-Ud_WiuU9.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-Ud_WiuU9.js","names":["ERROR_STORM_WINDOW_MS","FNV_OFFSET_BASIS","UINT32_MAX","ATTR_LOG_TYPE","LEVEL_BYPASS_TYPES","ATTR_APP_NAMESPACE","FNV_PRIME","LEVEL_ORDER","METRIC_KEYS","countInWindow","nowUnixNano","isLogLevel","value","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","belowMinLevel","shouldSample","ATTR_JOURNEY_ID","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters.\n if (input.aggregated === true || input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n // minLevel does not apply to an action or a metric. Do not cap them.\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW, ERROR_STORM_WINDOW_MS);\n }\n}\n"],"m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
-
const e=require("./constants-Cb92egPS.cjs"),t=require("./deadline-CUrH0Hd8.cjs"),n=require("./sampling-C-M8p3FK.cjs"),r=require("./sanitize--_e4oOPX.cjs"),i=require("./identity-C1WLItSl.cjs"),a=require("./openfin-DtH2f7zX.cjs"),o=require("./platform-kIL5AZB7.cjs"),s=require("./batch-D5qvsMQ_.cjs"),c=require("./library-request-BcAxuwsf.cjs"),l=require("./remote-rules-CI3gbRCL.cjs");function u(e){let{maxBatches:t}=e;return e.mode===`until-delivered`?{maxBatches:t,maxAgeMs:1/0,maxAttempts:1/0}:{maxBatches:t,maxAgeMs:e.maxAgeMs,maxAttempts:e.maxAttempts}}function d(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function f(e,t){return`${e}${String(t.createdAt).padStart(14,`0`)}.${t.id}`}function p(e,t){let n=[];return t.guard(`storage.unavailable`,`The library could not list the localStorage keys.`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function m(e,t){let n=t.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return n===void 0?null:s.i(n)?n:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function h(n,r){let i=0;for(let a of p(e.H,r)){let o=r.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(a);return localStorage.removeItem(a),e});if(!o)continue;let s=m(o,r);if(s!==null)try{await t.n(n.save(s),e.on),i++}catch(e){r.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:a},e)}}return i}function g(t,n,r){let i=`writing the emergency queue, ${String(t.records.length)} records`,a=[],o=n.guard(`storage.quota_exceeded`,i,()=>{let r=p(e.H,n);for(let e of r.slice(0,Math.max(0,r.length-20+1))){let t=m(String(localStorage.getItem(e)),n);t!==null&&a.push(t),localStorage.removeItem(e)}return localStorage.setItem(f(e.H,t),JSON.stringify(t)),!0});n.guard(`pipeline.crashed`,`The loss report of the emergency queue failed.`,()=>{if(a.length>0){let e=a.flatMap(e=>e.records);r?.(`exit_queue_full`,e,a.map(e=>e.id))}o!==!0&&r?.(`quota`,t.records,[t.id])})}async function _(e,t){return await d(`ui-observability.emergency`,t,()=>h(e,t),{skipIfBusy:!1})??0}function v(e){return Array.isArray(e.records)&&e.records.some(s.r)}var y=class{howMany;isAudit;plain=[];audit=[];constructor(e,t){this.howMany=e,this.isAudit=t}add(e){return this.isAudit(e)?this.audit.length<this.howMany&&this.audit.push(e):this.plain.push(e),this.plain.length<this.howMany}picked(){return[...this.plain,...this.audit].slice(0,this.howMany)}};function b(e,t,n){let r=new y(t,n);for(let t of e)if(!r.add(t))break;return r.picked()}function x(e,t,n,r){return e.batches+=n,e.records+=r,e.reason=t,{batches:n,records:r,reason:t}}function S(e,t,n,r){n.batches!==0&&(e.report(`storage.evicted`,`The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`,{...n}),t?.(n,r))}function C(t){let n=e.x.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var ee=class{limits;diagnostics;onGap;name=e.ln;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`))await this.prune();else if(this.evictForQuota(),!this.write(e,`localStorage refused a batch even after evicting`)){let t={batches:1,records:e.records.length,reason:`quota`};S(this.diagnostics,this.onGap,t,[e])}}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=[],r=[];for(let t of this.keys()){let i=C(t);i===null||i<e?n.push(t):r.push(t)}this.drop(t,`expired`,[...this.entries(n)]);let i=r.length-this.limits.maxBatches;return i>0&&this.drop(t,`over_capacity`,this.evictable(r,i)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(t,n){return this.diagnostics.guard(`storage.quota_exceeded`,n,()=>(localStorage.setItem(f(e.x,t),JSON.stringify(t)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`},n=Math.ceil(e.length/4);this.drop(t,`quota`,this.evictable(e,n))}evictable(e,t){return b(this.entries(e),t,e=>e.batch!==null&&v(e.batch))}*entries(e){for(let t of e)yield{key:t,batch:this.read(t)}}drop(e,t,n){if(n.length===0)return;let r=[];for(let{key:e,batch:t}of n)this.removeKey(e),t&&r.push(t);let i=x(e,t,n.length,s.n(r));S(this.diagnostics,this.onGap,i,r)}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(t));return n===void 0?null:s.i(n)?n:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return p(e.x,this.diagnostics)}},w=class{limits;onGap;name=e.un;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),this.report(t,`expired`,n);let r=this.batches.length-this.limits.maxBatches;if(r>0){let e=b(this.batches,r,v);this.batches=this.batches.filter(t=>!e.includes(t)),this.report(t,`over_capacity`,e)}return Promise.resolve(t)}report(e,t,n){if(n.length===0)return;let r=x(e,t,n.length,s.n(n));this.onGap?.(r,n)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},te=t=>({name:e.dn,save:e=>(t?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),Promise.resolve()),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()});function ne(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function re(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e.fn,`1`),localStorage.removeItem(e.fn),!0))===!0}async function T(e,t,n,r,i){if(e===`none`)return te(i);if(e===`memory`)return new w(n,i);if(e===`indexeddb`||e===`auto`){if(ne(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-DX18p39D.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new w(n,i)}return re(r)?new ee(n,r,i):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new w(n,i))}var E=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 D(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.bt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function ie(t){return e.St.test(t)?Number(BigInt(t)/e.Ct):Date.now()}function ae(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function O(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function k(e,t,n,r){let i=ae(n);if(i!==null)O(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)k(e,t,i,r);else for(let[i,a]of Object.entries(n))k(e,`${t}.${i}`,a,r);r.delete(n)}}function A(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))k(t,r,i,n);return t}var oe={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=ie(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:e.B[t.severityText]??t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Vt],version:t.resource[e.Ht],environment:t.resource[e.Lt]},user_agent:{original:t.resource[e.Ft]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...A(t.resource),...A(t.attributes)}})}).join(`
|
|
2
|
-
`)}\n`,contentType:e.N}}};function j(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(j).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:M(e)}}:null}function M(e){let t=[];for(let[n,r]of Object.entries(e)){let e=j(r);e&&t.push({key:n,value:e})}return t}var N=new WeakMap;function se(e){let t=N.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return N.set(e,n),n}function P(e){let t=new Map;for(let n of e){let e=se(n.resource),r=t.get(e);r?r.records.push(n):t.set(e,{resource:n.resource,records:[n]})}return[...t.values()]}var F={name:e.en,serialize(t){let n=P(t).map(t=>({resource:{attributes:M(t.resource)},scopeLogs:[{scope:{name:e.hn,version:e.gn},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:M(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:n}),contentType:e.M}}},I=1;function L(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function R(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function z(t){let n=t.attributes[e.vt.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 B(t){let n=L(t,e.vt.count);if(n===void 0){let e=L(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.vt.bounds],i=t.attributes[e.vt.buckets];if(!R(r)||!R(i)||i.length!==r.length+1)return null;let a=L(t,e.vt.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:L(t,e.vt.sum),min:a,max:L(t,e.vt.max),bucketCounts:i.map(String),explicitBounds:r}}function V(e){let t=L(e,`metric.value`);return t===void 0?null:{asDouble:t}}function H(t,n){let r=t.attributes[e.vt.start],i=n===`histogram`?B(t):V(t);return i===null?null:{attributes:M(z(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function U({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:I,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var W={name:e.en,serialize(t){let n=P(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=H(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:M(t.resource)},scopeMetrics:[{scope:{name:e.hn,version:e.gn},metrics:[...n.values()].map(U)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.M}}};function G(e){return e===`otlp`?F:e===`ecs`?oe:e}function K(e,t){return t.metricsEndpoint!==``&&e.records.length>0&&e.records.every(e=>s.t(e,`log.type`)===`metric`)?`metrics`:`logs`}function q(e,t){return e===`metrics`?t.metricsEndpoint:t.endpoint}function J(e,t,n,r){try{return(K(t,e)===`metrics`?W:G(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var Y=class{config;diagnostics;onSampling;onLoss;throttledUntil={logs:0,metrics:0};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[K(e,this.config)]-Date.now())}serialize(e){let t=J(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.config.sampling.remote&&t!=null&&this.onSampling(t)}reject(t,n,r,i){let a=String(t);if(t===401||t===403){let e=i.advice===void 0?``:` ${i.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${a}.${e}`,{status:t,endpoint:q(r,this.config)}),new E(`permanent`,`The server rejected the batch with ${a}.`,t)}if(t===413)return new E(`too_large`,`The payload is too large.`,t,void 0,i.maxBytes);if(t===429||t===503){let n=t===429,a=i.retryAfterMs===void 0?void 0:Math.min(i.retryAfterMs,e.Xt);return this.throttledUntil[r]=Date.now()+(a??2e3),n&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:a}),new E(`throttled`,n?`The server throttles the requests.`:`The service is not available.`,t,a)}return t===408||t>=500?new E(`transient`,`The server returned the error ${a}.`,t):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${a}. The library dropped it.`,{batchId:n,status:t}),new E(`permanent`,`The server rejected the batch with ${a}.`,t))}};function X(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records}}function ce(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 Z(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var le=class extends Y{async send(n){let{transport:i}=this.config;if(!i||n.records.length===0)return;let a=this.serialize(n);if(!a)return;let o=K(n,this.config),s=X(n,a,o),l;try{l=await t.n(c.i(()=>c.r(()=>r.o(()=>i(s)))),e.Pt)}catch(e){let n=e instanceof t.t?e:void 0;throw new E(n?`timeout`:`transient`,n?.message??`The custom transport failed.`,void 0,void 0,void 0,e)}if(!ce(l))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:n.id}),new E(`transient`,`The custom transport returned no valid status.`);let{status:u}=l;if(u>=200&&u<300)this.accept(o,l.sampling);else throw this.reject(u,n.id,o,{retryAfterMs:Z(l.retryAfterMs),maxBytes:Z(l.maxBytes)})}},ue=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=a.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=a.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 n of this.deps.drainForExit()){let i=K(n,t)===`metrics`?t.metricsEndpoint:r.href;this.flushBatch(n,e,new URL(i))}}}flushBatch(t,n,i){let{config:a,diagnostics:o}=this.deps;if(t.records.length===0)return;let s=this.serialize(t,n);if(!s)return;if(r.t(s.body)>6e4){g(t,o,this.deps.onLoss);return}i.searchParams.set(e.Dt,t.id),i.searchParams.set(e.Ot,n);let c=i.toString(),l=this.deps.exitHeaders();if(l){this.keepaliveFetch(c,t,s.body,n,()=>{let n=new Headers(l);return n.set(e.Q,s.contentType),n.set(e.X,t.id),n});return}if(a.headers){g(t,o,this.deps.onLoss);return}let u=this.beacon(c,s.body);u!==`sent`&&(u===`refused`?g(t,o,this.deps.onLoss):this.keepaliveFetch(c,t,s.body,n,()=>new Headers({[e.Q]:e.P})))}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 a=this.serialize(i,e);if(!a)continue;let o=X(i,a,K(i,n));(t===void 0||r.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>c.r(()=>t(o)))!==!0)&&g(i,r,this.deps.onLoss)}}serialize(e,t){let n=J(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=()=>{g(t,s,this.deps.onLoss)},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 de(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.U)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var fe=`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.`,pe=class extends Y{cachedHeaders;async send(e,t){let{config:n}=this,r=K(e,n),i=q(r,n);i&&e.records.length!==0&&await this.post(e,r,i,t)}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.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.rejectsCredentials(o.status)&&typeof this.config.headers==`function`&&(this.cachedHeaders=void 0,o=await this.attempt(t,r,a,i)),o.ok){this.accept(n,o.headers.get(e.et));return}let s=o.status,c=D(o.headers.get(e.$)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,n,{retryAfterMs:c,maxBytes:l,advice:fe})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i){let a=Date.now()+e.Pt,o=new Headers(await this.before(this.resolveHeaders(),a,n));o.set(e.Q,r.contentType),o.set(e.X,t.id),o.set(e.Y,String(t.attempts));let s=await this.before(this.encodeBody(r.body),a,n);typeof s!=`string`&&o.set(e.Z,e.U);let c=this.keepalive(s);return c&&i?.(),this.dispatch(n,o,s,a,c)}async before(e,n,r){try{return await t.n(e,Math.max(0,n-Date.now()))}catch{throw this.timeout(r)}}timeout(t){let n=`The request took longer than ${String(e.Pt)} ms.`;return this.diagnostics.report(`transport.timeout`,n,{endpoint:t}),new E(`timeout`,n)}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.`,()=>de(e))??e}async dispatch(e,n,r,i,a){let{config:s}=this,l=new AbortController,u=setTimeout(()=>{l.abort()},Math.max(0,i-Date.now()));t.r(u);try{return await c.r(()=>fetch(e,{method:`POST`,headers:n,body:r,credentials:s.credentials,signal:l.signal,cache:`no-store`,keepalive:a}))}catch{throw l.signal.aborted?this.timeout(e):new E(o.r()?`transient`:`offline`,`A network error occurred.`)}finally{clearTimeout(u)}}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}=this.config,r=await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()));return r&&(this.cachedHeaders={source:e,endpoint:t,metricsEndpoint:n,headers:r}),r??{}}},me=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=20,a=()=>void 0){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i,this.onLoss=a,this.maxAttempts=u(r.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.Yt)}nudge(){this.draining||this.schedule(e.Jt)}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()}schedule(e){if(this.stopped)return;this.clearTimer();let n=setTimeout(()=>{this.drain()},e);this.timer=n,t.r(n)}bounded(n){return t.n(n,e.on)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Jt*2**this.attempt,e.Xt);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await d(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.Yt)}finally{this.draining=!1}}}async drainLocked(){try{if(!o.r())return this.schedule(e.Yt),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.Yt),!0;let n=new Set,r=0;for(let e of t){if(this.stopped)return!0;let t=K(e,this.config);if(n.has(t))continue;let i=await this.deliver(e);if(i===`stop`)return!0;i!==`next`&&(n.add(t),r=Math.max(r,i))}return n.size>0?this.schedule(r):this.schedule(t.length===this.batchesPerDrain?0:e.Yt),!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(t){if(t.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${t.attempts.toString()} attempts.`,{batchId:t.id,records:t.records.length}),this.onLoss(`max_attempts`,t.records,[t.id]),await this.bounded(this.storage.remove(t.id)),`next`;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,`next`}catch(n){let r=n instanceof E?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),`next`):r?.kind===`offline`?(this.schedule(e.Yt),`stop`):r?.kind===`throttled`?(this.attempt++,r.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,r?.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 E?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=s.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]),[])}};function Q(t){return t.attributes[e.d]===e.ht}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}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,t.r(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},he=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new n.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new $(i.logs,a),metrics:new $(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=n.o(),this.route(e))}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);this.unconfirmed.clear();let t=[...e.filter(Q),...this.streams.metrics.take()],n=[...e.filter(e=>!Q(e)),...this.streams.logs.take()];return[this.toBatch(t),this.toBatch(n)].filter(e=>e!==null)}async flushPending(){this.stopped||(this.claim(this.streams.metrics),this.claim(this.streams.logs)),await Promise.all([...this.open].map(e=>e.done))}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.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}}route(e){try{let t=Q(e)?this.streams.metrics:this.streams.logs;if(!this.ceiling.allow(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(){for(;this.inFlight<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.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){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(n){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await t.n(this.storage.save(n),e.on),this.retry.nudge()})}},ge=class t{storage;retry;pipeline;exitFlush;diagnostics;constructor(e,t,n,r,i){this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i}static async create(n){let{config:r,diagnostics:i}=n,a=await T(r.storage,e.an,u(r.retention),i,n.onGap),o=e=>{let t=l.n(e,i);t&&l.t(n.remote,r,t)},{onLoss:s}=n,c=r.transport?void 0:new pe(r,i,o,s),d=c??new le(r,i,o,s),f=new me(a,d,i,r,20,s),{batching:p}=r,m=new he(d,a,f,i,{logs:{flushIntervalMs:p.logFlushIntervalMs,batchSize:p.logBatchSize},metrics:{flushIntervalMs:p.metricFlushIntervalMs,batchSize:p.metricBatchSize}}),h=new ue({config:r,diagnostics:i,drainForExit:()=>m.drainForExit(),flushAlive:()=>m.flushPending(),exitHeaders:()=>c?.lastHeaders(),onLoss:s,beforeExit:n.beforeExit}),g=!1;try{h.install(),f.start(),g=!0}finally{g||(h.uninstall(),f.stop())}let _=new t(a,f,m,h,i);return _.importEmergency(),_}push(e){this.pipeline.push(e)}async flush(){await this.pipeline.flushPending()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}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 importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>_(this.storage,this.diagnostics));e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=ge,exports.i=v,exports.n=S,exports.r=y,exports.t=x;
|
|
3
|
-
//# sourceMappingURL=sender-BESHz6my.cjs.map
|