@utk09/ui-observability 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/README.md +74 -33
- package/dist/bus/bus.d.ts +9 -0
- package/dist/bus-D3OO0OcL.js +378 -0
- package/dist/bus-D3OO0OcL.js.map +1 -0
- package/dist/bus-OdRJVUzr.cjs +2 -0
- package/dist/bus-OdRJVUzr.cjs.map +1 -0
- package/dist/capture/types.d.ts +14 -0
- package/dist/capture/web-vitals.d.ts +9 -3
- package/dist/{constants-CrU3IUyy.js → constants-B6kdsCzF.js} +9 -8
- package/dist/constants-B6kdsCzF.js.map +1 -0
- package/dist/constants-DZH04585.cjs +2 -0
- package/dist/constants-DZH04585.cjs.map +1 -0
- package/dist/constants.d.ts +8 -1
- package/dist/core/journey.d.ts +5 -2
- package/dist/core/logger.d.ts +22 -3
- package/dist/core/pipeline.d.ts +10 -1
- package/dist/core/runtime.d.ts +102 -18
- package/dist/core/sender.d.ts +58 -0
- package/dist/errors-DPju_xSI.cjs +3 -0
- package/dist/errors-DPju_xSI.cjs.map +1 -0
- package/dist/errors-Dme9tz-6.js +76 -0
- package/dist/errors-Dme9tz-6.js.map +1 -0
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +462 -2196
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
- package/dist/{indexeddb-storage-CSaDuHGk.js → indexeddb-storage-nxs_rxGx.js} +30 -17
- package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
- package/dist/interactions-C1romMpE.js +67 -0
- package/dist/interactions-C1romMpE.js.map +1 -0
- package/dist/interactions-DP0-rIPJ.cjs +2 -0
- package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
- package/dist/models/config.d.ts +29 -11
- package/dist/network-DDVIJSHd.cjs +2 -0
- package/dist/network-DDVIJSHd.cjs.map +1 -0
- package/dist/network-au-Tqt1n.js +111 -0
- package/dist/network-au-Tqt1n.js.map +1 -0
- package/dist/platform-DMYo3AX3.js +48 -0
- package/dist/platform-DMYo3AX3.js.map +1 -0
- package/dist/platform-g99Kn755.cjs +2 -0
- package/dist/platform-g99Kn755.cjs.map +1 -0
- package/dist/sampling-ByI5H44E.js +248 -0
- package/dist/sampling-ByI5H44E.js.map +1 -0
- package/dist/sampling-Dui-Fp3u.cjs +2 -0
- package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
- package/dist/sender-R7lOpyNc.js +907 -0
- package/dist/sender-R7lOpyNc.js.map +1 -0
- package/dist/sender-vLcbQhiB.cjs +3 -0
- package/dist/sender-vLcbQhiB.cjs.map +1 -0
- package/dist/storage/idb-driver.d.ts +9 -1
- package/dist/storage/indexeddb-storage.d.ts +5 -0
- package/dist/transport/exit-flush.d.ts +11 -1
- package/dist/transport/http-transport.d.ts +2 -0
- package/dist/transport/retry-engine.d.ts +28 -3
- package/dist/transport/serializers/select.d.ts +8 -0
- package/dist/unref-16maCyKA.js +8 -0
- package/dist/unref-16maCyKA.js.map +1 -0
- package/dist/unref-CU9Nyz_9.cjs +2 -0
- package/dist/unref-CU9Nyz_9.cjs.map +1 -0
- package/dist/utils/console.d.ts +11 -3
- package/dist/utils/deadline.d.ts +7 -0
- package/dist/utils/identity.d.ts +47 -3
- package/dist/utils/tracing.d.ts +6 -5
- package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
- package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
- package/dist/web-vitals-DwWdLBq6.js +51 -0
- package/dist/web-vitals-DwWdLBq6.js.map +1 -0
- package/package.json +21 -11
- package/dist/constants-BpFlszME.cjs +0 -2
- package/dist/constants-BpFlszME.cjs.map +0 -1
- package/dist/constants-CrU3IUyy.js.map +0 -1
- package/dist/indexeddb-storage-CSaDuHGk.js.map +0 -1
- package/dist/indexeddb-storage-DIJIbFnp.cjs +0 -2
- package/dist/indexeddb-storage-DIJIbFnp.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-au-Tqt1n.js","names":["stripUrlQuery","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface consumed by auto-capture modules. Naming the runtime class\n * here instead would cycle: the runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances, so instance state cannot\n * hold this. web-vitals has no unsubscribe, and a second subscription reports\n * each metric two times.\n */\nexport interface CaptureOnce {\n /** True once the web-vitals reporters are subscribed. */\n webVitals: boolean;\n /** True once navigation timing has been reported. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. Patching an\n * already patched function chains the wrapper and doubles every record, so a\n * second call must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if URL should be excluded from telemetry.\n */\n private ignored(url: string): boolean {\n // The endpoint is always in ignoreUrls, added by resolveConfig. Without it\n // one failed POST logs, which POSTs, which logs, forever.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Allowlist only. An unexpected traceparent on a third-party request\n // forces a CORS preflight they will not answer, and their API stops\n // working inside the consumer's application.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Never spread a non-empty init alongside a Request input: that\n // re-runs the Request constructor over `input` and consumes its\n // body, which throws TypeError on an already-read body.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send exactly what the caller passed. Losing our header is always\n // better than breaking their request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"could not attach traceparent, sending the request unchanged\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL, scrubbed before it is recorded.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Scrubbed here, not at the call sites: ignoreUrls and propagateTraceHeaderTo\n // match on the whole URL, so only what is recorded loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // A throw here runs inside the caller's own fetch. Breaking their request\n // to record that their request broke is the one unacceptable outcome.\n this.ctx.diagnostics.guard(\"capture.record_failed\", `recording ${method} ${url}`, () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // DEBUG, so a successful request is dropped by the default minLevel of\n // INFO and only failures cost bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n });\n }\n}\n"],"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K,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,KAAKqB,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,KAAO6B,CAAU;EACtD,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { ct as e, dt as t, et as n, gt as r, t as i } from "./constants-B6kdsCzF.js";
|
|
2
|
+
//#region src/utils/platform.ts
|
|
3
|
+
var a = null;
|
|
4
|
+
function o(e, t) {
|
|
5
|
+
let n = e[t];
|
|
6
|
+
return n !== void 0 && e instanceof n;
|
|
7
|
+
}
|
|
8
|
+
function s(e) {
|
|
9
|
+
if (a) return a;
|
|
10
|
+
let t = globalThis, n = t.navigator?.userAgent ?? "", i = "browser", s, u, d = !1, f = t.fin?.me;
|
|
11
|
+
return o(t, "ServiceWorkerGlobalScope") ? (i = "service_worker", d = !0) : o(t, "SharedWorkerGlobalScope") ? (i = "shared_worker", d = !0) : o(t, "WorkerGlobalScope") ? (i = "web_worker", d = !0) : f === void 0 ? t.Capacitor !== void 0 || t.Ionic !== void 0 ? i = "ionic" : t.cordova !== void 0 || c(n) ? i = "mobile_webview" : typeof document > "u" && typeof process < "u" && (i = "node") : (i = r.test(n) ? "openfin" : "openfin_web", e.guard("openfin.unavailable", "reading fin.me.identity", () => {
|
|
12
|
+
let e = f.identity;
|
|
13
|
+
s = e?.uuid, u = e?.name;
|
|
14
|
+
})), a = {
|
|
15
|
+
platform: i,
|
|
16
|
+
openfinUuid: s,
|
|
17
|
+
openfinName: u,
|
|
18
|
+
userAgent: n,
|
|
19
|
+
isWorker: d,
|
|
20
|
+
isTopLevelDocument: l()
|
|
21
|
+
}, a;
|
|
22
|
+
}
|
|
23
|
+
function c(r) {
|
|
24
|
+
return i.test(r) ? !0 : (n.test(r) || e.test(r) && t.test(r)) && r.includes("AppleWebKit") && !r.includes("Safari/");
|
|
25
|
+
}
|
|
26
|
+
function l() {
|
|
27
|
+
if (typeof window > "u") return !1;
|
|
28
|
+
try {
|
|
29
|
+
return window.self === window.top;
|
|
30
|
+
} catch {
|
|
31
|
+
return !1;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function u() {
|
|
35
|
+
try {
|
|
36
|
+
return typeof location < "u" ? location.href : "";
|
|
37
|
+
} catch {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function d(e) {
|
|
42
|
+
let t = e.search(/[?#]/);
|
|
43
|
+
return t === -1 ? e : e.slice(0, t);
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { s as n, d as r, u as t };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=platform-DMYo3AX3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-DMYo3AX3.js","names":["MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","IOS_DEVICE_UA_PATTERN","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. Cached: nothing here changes for the lifetime of a realm.\n// Order matters, a webview is also a browser and is tested 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\";\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 /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether 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 * Evaluates whether 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/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\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 = (g.fin as FinLike | undefined)?.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\", \"reading 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(),\n };\n return cached;\n}\n\n/**\n * Evaluates whether 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 * Determines whether the current window is the top-level browsing context.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * A string cut, not a URL parse: a relative request target has no base to parse against.\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/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAASR,EAAE,KAA6B;CAkC9C,OAhCIF,EAAcE,GAAG,0BAA0B,KAC7C,IAAW,kBACX,IAAW,MACFF,EAAcE,GAAG,yBAAyB,KACnD,IAAW,iBACX,IAAW,MACFF,EAAcE,GAAG,mBAAmB,KAC7C,IAAW,cACX,IAAW,MACFQ,MAAU,KAAA,IAOVR,EAAE,cAAc,KAAA,KAAaA,EAAE,UAAU,KAAA,IAClD,IAAW,UACFA,EAAE,YAAY,KAAA,KAAaS,EAAUN,CAAE,IAChD,IAAW,mBACF,OAAO,WAAa,OAAe,OAAO,UAAY,QAC/D,IAAW,WAXX,IAAWR,EAAmB,KAAKQ,CAAE,IAAI,YAAY,eACrDO,EAAY,MAAM,uBAAuB,iCAAiC;EACxE,IAAMC,IAAWH,EAAM;EAEvB,AADA,IAAcG,GAAU,MACxB,IAAcA,GAAU;CAC1B,CAAC,IASH,IAAS;EACP;EACA;EACA;EACA,WAAWR;EACX;EACA,oBAAoBS,EAAW;CACjC,GACOf;AACT;AAOA,SAASY,EAAU,GAAqB;CAMtC,OALIb,EAA2B,KAAKO,CAAE,IAC7B,MAGPT,EAAsB,KAAKS,CAAE,KAAMX,EAAqB,KAAKW,CAAE,KAAKV,EAAkB,KAAKU,CAAE,MACjFA,EAAG,SAAA,aAAwB,KAAK,CAACA,EAAG,SAAA,SAAwB;AAC5E;AAMA,SAAgBS,IAAsB;CACpC,IAAI,OAAO,SAAW,KACpB,OAAO;CAET,IAAI;EACF,OAAO,OAAO,SAAS,OAAO;CAChC,QAAQ;EACN,OAAO;CACT;AACF;AAMA,SAAgBC,IAAqB;CACnC,IAAI;EACF,OAAO,OAAO,WAAa,MAAc,SAAS,OAAO;CAC3D,QAAQ;EACN,OAAO;CACT;AACF;AAQA,SAAgBC,EAAc,GAAqB;CACjD,IAAMC,IAAMC,EAAI,OAAO,MAAM;CAE7B,OAAOD,MAAQ,KAAKC,IAAMA,EAAI,MAAM,GAAGD,CAAG;AAC5C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-DZH04585.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.gt.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`reading fin.me.identity`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a()},t}function i(t){return e.t.test(t)?!0:(e.et.test(t)||e.ct.test(t)&&e.dt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return!1}}function o(){try{return typeof location<`u`?location.href:``}catch{return``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=platform-g99Kn755.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-g99Kn755.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. Cached: nothing here changes for the lifetime of a realm.\n// Order matters, a webview is also a browser and is tested 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\";\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 /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether 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 * Evaluates whether 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/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\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 = (g.fin as FinLike | undefined)?.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\", \"reading 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(),\n };\n return cached;\n}\n\n/**\n * Evaluates whether 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 * Determines whether the current window is the top-level browsing context.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * A string cut, not a URL parse: a relative request target has no base to parse against.\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/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAYA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAO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AqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { H as e, U as t, Ut as n, a as r, l as i, n as a, sn as o, tn as s } from "./constants-B6kdsCzF.js";
|
|
2
|
+
import { t as c } from "./unref-16maCyKA.js";
|
|
3
|
+
//#region src/models/log-record.ts
|
|
4
|
+
function l() {
|
|
5
|
+
return `${String(Date.now())}000000`;
|
|
6
|
+
}
|
|
7
|
+
function u(e) {
|
|
8
|
+
if (typeof e != "object" || !e) return !1;
|
|
9
|
+
let t = e;
|
|
10
|
+
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;
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/utils/sanitize.ts
|
|
14
|
+
function d(e, t) {
|
|
15
|
+
if (e.length <= t) return e;
|
|
16
|
+
let n = f(e.charCodeAt(t - 1)) ? t - 1 : t;
|
|
17
|
+
return `${e.slice(0, n)}… [truncated ${String(e.length - n)} chars]`;
|
|
18
|
+
}
|
|
19
|
+
function f(e) {
|
|
20
|
+
return e >= 55296 && e <= 56319;
|
|
21
|
+
}
|
|
22
|
+
function p(e) {
|
|
23
|
+
return `[Element ${(e.nodeName ?? "NODE").toLowerCase()}${e.id ? `#${e.id}` : ""}${typeof e.className == "string" && e.className ? `.${e.className.trim().split(/\s+/).slice(0, 3).join(".")}` : ""}]`;
|
|
24
|
+
}
|
|
25
|
+
function m(e, t) {
|
|
26
|
+
return h(e, t).value;
|
|
27
|
+
}
|
|
28
|
+
function h(e, t) {
|
|
29
|
+
let n = {
|
|
30
|
+
bytes: 0,
|
|
31
|
+
nodes: 0
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
value: _(e, t, /* @__PURE__ */ new WeakSet(), 0, n),
|
|
35
|
+
bytes: n.bytes
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function g(e, t) {
|
|
39
|
+
return t.bytes += v(e) + 2, e;
|
|
40
|
+
}
|
|
41
|
+
function _(e, t, n, r, i) {
|
|
42
|
+
if (i.nodes++, i.nodes > t.maxNodes) return g("[MaxNodes]", i);
|
|
43
|
+
if (e == null) return i.bytes += 4, e;
|
|
44
|
+
if (typeof e == "string") return g(d(e, t.maxAttributeChars), i);
|
|
45
|
+
if (typeof e == "number") return i.bytes += 8, Number.isFinite(e) ? e : String(e);
|
|
46
|
+
if (typeof e == "boolean") return i.bytes += 5, e;
|
|
47
|
+
if (typeof e == "bigint") return g(`${e.toString()}n`, i);
|
|
48
|
+
if (typeof e == "symbol") return g(e.toString(), i);
|
|
49
|
+
if (typeof e == "function") return g(`[Function ${e.name === "" ? "anonymous" : e.name}]`, i);
|
|
50
|
+
if (r >= t.maxDepth) return g("[MaxDepth]", i);
|
|
51
|
+
if (n.has(e)) return g("[Circular]", i);
|
|
52
|
+
n.add(e), i.bytes += 2;
|
|
53
|
+
try {
|
|
54
|
+
if (e instanceof Error) return {
|
|
55
|
+
name: g(e.name, i),
|
|
56
|
+
message: g(d(e.message, t.maxAttributeChars), i),
|
|
57
|
+
stack: e.stack ? g(d(e.stack, t.maxStackChars), i) : void 0,
|
|
58
|
+
cause: e.cause ? _(e.cause, t, n, r + 1, i) : void 0
|
|
59
|
+
};
|
|
60
|
+
if (e instanceof Date) return g(e.toISOString(), i);
|
|
61
|
+
if (e instanceof RegExp) return g(e.toString(), i);
|
|
62
|
+
if (e instanceof Map) {
|
|
63
|
+
let a = e, o = {}, s = 0;
|
|
64
|
+
for (let [e, c] of a) {
|
|
65
|
+
if (s >= t.maxArrayLength) {
|
|
66
|
+
o["…"] = g(`[${String(a.size - t.maxArrayLength)} more entries]`, i);
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
s++;
|
|
70
|
+
let l = String(e);
|
|
71
|
+
i.bytes += v(l) + 4, o[l] = _(c, t, n, r + 1, i);
|
|
72
|
+
}
|
|
73
|
+
return o;
|
|
74
|
+
}
|
|
75
|
+
if (e instanceof Set) return _([...e].slice(0, t.maxArrayLength), t, n, r, i);
|
|
76
|
+
if (ArrayBuffer.isView(e)) {
|
|
77
|
+
let t = e.length ?? 0;
|
|
78
|
+
return g(`[${e.constructor.name}(${String(t)})]`, i);
|
|
79
|
+
}
|
|
80
|
+
if (e instanceof Promise) return g("[Promise]", i);
|
|
81
|
+
if (typeof Node < "u" && e instanceof Node) return g(p(e), i);
|
|
82
|
+
if (Array.isArray(e)) {
|
|
83
|
+
let a = e, o = a.slice(0, t.maxArrayLength).map((e) => _(e, t, n, r + 1, i));
|
|
84
|
+
return a.length > t.maxArrayLength && o.push(g(`[${String(a.length - t.maxArrayLength)} more items]`, i)), o;
|
|
85
|
+
}
|
|
86
|
+
let a = e.toJSON;
|
|
87
|
+
if (typeof a == "function") return _(a.call(e), t, n, r + 1, i);
|
|
88
|
+
let o = e, s = Object.keys(o), c = {}, l = 0;
|
|
89
|
+
for (let e of s) {
|
|
90
|
+
if (l >= t.maxAttributeCount) {
|
|
91
|
+
c["…"] = g(`[${String(s.length - l)} more keys]`, i);
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
l++, i.bytes += v(e) + 4, c[e] = _(o[e], t, n, r + 1, i);
|
|
95
|
+
}
|
|
96
|
+
return c;
|
|
97
|
+
} catch (e) {
|
|
98
|
+
return g(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
|
|
99
|
+
} finally {
|
|
100
|
+
n.delete(e);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function v(e) {
|
|
104
|
+
let t = 0;
|
|
105
|
+
for (let n = 0; n < e.length; n++) {
|
|
106
|
+
let r = e.charCodeAt(n);
|
|
107
|
+
r < 128 ? t += 1 : r < 2048 ? t += 2 : r >= 55296 && r <= 56319 ? (t += 4, n++) : t += 3;
|
|
108
|
+
}
|
|
109
|
+
return t;
|
|
110
|
+
}
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region src/utils/identity.ts
|
|
113
|
+
var y = {
|
|
114
|
+
local: () => localStorage,
|
|
115
|
+
session: () => sessionStorage
|
|
116
|
+
};
|
|
117
|
+
function b() {
|
|
118
|
+
let e = (e) => ({
|
|
119
|
+
getItem: (t) => e.get(t) ?? null,
|
|
120
|
+
setItem: (t, n) => {
|
|
121
|
+
e.set(t, n);
|
|
122
|
+
},
|
|
123
|
+
removeItem: (t) => {
|
|
124
|
+
e.delete(t);
|
|
125
|
+
}
|
|
126
|
+
}), t = e(/* @__PURE__ */ new Map()), n = e(/* @__PURE__ */ new Map());
|
|
127
|
+
return {
|
|
128
|
+
local: () => t,
|
|
129
|
+
session: () => n
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function x(e) {
|
|
133
|
+
let t = new Uint8Array(e);
|
|
134
|
+
if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
|
|
135
|
+
else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
|
|
136
|
+
return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
|
|
137
|
+
}
|
|
138
|
+
function S() {
|
|
139
|
+
try {
|
|
140
|
+
if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
|
|
141
|
+
} catch {}
|
|
142
|
+
return x(16);
|
|
143
|
+
}
|
|
144
|
+
function C(e, t, n, r) {
|
|
145
|
+
return r.guard("storage.unavailable", `reading ${t}Storage`, () => e[t]().getItem(n)) ?? null;
|
|
146
|
+
}
|
|
147
|
+
function w(e, t, n, r, i) {
|
|
148
|
+
i.guard("storage.unavailable", `writing ${t}Storage`, () => {
|
|
149
|
+
e[t]().setItem(n, r);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
function T(e, t = y) {
|
|
153
|
+
let r = S(), i = Date.now(), a = S(), o = C(t, "local", n, e);
|
|
154
|
+
if (o) try {
|
|
155
|
+
let e = JSON.parse(o);
|
|
156
|
+
e.id && i - (e.lastSeenAt ?? 0) < 18e5 && (a = e.id);
|
|
157
|
+
} catch {
|
|
158
|
+
e.report("storage.degraded", "session record was not JSON, starting a new session");
|
|
159
|
+
}
|
|
160
|
+
let c = JSON.stringify({
|
|
161
|
+
id: a,
|
|
162
|
+
lastSeenAt: i
|
|
163
|
+
});
|
|
164
|
+
w(t, "local", n, c, e);
|
|
165
|
+
let l = C(t, "session", "ui-observability.tab", e) ?? "";
|
|
166
|
+
return l || (l = S(), w(t, "session", s, l, e)), {
|
|
167
|
+
sessionId: a,
|
|
168
|
+
tabId: l,
|
|
169
|
+
contextId: r
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function E(e, t, n) {
|
|
173
|
+
w(n, "session", s, e, t);
|
|
174
|
+
}
|
|
175
|
+
var D = class {
|
|
176
|
+
diagnostics;
|
|
177
|
+
stores;
|
|
178
|
+
lastTouchAt = 0;
|
|
179
|
+
constructor(e, t = y) {
|
|
180
|
+
this.diagnostics = e, this.stores = t;
|
|
181
|
+
}
|
|
182
|
+
touch(e) {
|
|
183
|
+
let t = Date.now();
|
|
184
|
+
if (t - this.lastTouchAt < 6e4) return;
|
|
185
|
+
this.lastTouchAt = t;
|
|
186
|
+
let r = JSON.stringify({
|
|
187
|
+
id: e,
|
|
188
|
+
lastSeenAt: t
|
|
189
|
+
});
|
|
190
|
+
w(this.stores, "local", n, r, this.diagnostics);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/utils/deadline.ts
|
|
195
|
+
function O(e, t) {
|
|
196
|
+
let n, r = new Promise((e, r) => {
|
|
197
|
+
let i = setTimeout(() => {
|
|
198
|
+
r(/* @__PURE__ */ Error(`timed out after ${String(t)}ms`));
|
|
199
|
+
}, t);
|
|
200
|
+
n = i, c(i);
|
|
201
|
+
});
|
|
202
|
+
return Promise.race([e, r]).finally(() => {
|
|
203
|
+
clearTimeout(n);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/core/sampling.ts
|
|
208
|
+
function k(n) {
|
|
209
|
+
let r = e;
|
|
210
|
+
for (let e = 0; e < n.length; e++) r ^= n.charCodeAt(e), r = Math.imul(r, t);
|
|
211
|
+
return r >>> 0;
|
|
212
|
+
}
|
|
213
|
+
function A(e, t) {
|
|
214
|
+
let n = e.attributes[t];
|
|
215
|
+
return typeof n == "string" ? n : "";
|
|
216
|
+
}
|
|
217
|
+
function j(e, t) {
|
|
218
|
+
let { rates: n, defaultRate: r } = t.sampling, i, a = -1;
|
|
219
|
+
for (let [t, r] of Object.entries(n)) (e === t || e.startsWith(`${t}.`)) && t.length > a && (i = r, a = t.length);
|
|
220
|
+
return i ?? r;
|
|
221
|
+
}
|
|
222
|
+
function M(e, t) {
|
|
223
|
+
if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
224
|
+
let n = j(e.namespace, t);
|
|
225
|
+
return n >= 1 ? !0 : n <= 0 ? !1 : k(e.journeyId || e.traceId) / o < n;
|
|
226
|
+
}
|
|
227
|
+
function N(e, t) {
|
|
228
|
+
return M({
|
|
229
|
+
level: e.severityText,
|
|
230
|
+
type: A(e, i),
|
|
231
|
+
namespace: A(e, a),
|
|
232
|
+
journeyId: A(e, r),
|
|
233
|
+
traceId: e.traceId
|
|
234
|
+
}, t);
|
|
235
|
+
}
|
|
236
|
+
var P = class {
|
|
237
|
+
windowStart = 0;
|
|
238
|
+
count = 0;
|
|
239
|
+
allow(e) {
|
|
240
|
+
if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
|
|
241
|
+
let t = Date.now();
|
|
242
|
+
return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
//#endregion
|
|
246
|
+
export { l as _, y as a, S as c, T as d, v as f, u as g, d as h, O as i, E as l, h as m, N as n, D as o, m as p, M as r, b as s, P as t, x as u };
|
|
247
|
+
|
|
248
|
+
//# sourceMappingURL=sampling-ByI5H44E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling-ByI5H44E.js","names":["set","toJson","FNV_OFFSET_BASIS","FNV_PRIME","SESSION_ID_KEY","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","UINT32_MAX","TAB_ID_KEY","unrefTimer","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.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// Severity tables live in `src/constants.ts`.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape, converted to wire format by a serializer. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. Only the sampled bit is used. */\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 * Concatenates rather than multiplies: `Date.now() * 1e6` overflows\n * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are\n * unknown precision, not real.\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 whether a value has the shape `LogRecord` requires.\n * Used to validate records arriving from another realm, since a malformed\n * one throws during serialization. `severityText` is checked as a string,\n * not a known level, so an unrecognised level from a newer version still\n * passes.\n * @param value The value to check.\n * @returns Whether `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 // Widened to `unknown` rather than asserted as `Partial<LogRecord>`, which\n // would tell the compiler these fields are never null and make the checks\n // below 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/utils/sanitize.ts\n//\n// Sanitizes arbitrary data into JSON-safe structures with cycle detection and byte-size estimation.\n// Never throws. Never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(value: unknown, limits: SanitizeLimits): unknown {\n return sanitizeWithSize(value, limits).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(value: unknown, limits: SanitizeLimits): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0 };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Recursively walks object trees, replacing cyclic references, hostile getters, and invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits cannot bound a wide tree: 128 keys over 6 levels is\n // 128^6 values, all walked synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catches hostile getters and throwing proxies. One costs an attribute, not the\n // record.\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Removes object from ancestor set on unwind. Left in, a repeated sibling reads\n // as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. Storage\n// throws rather than returning null in a sandboxed iframe and in private mode. An\n// unguarded read takes the library down at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * Uses crypto.getRandomValues when available, falling back to Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @returns UUID or random hex identifier.\n */\nexport function newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // Catches sandbox SecurityError throws when crypto.randomUUID is blocked. The\n // method is present; only the call fails.\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `reading ${store}Storage`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\"storage.unavailable\", `writing ${store}Storage`, () => {\n stores[store]().setItem(key, value);\n });\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId();\n const now = Date.now();\n\n let sessionId = newId();\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\"storage.degraded\", \"session record was not JSON, starting a new session\");\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId();\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.\n * The throttle is instance state, not module state: two runtimes in one document\n * must not silence each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event, so its caller waits with it and holds the slot it took.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`timed out after ${String(ms)}ms`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Cleared on both paths. One armed timer for each storage call is waste.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// Deterministic record sampling based on namespace rules, journey IDs, and trace\n// IDs. Keyed on the journey, so one journey is kept or dropped whole. Stable\n// 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 SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes 32-bit FNV-1a hash of a string value. Not 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 * Safely extracts a string attribute value from a log record. Absent and non-string\n * both read as empty. A forwarded record has only passed a shape check.\n * @param record Log record being evaluated.\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/**\n * Resolves sampling rate for a namespace using longest-prefix matching, so\n * trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Everything sampling reads, all of it known before a record is built. */\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, empty when no journey is running. */\n journeyId: string;\n /** Trace id, the sampling key when no journey is running. */\n traceId: string;\n}\n\n/**\n * Evaluates whether an entry should be sampled for retention. Takes the fields\n * rather than a record, so the verdict is available before the attribute walk\n * a dropped entry must not pay for.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the entry should be retained and transmitted.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): 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 const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Falls back to trace ID when journey ID is absent. The trace still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Evaluates whether a built log record should be sampled for retention. Used on\n * records that arrive already built, from a child context over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the record should be retained and transmitted.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): 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 );\n}\n\n/**\n * Fixed-window ceiling on the ERROR and FATAL records that bypass sampling.\n *\n * Auto-captured errors are already limited inside ErrorCapture. This covers the\n * case nothing else does: application code calling logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the window currently counting, 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 * Admits a record against the ceiling, counting only ERROR and FATAL.\n * @param record Record about to enter a stream.\n * @returns False when the window is spent and the record must be dropped.\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 // Fixed window, not a sliding one: a quiet spell banks 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":";;;AAqDA,SAAgBW,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAWA,SAAgBC,EAAY,GAAoC;C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;AAQA,IAAaW,IAAb,MAA0B;CAExB,cAAsB;CAGtB,QAAgB;CAOhB,MAAM,GAA4B;EAChC,IAAI9E,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,SAC7D,OAAO;EAGT,IAAMiD,IAAM,KAAK,IAAI;EASrB,OAPIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,QAAQ,IAGf,KAAK,SAEE,KAAK,SAAA;CACd;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-DZH04585.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(){return`${String(Date.now())}000000`}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(e,t){if(e.length<=t)return e;let n=a(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function a(e){return e>=55296&&e<=56319}function o(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function s(e,t){return c(e,t).value}function c(e,t){let n={bytes:0,nodes:0};return{value:u(e,t,new WeakSet,0,n),bytes:n.bytes}}function l(e,t){return t.bytes+=d(e)+2,e}function u(e,t,n,r,a){if(a.nodes++,a.nodes>t.maxNodes)return l(`[MaxNodes]`,a);if(e==null)return a.bytes+=4,e;if(typeof e==`string`)return l(i(e,t.maxAttributeChars),a);if(typeof e==`number`)return a.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return a.bytes+=5,e;if(typeof e==`bigint`)return l(`${e.toString()}n`,a);if(typeof e==`symbol`)return l(e.toString(),a);if(typeof e==`function`)return l(`[Function ${e.name===``?`anonymous`:e.name}]`,a);if(r>=t.maxDepth)return l(`[MaxDepth]`,a);if(n.has(e))return l(`[Circular]`,a);n.add(e),a.bytes+=2;try{if(e instanceof Error)return{name:l(e.name,a),message:l(i(e.message,t.maxAttributeChars),a),stack:e.stack?l(i(e.stack,t.maxStackChars),a):void 0,cause:e.cause?u(e.cause,t,n,r+1,a):void 0};if(e instanceof Date)return l(e.toISOString(),a);if(e instanceof RegExp)return l(e.toString(),a);if(e instanceof Map){let i=e,o={},s=0;for(let[e,c]of i){if(s>=t.maxArrayLength){o[`…`]=l(`[${String(i.size-t.maxArrayLength)} more entries]`,a);break}s++;let f=String(e);a.bytes+=d(f)+4,o[f]=u(c,t,n,r+1,a)}return o}if(e instanceof Set)return u([...e].slice(0,t.maxArrayLength),t,n,r,a);if(ArrayBuffer.isView(e)){let t=e.length??0;return l(`[${e.constructor.name}(${String(t)})]`,a)}if(e instanceof Promise)return l(`[Promise]`,a);if(typeof Node<`u`&&e instanceof Node)return l(o(e),a);if(Array.isArray(e)){let i=e,o=i.slice(0,t.maxArrayLength).map(e=>u(e,t,n,r+1,a));return i.length>t.maxArrayLength&&o.push(l(`[${String(i.length-t.maxArrayLength)} more items]`,a)),o}let s=e.toJSON;if(typeof s==`function`)return u(s.call(e),t,n,r+1,a);let c=e,f=Object.keys(c),p={},m=0;for(let e of f){if(m>=t.maxAttributeCount){p[`…`]=l(`[${String(f.length-m)} more keys]`,a);break}m++,a.bytes+=d(e)+4,p[e]=u(c[e],t,n,r+1,a)}return p}catch(e){return l(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,a)}finally{n.delete(e)}}function d(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}var f={local:()=>localStorage,session:()=>sessionStorage};function p(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function m(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function h(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return m(16)}function g(e,t,n,r){return r.guard(`storage.unavailable`,`reading ${t}Storage`,()=>e[t]().getItem(n))??null}function _(e,t,n,r,i){i.guard(`storage.unavailable`,`writing ${t}Storage`,()=>{e[t]().setItem(n,r)})}function v(t,n=f){let r=h(),i=Date.now(),a=h(),o=g(n,`local`,e.Ut,t);if(o)try{let e=JSON.parse(o);e.id&&i-(e.lastSeenAt??0)<18e5&&(a=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let s=JSON.stringify({id:a,lastSeenAt:i});_(n,`local`,e.Ut,s,t);let c=g(n,`session`,`ui-observability.tab`,t)??``;return c||(c=h(),_(n,`session`,e.tn,c,t)),{sessionId:a,tabId:c,contextId:r}}function y(t,n,r){_(r,`session`,e.tn,t,n)}var b=class{diagnostics;stores;lastTouchAt=0;constructor(e,t=f){this.diagnostics=e,this.stores=t}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});_(this.stores,`local`,e.Ut,r,this.diagnostics)}};function x(e,n){let r,i=new Promise((e,i)=>{let a=setTimeout(()=>{i(Error(`timed out after ${String(n)}ms`))},n);r=a,t.t(a)});return Promise.race([e,i]).finally(()=>{clearTimeout(r)})}function S(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function C(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function w(e,t){let{rates:n,defaultRate:r}=t.sampling,i,a=-1;for(let[t,r]of Object.entries(n))(e===t||e.startsWith(`${t}.`))&&t.length>a&&(i=r,a=t.length);return i??r}function T(t,n){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let r=w(t.namespace,n);return r>=1?!0:r<=0?!1:S(t.journeyId||t.traceId)/e.sn<r}function E(t,n){return T({level:t.severityText,type:C(t,e.l),namespace:C(t,e.n),journeyId:C(t,e.a),traceId:t.traceId},n)}var D=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,"_",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return m}});
|
|
2
|
+
//# sourceMappingURL=sampling-Dui-Fp3u.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling-Dui-Fp3u.cjs","names":["set","toJson","SESSION_ID_KEY","TAB_ID_KEY","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","require_unref","nowUnixNano","isLogRecord","value","record","truncate","max","end","isHighSurrogate","code","describeNode","node","sanitize","sanitizeWithSize","limits","state","walk","counted","estimateBytes","text","depth","seen","map","out","shown","key","entry","name","length","items","item","maybeToJson","keys","count","error","bytes","i","BROWSER_STORES","memoryStores","wrap","localStore","sessionStore","randomHex","byteLength","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","withDeadline","expire","deadline","timer","reject","ms","work","hash","h","readAttr","rateFor","config","best","bestLength","prefix","rate","rates","namespace","defaultRate","shouldSampleInput","input","shouldSample","ErrorCeiling"],"sources":["../src/models/log-record.ts","../src/utils/sanitize.ts","../src/utils/identity.ts","../src/utils/deadline.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// Severity tables live in `src/constants.ts`.\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing a record describes: `action` (something a person did),\n * `event` (something the application did), `metric` (a measurement), or\n * `system` (this library's own diagnostic output).\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape, converted to wire format by a serializer. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. Only the sampled bit is used. */\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 * Concatenates rather than multiplies: `Date.now() * 1e6` overflows\n * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are\n * unknown precision, not real.\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 whether a value has the shape `LogRecord` requires.\n * Used to validate records arriving from another realm, since a malformed\n * one throws during serialization. `severityText` is checked as a string,\n * not a known level, so an unrecognised level from a newer version still\n * passes.\n * @param value The value to check.\n * @returns Whether `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 // Widened to `unknown` rather than asserted as `Partial<LogRecord>`, which\n // would tell the compiler these fields are never null and make the checks\n // below 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/utils/sanitize.ts\n//\n// Sanitizes arbitrary data into JSON-safe structures with cycle detection and byte-size estimation.\n// Never throws. Never returns a circular structure.\n\nimport {\n BYTES_PER_BOOLEAN,\n BYTES_PER_CONTAINER,\n BYTES_PER_KEY_OVERHEAD,\n BYTES_PER_NULL,\n BYTES_PER_NUMBER,\n BYTES_PER_QUOTED_STRING,\n HIGH_SURROGATE_MAX,\n HIGH_SURROGATE_MIN,\n MAX_NODE_CLASS_NAMES,\n UTF8_ONE_BYTE_CEILING,\n UTF8_TWO_BYTE_CEILING,\n} from \"../constants\";\n\n/** Structural depth and size limits enforced during object sanitization. */\nexport interface SanitizeLimits {\n /** Maximum recursion depth before truncating nested objects. */\n maxDepth: number;\n /** Maximum items retained in arrays, sets, and maps before truncating. */\n maxArrayLength: number;\n /** Maximum string attribute length in characters. */\n maxAttributeChars: number;\n /** Maximum key-value properties retained in a single object. */\n maxAttributeCount: number;\n /** Maximum error stack trace length in characters. */\n maxStackChars: number;\n /** Maximum values visited in one pass, across the whole tree. */\n maxNodes: number;\n}\n\n/**\n * Truncates a string to maximum character length while preserving UTF-16 surrogate pairs.\n * @param value Target string.\n * @param max Maximum allowed character length.\n * @returns Truncated string with appended drop count suffix.\n */\nexport function truncate(value: string, max: number): string {\n if (value.length <= max) {\n return value;\n }\n\n // Avoids splitting UTF-16 surrogate pairs at truncation boundaries. slice works in\n // code units. Half a pair serializes as U+FFFD.\n const end = isHighSurrogate(value.charCodeAt(max - 1)) ? max - 1 : max;\n return `${value.slice(0, end)}… [truncated ${String(value.length - end)} chars]`;\n}\n\n/**\n * Evaluates whether a UTF-16 code unit is a leading surrogate.\n * @param code UTF-16 character code.\n * @returns True if character is a high surrogate.\n */\nfunction isHighSurrogate(code: number): boolean {\n return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;\n}\n\n/** Structural interface for DOM Node inspection across realms. */\ninterface NodeLike {\n nodeName?: string;\n id?: string;\n className?: unknown;\n}\n\n/**\n * Formats a DOM node as a descriptive CSS selector string.\n * @param node Node-like object to format.\n * @returns Formatted selector string.\n */\nfunction describeNode(node: NodeLike): string {\n const tag = (node.nodeName ?? \"NODE\").toLowerCase();\n const id = node.id ? `#${node.id}` : \"\";\n const cls =\n typeof node.className === \"string\" && node.className\n ? `.${node.className.trim().split(/\\s+/).slice(0, MAX_NODE_CLASS_NAMES).join(\".\")}`\n : \"\";\n return `[Element ${tag}${id}${cls}]`;\n}\n\n/** Sanitized JSON-safe output with estimated serialized byte size. */\nexport interface SanitizeResult {\n /** JSON-safe sanitized structure. */\n value: unknown;\n /** Approximate serialized byte count. */\n bytes: number;\n}\n\n/** Mutable accumulators passed through recursive sanitization passes. */\ninterface WalkState {\n /** Running estimate of the serialized byte count. */\n bytes: number;\n /** Count of values visited so far. */\n nodes: number;\n}\n\n/**\n * Sanitizes arbitrary values into JSON-safe structures without throwing.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits for depth, count, and character lengths.\n * @returns JSON-safe sanitized value.\n */\nexport function sanitize(value: unknown, limits: SanitizeLimits): unknown {\n return sanitizeWithSize(value, limits).value;\n}\n\n/**\n * Sanitizes arbitrary values and calculates approximate serialized byte sizes.\n * @param value Raw value to sanitize.\n * @param limits Configuration limits.\n * @returns SanitizeResult containing sanitized value and byte count.\n */\nexport function sanitizeWithSize(value: unknown, limits: SanitizeLimits): SanitizeResult {\n const state: WalkState = { bytes: 0, nodes: 0 };\n const result = walk(value, limits, new WeakSet(), 0, state);\n return { value: result, bytes: state.bytes };\n}\n\n/**\n * Adds string length and quotes overhead to size accumulator.\n * @param text Serialized string token.\n * @param state Byte size accumulator.\n * @returns Input text unchanged.\n */\nfunction counted(text: string, state: WalkState): string {\n state.bytes += estimateBytes(text) + BYTES_PER_QUOTED_STRING;\n return text;\n}\n\n/**\n * Recursively walks object trees, replacing cyclic references, hostile getters, and invalid primitives.\n * @param value Target value to sanitize.\n * @param limits Truncation and depth limits.\n * @param seen Set of active ancestor objects for cycle detection.\n * @param depth Current recursion depth.\n * @param state Running byte size accumulator.\n * @returns JSON-safe sanitized representation.\n */\nfunction walk(\n value: unknown,\n limits: SanitizeLimits,\n seen: WeakSet<object>,\n depth: number,\n state: WalkState,\n): unknown {\n state.nodes++;\n // The per-level limits cannot bound a wide tree: 128 keys over 6 levels is\n // 128^6 values, all walked synchronously on the main thread.\n if (state.nodes > limits.maxNodes) {\n return counted(\"[MaxNodes]\", state);\n }\n\n if (value === null || value === undefined) {\n state.bytes += BYTES_PER_NULL;\n return value;\n }\n\n if (typeof value === \"string\") {\n return counted(truncate(value, limits.maxAttributeChars), state);\n }\n if (typeof value === \"number\") {\n state.bytes += BYTES_PER_NUMBER;\n return Number.isFinite(value) ? value : String(value);\n }\n if (typeof value === \"boolean\") {\n state.bytes += BYTES_PER_BOOLEAN;\n return value;\n }\n if (typeof value === \"bigint\") {\n return counted(`${value.toString()}n`, state);\n }\n if (typeof value === \"symbol\") {\n return counted(value.toString(), state);\n }\n if (typeof value === \"function\") {\n return counted(`[Function ${value.name === \"\" ? \"anonymous\" : value.name}]`, state);\n }\n\n if (depth >= limits.maxDepth) {\n return counted(\"[MaxDepth]\", state);\n }\n\n if (seen.has(value)) {\n return counted(\"[Circular]\", state);\n }\n seen.add(value);\n state.bytes += BYTES_PER_CONTAINER;\n\n try {\n if (value instanceof Error) {\n return {\n name: counted(value.name, state),\n message: counted(truncate(value.message, limits.maxAttributeChars), state),\n stack: value.stack\n ? counted(truncate(value.stack, limits.maxStackChars), state)\n : undefined,\n cause: value.cause ? walk(value.cause, limits, seen, depth + 1, state) : undefined,\n };\n }\n if (value instanceof Date) {\n return counted(value.toISOString(), state);\n }\n if (value instanceof RegExp) {\n return counted(value.toString(), state);\n }\n if (value instanceof Map) {\n const map: ReadonlyMap<unknown, unknown> = value;\n const out: Record<string, unknown> = {};\n let shown = 0;\n for (const [key, entry] of map) {\n if (shown >= limits.maxArrayLength) {\n out[\"…\"] = counted(`[${String(map.size - limits.maxArrayLength)} more entries]`, state);\n break;\n }\n shown++;\n const name = String(key);\n state.bytes += estimateBytes(name) + BYTES_PER_KEY_OVERHEAD;\n out[name] = walk(entry, limits, seen, depth + 1, state);\n }\n return out;\n }\n if (value instanceof Set) {\n const set: ReadonlySet<unknown> = value;\n return walk([...set].slice(0, limits.maxArrayLength), limits, seen, depth, state);\n }\n if (ArrayBuffer.isView(value)) {\n const length = (value as { length?: number }).length ?? 0;\n return counted(`[${value.constructor.name}(${String(length)})]`, state);\n }\n if (value instanceof Promise) {\n return counted(\"[Promise]\", state);\n }\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n return counted(describeNode(value), state);\n }\n\n if (Array.isArray(value)) {\n const items: readonly unknown[] = value;\n const out: unknown[] = items\n .slice(0, limits.maxArrayLength)\n .map((item) => walk(item, limits, seen, depth + 1, state));\n if (items.length > limits.maxArrayLength) {\n out.push(counted(`[${String(items.length - limits.maxArrayLength)} more items]`, state));\n }\n return out;\n }\n\n const maybeToJson: unknown = (value as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJson === \"function\") {\n const toJson = maybeToJson as () => unknown;\n return walk(toJson.call(value), limits, seen, depth + 1, state);\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const out: Record<string, unknown> = {};\n let count = 0;\n for (const key of keys) {\n if (count >= limits.maxAttributeCount) {\n out[\"…\"] = counted(`[${String(keys.length - count)} more keys]`, state);\n break;\n }\n count++;\n state.bytes += estimateBytes(key) + BYTES_PER_KEY_OVERHEAD;\n out[key] = walk(record[key], limits, seen, depth + 1, state);\n }\n return out;\n } catch (error) {\n // Catches hostile getters and throwing proxies. One costs an attribute, not the\n // record.\n const name = error instanceof Error ? error.name : \"error\";\n return counted(`[Unserializable: ${name}]`, state);\n } finally {\n // Removes object from ancestor set on unwind. Left in, a repeated sibling reads\n // as a cycle.\n seen.delete(value);\n }\n}\n\n/**\n * Estimates UTF-8 encoded byte length for a string.\n * @param value Target string.\n * @returns Estimated UTF-8 byte length.\n */\nexport function estimateBytes(value: string): number {\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < UTF8_ONE_BYTE_CEILING) {\n bytes += 1;\n } else if (code < UTF8_TWO_BYTE_CEILING) {\n bytes += 2;\n } else if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n","// src/utils/identity.ts\n//\n// Generates and manages session, tab, and context correlation identifiers. Storage\n// throws rather than returning null in a sandboxed iframe and in private mode. An\n// unguarded read takes the library down at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * Uses crypto.getRandomValues when available, falling back to Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @returns UUID or random hex identifier.\n */\nexport function newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // Catches sandbox SecurityError throws when crypto.randomUUID is blocked. The\n // method is present; only the call fails.\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `reading ${store}Storage`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\"storage.unavailable\", `writing ${store}Storage`, () => {\n stores[store]().setItem(key, value);\n });\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId();\n const now = Date.now();\n\n let sessionId = newId();\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\"storage.degraded\", \"session record was not JSON, starting a new session\");\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId();\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the session's last-seen timestamp, throttled by `SESSION_TOUCH_MS`.\n * The throttle is instance state, not module state: two runtimes in one document\n * must not silence each other's session writes.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/deadline.ts\n//\n// Deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event, so its caller waits with it and holds the slot it took.\n\nimport { unrefTimer } from \"./unref\";\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`timed out after ${String(ms)}ms`));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Cleared on both paths. One armed timer for each storage call is waste.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// Deterministic record sampling based on namespace rules, journey IDs, and trace\n// IDs. Keyed on the journey, so one journey is kept or dropped whole. Stable\n// 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 SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/**\n * Computes 32-bit FNV-1a hash of a string value. Not 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 * Safely extracts a string attribute value from a log record. Absent and non-string\n * both read as empty. A forwarded record has only passed a shape check.\n * @param record Log record being evaluated.\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/**\n * Resolves sampling rate for a namespace using longest-prefix matching, so\n * trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig): number {\n const { rates, defaultRate } = config.sampling;\n let best: number | undefined;\n let bestLength = -1;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > bestLength) {\n best = rate;\n bestLength = prefix.length;\n }\n }\n\n return best ?? defaultRate;\n}\n\n/** Everything sampling reads, all of it known before a record is built. */\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, empty when no journey is running. */\n journeyId: string;\n /** Trace id, the sampling key when no journey is running. */\n traceId: string;\n}\n\n/**\n * Evaluates whether an entry should be sampled for retention. Takes the fields\n * rather than a record, so the verdict is available before the attribute walk\n * a dropped entry must not pay for.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @returns True if the entry should be retained and transmitted.\n */\nexport function shouldSampleInput(input: SampleInput, config: ResolvedConfig): 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 const rate = rateFor(input.namespace, config);\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Falls back to trace ID when journey ID is absent. The trace still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Evaluates whether a built log record should be sampled for retention. Used on\n * records that arrive already built, from a child context over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @returns True if the record should be retained and transmitted.\n */\nexport function shouldSample(record: LogRecord, config: ResolvedConfig): 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 );\n}\n\n/**\n * Fixed-window ceiling on the ERROR and FATAL records that bypass sampling.\n *\n * Auto-captured errors are already limited inside ErrorCapture. This covers the\n * case nothing else does: application code calling logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the window currently counting, 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 * Admits a record against the ceiling, counting only ERROR and FATAL.\n * @param record Record about to enter a stream.\n * @returns False when the window is spent and the record must be dropped.\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 // Fixed window, not a sliding one: a quiet spell banks 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":"8EAqDA,SAAgBY,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAWA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOC,GAAU,WAAYA,EAC/B,MAAO,GAKT,IAAMC,EAASD,EACf,OACE,OAAOC,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,CC1CA,SAAgBC,EAAS,EAA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