@utk09/ui-observability 0.9.1 → 0.9.3
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 +33 -0
- package/README.md +75 -64
- package/dist/batch-D5qvsMQ_.cjs +2 -0
- package/dist/batch-D5qvsMQ_.cjs.map +1 -0
- package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
- package/dist/batch-DDgxg16_.js.map +1 -0
- package/dist/bus/bus.d.ts +0 -4
- package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
- package/dist/bus-C6RwKzPW.js.map +1 -0
- package/dist/bus-WPVDFw2y.cjs +2 -0
- package/dist/bus-WPVDFw2y.cjs.map +1 -0
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/storm.d.ts +2 -7
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
- package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
- package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
- package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
- package/dist/constants-Cb92egPS.cjs +2 -0
- package/dist/constants-Cb92egPS.cjs.map +1 -0
- package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
- package/dist/constants-DhH6VI5a.js.map +1 -0
- package/dist/constants.d.ts +28 -3
- package/dist/core/breadcrumbs.d.ts +1 -3
- package/dist/core/context.d.ts +0 -8
- package/dist/core/diagnostics.d.ts +1 -3
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +5 -12
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +17 -0
- package/dist/core/sampling.d.ts +3 -3
- package/dist/core/sender.d.ts +2 -0
- package/dist/deadline-CUrH0Hd8.cjs +2 -0
- package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
- package/dist/deadline-DeqXEliN.js +31 -0
- package/dist/deadline-DeqXEliN.js.map +1 -0
- package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
- package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
- package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
- package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
- package/dist/fixed-window-BR0bu32Y.cjs +2 -0
- package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
- package/dist/fixed-window-Re7jIRJH.js +9 -0
- package/dist/fixed-window-Re7jIRJH.js.map +1 -0
- package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
- package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
- package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
- package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/index.js +522 -369
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
- package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
- package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
- package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
- package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
- package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
- package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
- package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
- package/dist/journey-BRUj0hqD.cjs +2 -0
- package/dist/journey-BRUj0hqD.cjs.map +1 -0
- package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
- package/dist/journey-yALMEWF7.js.map +1 -0
- package/dist/library-request-BcAxuwsf.cjs +2 -0
- package/dist/library-request-BcAxuwsf.cjs.map +1 -0
- package/dist/library-request-CQD4HUiP.js +25 -0
- package/dist/library-request-CQD4HUiP.js.map +1 -0
- package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
- package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
- package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
- package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
- package/dist/models/batch.d.ts +6 -0
- package/dist/models/config.d.ts +23 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/network--GoE7_Or.js +211 -0
- package/dist/network--GoE7_Or.js.map +1 -0
- package/dist/network-DcuS2H1P.cjs +2 -0
- package/dist/network-DcuS2H1P.cjs.map +1 -0
- package/dist/openfin-BwEN0uj4.js +8 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -0
- package/dist/openfin-DtH2f7zX.cjs +2 -0
- package/dist/openfin-DtH2f7zX.cjs.map +1 -0
- package/dist/platform-GaM6h7XM.js +52 -0
- package/dist/platform-GaM6h7XM.js.map +1 -0
- package/dist/platform-kIL5AZB7.cjs +2 -0
- package/dist/platform-kIL5AZB7.cjs.map +1 -0
- package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
- package/dist/remote-rules-6ePq8CrI.js.map +1 -0
- package/dist/remote-rules-CI3gbRCL.cjs +2 -0
- package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
- package/dist/sampling-C-M8p3FK.cjs +2 -0
- package/dist/sampling-C-M8p3FK.cjs.map +1 -0
- package/dist/sampling-Ud_WiuU9.js +65 -0
- package/dist/sampling-Ud_WiuU9.js.map +1 -0
- package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
- package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
- package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
- package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
- package/dist/sender-BESHz6my.cjs +3 -0
- package/dist/sender-BESHz6my.cjs.map +1 -0
- package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
- package/dist/sender-BUBWLn5i.js.map +1 -0
- package/dist/storage/gap.d.ts +20 -0
- package/dist/storage/indexeddb-storage.d.ts +1 -7
- package/dist/storage/keys.d.ts +9 -0
- package/dist/storage/local-storage.d.ts +0 -6
- package/dist/storage/memory-storage.d.ts +1 -1
- package/dist/storm-DhHGHhOc.cjs +2 -0
- package/dist/storm-DhHGHhOc.cjs.map +1 -0
- package/dist/storm-OD5J6Ylm.js +10 -0
- package/dist/storm-OD5J6Ylm.js.map +1 -0
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +13 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +3 -1
- package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +30 -0
- package/dist/transport/serializers/select.d.ts +20 -4
- package/dist/transport/status-transport.d.ts +19 -11
- package/dist/utils/fixed-window.d.ts +15 -0
- package/dist/utils/guards.d.ts +6 -0
- package/dist/utils/library-request.d.ts +12 -0
- package/dist/utils/openfin.d.ts +48 -0
- package/dist/utils/platform.d.ts +5 -0
- package/package.json +2 -3
- package/dist/batch-DEK4bv9N.js.map +0 -1
- package/dist/batch-DEVFs28i.cjs +0 -2
- package/dist/batch-DEVFs28i.cjs.map +0 -1
- package/dist/bus-DNFvTkif.cjs +0 -2
- package/dist/bus-DNFvTkif.cjs.map +0 -1
- package/dist/bus-HVQ8E72V.js.map +0 -1
- package/dist/constants-N99w84xy.js.map +0 -1
- package/dist/constants-X86IDwkC.cjs +0 -2
- package/dist/constants-X86IDwkC.cjs.map +0 -1
- package/dist/deadline-5_PecIl5.js +0 -26
- package/dist/deadline-5_PecIl5.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
- package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
- package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
- package/dist/journey-DjvDzHyp.js.map +0 -1
- package/dist/journey-DxlfdFJV.cjs +0 -2
- package/dist/journey-DxlfdFJV.cjs.map +0 -1
- package/dist/library-request-BZ1ekVtl.cjs +0 -2
- package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
- package/dist/library-request-C8kc5YWv.js +0 -14
- package/dist/library-request-C8kc5YWv.js.map +0 -1
- package/dist/network-51iicpLl.js +0 -174
- package/dist/network-51iicpLl.js.map +0 -1
- package/dist/network-jBbjyAJP.cjs +0 -2
- package/dist/network-jBbjyAJP.cjs.map +0 -1
- package/dist/platform-Cjts-8k8.js +0 -48
- package/dist/platform-Cjts-8k8.js.map +0 -1
- package/dist/platform-DW3GFIUE.cjs +0 -2
- package/dist/platform-DW3GFIUE.cjs.map +0 -1
- package/dist/remote-rules-ByS34k4e.cjs +0 -2
- package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
- package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
- package/dist/sampling-BN3Oi6SV.js +0 -63
- package/dist/sampling-BN3Oi6SV.js.map +0 -1
- package/dist/sampling-b2ck5X98.cjs +0 -2
- package/dist/sampling-b2ck5X98.cjs.map +0 -1
- package/dist/sender-BBY0IcUo.js.map +0 -1
- package/dist/sender-BXoAZKum.cjs +0 -3
- package/dist/sender-BXoAZKum.cjs.map +0 -1
- package/dist/storm-CKuaBp7i.cjs +0 -2
- package/dist/storm-CKuaBp7i.cjs.map +0 -1
- package/dist/storm-DhtL2eVr.js +0 -10
- package/dist/storm-DhtL2eVr.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-ByS34k4e.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","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 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 * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF,CAEA,IAAMC,EAAM,KAAK,IAAI,EAErB,KAAK,MAAQD,EAAO,MACpB,KAAK,WAAaC,EAClB,KAAK,MAAQA,EAAMD,EAAO,KAC5B,CAMA,SAA8B,CAC5B,GAAI,CAAC,KAAK,MACR,OAAO,KAGT,IAAMC,EAAM,KAAK,IAAI,EASrB,MALI,CAAC,KAAK,OAAO,SAAS,QAAUA,EAAM,KAAK,YAAcA,GAAO,KAAK,OACvE,KAAK,MAAQ,KACN,MAGF,KAAK,KACd,CAMA,UAAqB,CACnB,GAAM,CAAE,YAAa,KAAK,OACpBC,EAAS,KAAK,QAAQ,CAAC,EAAE,SAE/B,OAAOA,IAAW,IAAA,IAAaT,EAAAA,GAAYS,GAAUT,EAAAA,GAAYU,GAAYD,EAASC,CACxF,CAMA,MAA0B,CACxB,IAAMC,EAAQ,KAAK,QAAQ,EAM3B,OAJKA,EAIE,CAAE,GAAGA,EAAO,EAAA,EAA4B,MAAO,KAAK,MAAQ,KAAK,IAAI,CAAE,EAHrE,IAIX,CACF,EC9FMC,EAAN,cAAwB,KAAM,CAAC,EAO/B,SAASC,EAAO,EAAiC,CAC/C,OAAO,OAAOC,GAAU,UAAYA,GAAA,G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B,CAAE,MAAOO,EAAUJ,EAAM,KAAK,CAAE,EAU3D,OARIU,IAAgB,IAAA,KAClB,EAAM,YAAcA,GAGlBd,IAAa,IAAA,KACf,EAAM,SAAWA,GAGZ,CAAE,QAAO,OAAM,CACxB,CAQA,SAAgBe,EAAiB,EAAc,EAA+C,CAC5F,GAAI,CACF,OAAOH,EAAU,OAAOI,GAAQ,SAAWV,EAAUU,CAAG,EAAIA,CAAG,CACjE,OAASC,EAAO,CACd,IAAMC,EAASD,aAAiBf,EAAY,IAAIe,EAAM,UAAY,GAQlE,OANAE,EAAY,OACV,iBACA,0DAA0DD,IAC1D,IAAA,GACAD,CACF,EACO,IACT,CACF,CAQA,SAAgBG,EACd,EACA,EACA,EACM,CACFvB,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7CyB,EAAK,UAAU,MAAMxB,CAAM,CAC7B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-M-XZ1xbe.js","names":["REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","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 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 * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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,IAAaG,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,IAAMC,IAAM,KAAK,IAAI;EASrB,OALI,CAAC,KAAK,OAAO,SAAS,UAAUA,IAAM,KAAK,cAAcA,KAAO,KAA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AAIE,EAAM,MAAA,GACR,MAAM,IAAIF,EAAU,wBAAyD;CAG/E,IAAM,EAAE,UAAO,gBAAa,gBAAaE;CAEzC,IAAI,OAAOS,KAAU,YAAY,EAAEA,IAAQ,KAAKA,KAAA,OAC9C,MAAM,IAAIX,EACR,kDAAkD,OAAOT,CAA0B,EAAE,EACvF;CAGF,IAAIqB,MAAgB,KAAA,KAAa,CAACX,EAAOW,CAAW,GAClD,MAAM,IAAIZ,EAAU,2CAA2C;CAGjE,IACEF,MAAa,KAAA,KACb,EAAE,OAAOA,KAAa,YAAY,OAAO,OAAON,GAAaM,CAAQ,IAErE,MAAM,IAAIE,EAAU,mDAAmD;CAGzE,IAAMD,IAAqB,EAAE,OAAOO,EAAUJ,EAAM,KAAK,EAAE;CAU3D,OARIU,MAAgB,KAAA,MAClB,EAAM,cAAcA,IAGlBd,MAAa,KAAA,MACf,EAAM,WAAWA,IAGZ;EAAE;EAAO;CAAM;AACxB;AAQA,SAAgBe,EAAiB,GAAc,GAA+C;CAC5F,IAAI;EACF,OAAOH,EAAU,OAAOI,KAAQ,WAAWV,EAAUU,CAAG,IAAIA,CAAG;CACjE,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiBf,IAAY,IAAIe,EAAM,YAAY;EAQlE,OANAE,EAAY,OACV,kBACA,0DAA0DD,KAC1D,KAAA,GACAD,CACF,GACO;CACT;AACF;AAQA,SAAgBG,EACd,GACA,GACA,GACM;CAKN,AAJIvB,MACF,EAAK,aAAa,IAAIF,EAAeC,CAAM,IAG7CyB,EAAK,UAAU,MAAMxB,CAAM;AAC7B"}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { G as e, K as t, ct as n, d as r, hn as i, lt as a, n as o, s } from "./constants-N99w84xy.js";
|
|
2
|
-
//#region src/models/log-record.ts
|
|
3
|
-
function c() {
|
|
4
|
-
return `${String(Date.now())}000000`;
|
|
5
|
-
}
|
|
6
|
-
function l(e) {
|
|
7
|
-
return typeof e == "string" && Object.hasOwn(a, e);
|
|
8
|
-
}
|
|
9
|
-
function u(e) {
|
|
10
|
-
if (typeof e != "object" || !e) return !1;
|
|
11
|
-
let t = e;
|
|
12
|
-
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;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
|
-
//#region src/core/sampling.ts
|
|
16
|
-
function d(n) {
|
|
17
|
-
let r = e;
|
|
18
|
-
for (let e = 0; e < n.length; e++) r ^= n.charCodeAt(e), r = Math.imul(r, t);
|
|
19
|
-
return r >>> 0;
|
|
20
|
-
}
|
|
21
|
-
function f(e, t) {
|
|
22
|
-
let n = e.attributes[t];
|
|
23
|
-
return typeof n == "string" ? n : "";
|
|
24
|
-
}
|
|
25
|
-
function p(e, t) {
|
|
26
|
-
let n;
|
|
27
|
-
for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
|
|
28
|
-
rate: i,
|
|
29
|
-
length: r.length
|
|
30
|
-
});
|
|
31
|
-
return n;
|
|
32
|
-
}
|
|
33
|
-
function m(e, t, n) {
|
|
34
|
-
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = p(e, r), s = n ? p(e, n.rates) : void 0;
|
|
35
|
-
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);
|
|
36
|
-
}
|
|
37
|
-
function h(e, t, r) {
|
|
38
|
-
if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
39
|
-
let o = m(e.namespace, t, r), s = a[e.level] < a[t.minLevel];
|
|
40
|
-
return r && s && !n.includes(e.type) && (o = Math.min(o, t.sampling.remoteMaxRate)), o >= 1 ? !0 : o <= 0 ? !1 : d(e.journeyId || e.traceId) / i < o;
|
|
41
|
-
}
|
|
42
|
-
function g(e, t, n = null) {
|
|
43
|
-
return h({
|
|
44
|
-
level: e.severityText,
|
|
45
|
-
type: f(e, r),
|
|
46
|
-
namespace: f(e, o),
|
|
47
|
-
journeyId: f(e, s),
|
|
48
|
-
traceId: e.traceId
|
|
49
|
-
}, t, n);
|
|
50
|
-
}
|
|
51
|
-
var _ = class {
|
|
52
|
-
windowStart = 0;
|
|
53
|
-
count = 0;
|
|
54
|
-
allow(e) {
|
|
55
|
-
if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
|
|
56
|
-
let t = Date.now();
|
|
57
|
-
return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
//#endregion
|
|
61
|
-
export { u as a, l as i, g as n, c as o, h as r, _ as t };
|
|
62
|
-
|
|
63
|
-
//# sourceMappingURL=sampling-BN3Oi6SV.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-BN3Oi6SV.js","names":["FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","UINT32_MAX","LEVEL_ORDER","ATTR_APP_NAMESPACE","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","now"],"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 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 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}\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 and fatal records bypass sampling filters.\n if (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 },\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 /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private 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 const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;AA0DA,SAAgBO,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAOA,SAAgBC,EAAW,GAAmC;CAC5D,OAAO,OAAOC,KAAU,YAAY,OAAO,OAAOJ,GAAaI,CAAK;AACtE;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAME,IAASF;CACf,OACE,OAAOE,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AClEA,SAASC,EAAK,GAAuB;CACnC,IAAIC,IAAIb;CAER,KAAK,IAAIc,IAAI,GAAGA,IAAIL,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWK,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGZ,CAAS;CAG5B,OAAOY,MAAM;AACf;AASA,SAASE,EAAS,GAAmB,GAAqB;CACxD,IAAMN,IAAiBE,EAAO,WAAWK;CACzC,OAAO,OAAOP,KAAU,WAAWA,IAAQ;AAC7C;AAiBA,SAASQ,EAAc,GAAmB,GAAwD;CAChG,IAAIC;CAEJ,KAAK,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vB,EAAO;CAClB,GACAa,GACAG,CACF;AACF;AAQA,IAAaQ,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAIxB,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMyB,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-X86IDwkC.cjs");function t(){return`${String(Date.now())}000000`}function n(t){return typeof t==`string`&&Object.hasOwn(e.lt,t)}function r(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 i(t){let n=e.G;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.K);return n>>>0}function a(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function o(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 s(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,s=o(e,r),c=n?o(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.rate,a):s?s.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function c(t,n,r){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let a=s(t.namespace,n,r),o=e.lt[t.level]<e.lt[n.minLevel];return r&&o&&!e.ct.includes(t.type)&&(a=Math.min(a,n.sampling.remoteMaxRate)),a>=1?!0:a<=0?!1:i(t.journeyId||t.traceId)/e.hn<a}function l(t,n,r=null){return c({level:t.severityText,type:a(t,e.d),namespace:a(t,e.n),journeyId:a(t,e.s),traceId:t.traceId},n,r)}var u=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
|
|
2
|
-
//# sourceMappingURL=sampling-b2ck5X98.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-b2ck5X98.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","require_constants","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","now"],"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 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 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}\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 and fatal records bypass sampling filters.\n if (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 },\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 /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private 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 const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"4CA0DA,SAAgBU,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOZ,EAAAA,GAAaY,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,CClEA,SAASC,EAAK,EAAuB,CACnC,IAAIC,EAAIf,EAAAA,EAER,IAAK,IAAIgB,EAAI,EAAGA,EAAIL,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWK,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGd,EAAAA,CAAS,EAG5B,OAAOc,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,OAAO,QAAQC,CAAK,GAC/BC,IAAcH,GAAUG,EAAU,WAAW,GAAGH,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